PRovider根據實際EXCEL的版本來設置,推薦使用ACE接口來讀取。需要access database Engine。
注意修改注冊表以下兩項的值為0。否則導入EXCEL當單元格內字符長度超過255會發生截斷現象?。?!
HKEY_LOCAL_MACHINE/SOFTWARE/Microsoft/Office/12.0/AccessConnectivity Engine/Engines/Excel/TypeGuessRows
64位系統下
HKEY_LOCAL_MACHINE/SOFTWARE/Wow6432Node/Microsoft/Office/12.0/Access Connectivity Engine/Engines/Excel/ TypeGuessRows
看到論壇里面不斷有人提問關于讀取excel和導入excel的相關問題。閑暇時間將我所知道的對excel的操作加以總結,現在共享大家,希望給大家能夠給大家帶了一定的幫助。另外我們還要注意一些簡單的問題1.excel文件只能存儲65535行數據,如果你的數據大于65535行,那么就需要將excel分割存放了。2.關于亂碼,這主要是字符設置問題。
1.加載Excel(讀取excel內容)返回值是一個DataSet
[csharp]view plaincopy- //加載Excel
- publicstaticDataSetLoadDataFromExcel(stringfilePath)
- {
- try
- {
- stringstrConn;
- strConn="Provider=Microsoft.Jet.OLEDB.4.0;DataSource="+filePath+";ExtendedProperties='Excel8.0;HDR=False;IMEX=1'";
- OleDbConnectionOleConn=newOleDbConnection(strConn);
- OleConn.Open();
- Stringsql="SELECT*FROM[Sheet1$]";//可是更改Sheet名稱,比如sheet2,等等
- OleDbDataAdapterOleDaExcel=newOleDbDataAdapter(sql,OleConn);
- DataSetOleDsExcle=newDataSet();
- OleDaExcel.Fill(OleDsExcle,"Sheet1");
- OleConn.Close();
- returnOleDsExcle;
- }
- catch(Exceptionerr)
- {
- MessageBox.Show("數據綁定Excel失敗!失敗原因:"+err.Message,"提示信息",
- MessageBoxButtons.OK,MessageBoxIcon.Information);
- returnnull;
- }
- }
2.寫入Excel內容,參數:excelTable是要導入excel的一個table表
[csharp]view plaincopy- publicstaticboolSaveDataTableToExcel(System.Data.DataTableexcelTable,stringfilePath)
- {
- Microsoft.Office.Interop.Excel.applicationapp=
- newMicrosoft.Office.Interop.Excel.ApplicationClass();
- try
- {
- app.Visible=false;
- WorkbookwBook=app.Workbooks.Add(true);
- WorksheetwSheet=wBook.Worksheets[1]asWorksheet;
- if(excelTable.Rows.Count>0)
- {
- introw=0;
- row=excelTable.Rows.Count;
- intcol=excelTable.Columns.Count;
- for(inti=0;i<row;i++)
- {
- for(intj=0;j<col;j++)
- {
- stringstr=excelTable.Rows[i][j].ToString();
- wSheet.Cells[i+2,j+1]=str;
- }
- }
- }
- intsize=excelTable.Columns.Count;
- for(inti=0;i<size;i++)
- {
- wSheet.Cells[1,1+i]=excelTable.Columns[i].ColumnName;
- }
- //設置禁止彈出保存和覆蓋的詢問提示框
- app.DisplayAlerts=false;
- app.AlertBeforeOverwriting=false;
- //保存工作簿
- wBook.Save();
- //保存excel文件
- app.Save(filePath);
- app.SaveWorkspace(filePath);
- app.Quit();
- app=null;
- returntrue;
- }
- catch(Exceptionerr)
- {
- MessageBox.Show("導出Excel出錯!錯誤原因:"+err.Message,"提示信息",
- MessageBoxButtons.OK,MessageBoxIcon.Information);
- returnfalse;
- }
- finally
- {
- }
- }
轉載的朋友請一定注明出處謝謝!http://blog.csdn.net/gisfarmer/