這篇文章主要講解了“怎么用C#讀取Excel文件”,文中的講解內容簡單清晰,易于學習與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學習“怎么用C#讀取Excel文件”吧!
創新互聯公司是一家專注網站建設、網絡營銷策劃、小程序制作、電子商務建設、網絡推廣、移動互聯開發、研究、服務為一體的技術型公司。公司成立十多年以來,已經為上千家成都資質代辦各業的企業公司提供互聯網服務。現在,服務的上千家客戶與我們一路同行,見證我們的成長;未來,我們一起分享成功的喜悅。
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 ("文件中沒有數據記錄"); if(colCount<4) thrownewInvalidFormatException ("字段個數不對"); 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文件方法二:通過OleDb連接,把excel文件作為數據源來讀取(這里是fill進dataset,也可以返回OleDbDataReader來逐行讀,數據較快)
注:這種方法容易把混合型的字段作為null值讀取進來,解決辦法是改造連接字符串
strConn = "Provider=Microsoft.Jet. OLEDB.4.0;Data Source=C:\\Erp1912.xls;Extended Properties='Excel8.0;HDR=Yes;IMEX=1'";
通過Imex=1來把混合型作為文本型讀取,避免null值,來實現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; }
感謝各位的閱讀,以上就是“怎么用C#讀取Excel文件”的內容了,經過本文的學習后,相信大家對怎么用C#讀取Excel文件這一問題有了更深刻的體會,具體使用情況還需要大家實踐驗證。這里是創新互聯,小編將為大家推送更多相關知識點的文章,歡迎關注!