C读取excel.doc





《C读取excel.doc》由会员分享,可在线阅读,更多相关《C读取excel.doc(14页珍藏版)》请在淘文阁 - 分享文档赚钱的网站上搜索。
1、【精品文档】如有侵权,请联系网站删除,仅供学习与交流C读取excel.精品文档.C# 读取Excel文件代码的几种方法片段 1usingSystem.Data.OleDb;.staticvoidMain()Application.Run(newForm1();privatevoidForm1_Load(objectsender,System.EventArgse)DataTablemyT=ExcelToDataTable(D:/文件/新武昌站点资料.xls,sheet1);Stringmystr=myT.Rows00.ToString();this.textBox1.Text=mystr;pu
2、blicstaticDataTableExcelToDataTable(stringstrExcelFileName,stringstrSheetName)/源的定义stringstrConn=Provider=Microsoft.Jet.OLEDB.4.0;+DataSource=+strExcelFileName+;+ExtendedProperties=Excel8.0;HDR=NO;IMEX=1;/Sql语句/stringstrExcel=string.Format(select*from0$,strSheetName);这是一种方法stringstrExcel=select*from
3、sheet1$;/定义存放的数据表DataSetds=newDataSet();/连接数据源OleDbConnectionconn=newOleDbConnection(strConn);conn.Open();/适配到数据源OleDbDataAdapteradapter=newOleDbDataAdapter(strExcel,strConn);adapter.Fill(ds,strSheetName);conn.Close();returnds.TablesstrSheetName;很简单的代码,但是问题就出在连接字符串上面,后面一定要加上Extended Properties=Excel
4、 8.0;HDR=NO;IMEX=1,HDR和IMEX也一定要配合使用,哈哈,老实说,我也不知道为什么,这样配合的效果最好,这是我艰苦调试的结果.IMEX=1应该是将所有的列全部视为文本,我也有点忘记了.至于HDR本来只是说是否要出现一行标题头而已,但是结果却会导致某些字段值丢失,所以其实我至今也搞不明白为什么,很可能是驱动的问题.片段 2提供两种方法:一个是直接打开excel文件,然后逐行读取,速度较慢;还有一种方法是通过OleDb连接,把excel文件作为数据源来读取方法一:这种直接读取单元格的方法释放很重要。Excel.Applicationexcel=null;Excel.Workbo
5、okswbs=null;Excel.Workbookwb=null;Excel.Worksheetws=null;Excel.Rangerange1=null;objectNothing=System.Reflection.Missing.Value;tryexcel=newExcel.Application();excel.UserControl=true;excel.DisplayAlerts=false;excel.Application.Workbooks.Open(this.FilePath,Nothing,Nothing,Nothing,Nothing,Nothing,Nothin
6、g,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing);wbs=excel.Workbooks;wb=wbs1;ws=(Excel.Worksheet)wb.WorksheetsSheet2;introwCount=ws.UsedRange.Rows.Count;intcolCount=ws.UsedRange.Columns.Count;if(rowCount=0)thrownewInvalidFormatException(文件中没有数据记录);if(colCount4)thrownewInvalidFormatException(字段个数不对
7、);for(inti=0;ithis.rowNo=i+1;objectrow=newobject4;for(intj=0;j0)continue;DataRowdataRow=this.readExcel(row);if(this.isNullRecord=1)continue;if(this.verifyData(dataRow)=false)errFlag+;this.updateTableCurr(dataRow);finallyif(excel!=null)if(wbs!=null)if(wb!=null)if(ws!=null)if(range1!=null)System.Runti
8、me.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(
9、wbs);wbs=null;excel.Application.Workbooks.Close();excel.Quit();System.Runtime.InteropServices.Marshal.ReleaseComObject(excel);excel=null;GC.Collect();方法二:这里是fill进dataset,也可以返回OleDbDataReader来逐行读,数据较快注:这种方法容易把混合型的字段作为null值读取进来,解决办法是改造连接字符串strConn = Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:Erp19
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- 读取 excel

限制150内