.Net平台上对Excel进行操作主要有两种方式。第一种,把Excel文件看成一个数据库,通过OleDb的方式进行读取与操作;第二种,调用Excel的COM组件。两种方式各有特点。
注意一些简单的问题1.excel文件只能存储65535行数据,如果你的数据大于65535行,那么就需要将excel分割存放了。2.关于乱码,这主要是字符设置问题。
一、OleDb方式
读取Excel文件
1 //加载Excel 2 public static DataSet LoadDataFromExcel(string filePath) 3 { 4 try 5 { 6 string strConn; 7 strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties='Excel 8.0;HDR=False;IMEX=1'"; 8 OleDbConnection OleConn = new OleDbConnection(strConn); 9 OleConn.Open(); 10 String sql = "SELECT * FROM [Sheet1$]";//可是更改Sheet名称,比如sheet2,等等 11 12 OleDbDataAdapter OleDaExcel = new OleDbDataAdapter(sql, OleConn); 13 DataSet OleDsExcle = new DataSet(); 14 OleDaExcel.Fill(OleDsExcle, "Sheet1"); 15 OleConn.Close(); 16 return OleDsExcle; 17 } 18 catch (Exception err) 19 { 20 MessageBox.Show("数据绑定Excel失败!失败原因:" + err.Message, "提示信息", 21 MessageBoxButtons.OK, MessageBoxIcon.Information); 22 return null; 23 } 24 }
访问.xls的文件使用的是“Microsoft.Jet.OLEDB.4.0”,访问.xlsx的文件使用的是“Microsoft.Ace.OleDb.12.0”
写入excel文件
1 /// 2 /// 写入Excel文档 3 /// 4 public bool SaveFP2toExcel(string filePathath) 5 { 6 try 7 { 8 string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+ filePathath +";Extended Properties=Excel 8.0;"; 9 OleDbConnection conn = new OleDbConnection(strConn); 10 conn.Open(); 11 System.Data.OleDb.OleDbCommand cmd=new OleDbCommand (); 12 cmd.Connection =conn; 13 14 for(int i=0;i0].RowCount -1;i++) 15 { 16 if(fp2.Sheets [0].Cells[i,0].Text!="") 17 { 18 cmd.CommandText ="INSERT INTO [sheet1$] (工号,姓名,部门,职务,日期,时间) VALUES('"+fp2.Sheets [0].Cells[i,0].Text+ "','"+ 19 fp2.Sheets [0].Cells[i,1].Text+"','"+fp2.Sheets [0].Cells[i,2].Text+"','"+fp2.Sheets [0].Cells[i,3].Text+ 20 "','"+fp2.Sheets [0].Cells[i,4].Text+"','"+fp2.Sheets [0].Cells[i,5].Text+"')"; 21 cmd.ExecuteNonQuery (); 22 } 23 } 24 25 conn.Close (); 26 return true; 27 } 28 catch(System.Data.OleDb.OleDbException ex) 29 { 30 Console.WriteLine ("写入Excel发生错误:"+ex.Message ); 31 return false; 32 } 33 }
二、Excel COM组件
一个.NET组件事实上是一个.NET下的DLL,它包含的不仅是运行程序本身,更重要的是包含这个DLL的描述信息(Meta Data,即元数据),而一个COM组件是用其类库(TLB)储存其描述信息。这些COM组件都是非受管代码,要在Visual C#中使用这些非受管代码的COM组件,就必须把他们转换成受管代码的.NET组件。所以在用Visual C#调用Excel表格之前,必须完成从COM组件的非受管代码到受管代码的类库的转换。
添加COM组件
Create an Automation Client for Microsoft Excel
Start Microsoft Visual Studio .NET.
On the File menu, click New, and then click Project. Select Windows Application from the Visual C# Project types. Form1 is created by default.
Add a reference to the Microsoft Excel Object Library. To do this, follow these steps:
On the Project menu, click Add Reference.
On the COM tab, locate Microsoft Excel Object Library, and click Select.
Click OK in the Add References dialog box to accept your selections. If you are prompted to generate wrappers for the libraries that you selected, click Yes.
using Excel = Microsoft.Office.Interop.Excel;
读取Excel文件
1 private void button1_Click(object sender, EventArgs e) 2 { 3 Excel.Application xlApp ; 4 Excel.Workbook xlWorkBook ; 5 Excel.Worksheet xlWorkSheet ; 6 Excel.Range range ; 7 8 string str; 9 int rCnt = 0; 10 int cCnt = 0; 11 12 xlApp = new Excel.Application(); 13 xlWorkBook = xlApp.Workbooks.Open("csharp.net-informations.xls"); 14 xlWorkSheet = xlWorkBook.Sheets["Sheet1"]; 15 16 range = xlWorkSheet.UsedRange; 17 18 for (rCnt = 1; rCnt <= range.Rows.Count; rCnt++) 19 { 20 for (cCnt = 1; cCnt <= range.Columns.Count; cCnt++) 21 { 22 str = (string)(range.Cells[rCnt, cCnt] as Excel.Range).Value2 ; 23 MessageBox.Show(str); 24 } 25 } 26 27 xlWorkBook.Close(true, null, null); 28 xlApp.Quit(); 29 }
写入Excel文件
1 private void button1_Click(object sender, EventArgs e) 2 { 3 Excel.Application xlApp ; 4 Excel.Workbook xlWorkBook ; 5 Excel.Worksheet xlWorkSheet ; 6 object misValue = System.Reflection.Missing.Value; 7 8 xlApp = new Excel.Application(); 9 xlWorkBook = xlApp.Workbooks.Add(misValue); 10 xlWorkSheet = xlWorkBook.Sheets["Sheet1"]; 11 12 //add some text 13 xlWorkSheet.Cells[1, 1] = "http://csharp.net-informations.com"; 14 xlWorkSheet.Cells[2, 1] = "Adding picture in Excel File"; 15 16 xlWorkBook.SaveAs("csharp.net-informations.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue); 17 xlWorkBook.Close(true, misValue, misValue); 18 xlApp.Quit(); 19 20 MessageBox.Show ("File created !"); 21 }
主要参考:http://csharp.net-informations.com/excel/files/download/csharp-open-excel_download.htm
三、第三方插件-NPOI
摘要: NPOI,顾名思义,就是POI的.NET版本。那POI又是什么呢?POI是一套用Java写成的库,能够帮助开发者在没有安装微软Office的情况下读写Office 97-2003的文件,支持的文件格式包括xls, doc, ppt等。在本文发布时,NPOI的最新版本是2.2.1。
NPOI网址 http://npoi.codeplex.com/