C#讀取Excel文件方法一:直接讀取(這種直接讀取單元格的方法釋放很重要) - Excel.Applicationexcel=null;
- Excel.Workbookswbs=null;
- Excel.Workbookwb=null;
- Excel.Worksheetws=null;
- Excel.Rangerange1=null;
- objectNothing=System.Reflection.Missing.Value;
-
- try
- {
- excel=newExcel.Application();
- excel.UserControl=true;
- excel.DisplayAlerts=false;
-
- excel.Application.Workbooks.Open(this.
- FilePath,Nothing,Nothing,Nothing,Nothing,
- Nothing,Nothing,Nothing,Nothing,Nothing,
- Nothing,Nothing,Nothing);
-
- wbs=excel.Workbooks;
- wb=wbs[1];
- ws=(Excel.Worksheet)wb.Worksheets["Sheet2"];
-
-
- introwCount=ws.UsedRange.Rows.Count;
- intcolCount=ws.UsedRange.Columns.Count;
- if(rowCount<=0)
- thrownewInvalidFormatException
- ("文件中沒(méi)有數(shù)據(jù)記錄");
- if(colCount<4)
- thrownewInvalidFormatException
- ("字段個(gè)數(shù)不對(duì)");
-
- for(inti=0;i{
- this.rowNo=i+1;
- object[]row=newobject[4];
- for(intj=0;j<4;j++)
- {
- range1=ws.get_Range(ws.Cells[i+2,j+1],
- ws.Cells[i+2,j+1]);
- row[j]=range1.Value;
-
- if(row[0]==null)
- {
- this.isNullRecord++;
- break;
- }
- }
-
- if(this.isNullRecord>0)
- continue;
-
- DataRowdataRow=this.readExcel(row);
-
- if(this.isNullRecord==1)
- continue;
-
- if(this.verifyData(dataRow)==false)
- errFlag++;
-
- this.updateTableCurr(dataRow);
- }
- }
- finally
- {
- if(excel!=null)
- {
- if(wbs!=null)
- {
- if(wb!=null)
- {
- if(ws!=null)
- {
- if(range1!=null)
- {
- System.Runtime.InteropServices.Marshal.
- ReleaseComObject(range1);
- range1=null;
- }
- System.Runtime.InteropServices.Marshal.
- ReleaseComObject(ws);
- ws=null;
- }
- wb.Close(false,Nothing,Nothing);
- System.Runtime.InteropServices.Marshal.
- ReleaseComObject(wb);
- wb=null;
- }
- wbs.Close();
- System.Runtime.InteropServices.Marshal.
- ReleaseComObject(wbs);
- wbs=null;
- }
- excel.Application.Workbooks.Close();
- excel.Quit();
- System.Runtime.InteropServices.Marshal.
- ReleaseComObject(excel);
- excel=null;
- GC.Collect();
- }
- }
C#讀取Excel文件方法二:通過(guò)OleDb連接,,把excel文件作為數(shù)據(jù)源來(lái)讀取(這里是fill進(jìn)dataset,,也可以返回OleDbDataReader來(lái)逐行讀,數(shù)據(jù)較快)
注:這種方法容易把混合型的字段作為null值讀取進(jìn)來(lái),,解決辦法是改造連接字符串 - strConn = "Provider=Microsoft.Jet.
- OLEDB.4.0;Data Source=C:\\Erp1912.xls;Extended
- Properties='Excel8.0;HDR=Yes;IMEX=1'";
通過(guò)Imex=1來(lái)把混合型作為文本型讀取,,避免null值,來(lái)實(shí)現(xiàn)C#讀取Excel文件 - privateDataSetimportExcelToDataSet
- (stringFilePath)
- {
- stringstrConn;
- strConn="Provider=Microsoft.Jet.
- OLEDB.4.0;"+"DataSource="+FilePath+";
- ExtendedProperties=Excel8.0;";
- OleDbConnectionconn=newOleDbConnection
- (strConn);
- OleDbDataAdaptermyCommand=newOleDbDataAdapter
- ("SELECT*FROM[Sheet1$]",strConn);
- DataSetmyDataSet=newDataSet();
- try
- {
- myCommand.Fill(myDataSet);
- }
- catch(Exceptionex)
- {
- thrownewInvalidFormatException
- ("該Excel文件的工作表的名字不正確,"+ex.Message);
- }
- returnmyDataSet;
- }
|