.Net平台上对Excel进行操作主要有两种方式。第一种,把Excel文件看成一个数据库,通过OleDb的方式进行读取与操作;第二种,调用Excel的COM组件。两种方式各有特点。
注意一些简单的问题1.excel文件只能存储65535行数据,如果你的数据大于65535行,那么就需要将excel分割存放了。2.关于乱码,这主要是字符设置问题。
一、OleDb方式
- 读取Excel文件
//加载Excel
public static DataSet LoadDataFromExcel(string filePath)
{
try
{
string strConn;
strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties='Excel 8.0;HDR=False;IMEX=1'";
OleDbConnection OleConn = new OleDbConnection(strConn);
OleConn.Open();
String sql = "SELECT * FROM [Sheet1$]";//可是更改Sheet名称,比如sheet2,等等 OleDbDataAdapter OleDaExcel = new OleDbDataAdapter(sql, OleConn);
DataSet OleDsExcle = new DataSet();
OleDaExcel.Fill(OleDsExcle, "Sheet1");
OleConn.Close();
return OleDsExcle;
}
catch (Exception err)
{
MessageBox.Show("数据绑定Excel失败!失败原因:" + err.Message, "提示信息",
MessageBoxButtons.OK, MessageBoxIcon.Information);
return null;
}
}
访问.xls的文件使用的是“Microsoft.Jet.OLEDB.4.0”,访问.xlsx的文件使用的是“Microsoft.Ace.OleDb.12.0”
- 写入excel文件
/// <summary>
/// 写入Excel文档
/// </summary>
public bool SaveFP2toExcel(string filePathath)
{
try
{
string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+ filePathath +";Extended Properties=Excel 8.0;";
OleDbConnection conn = new OleDbConnection(strConn);
conn.Open();
System.Data.OleDb.OleDbCommand cmd=new OleDbCommand ();
cmd.Connection =conn; for(int i=;i<fp2.Sheets [].RowCount -;i++)
{
if(fp2.Sheets [].Cells[i,].Text!="")
{
cmd.CommandText ="INSERT INTO [sheet1$] (工号,姓名,部门,职务,日期,时间) VALUES('"+fp2.Sheets [].Cells[i,].Text+ "','"+
fp2.Sheets [].Cells[i,].Text+"','"+fp2.Sheets [].Cells[i,].Text+"','"+fp2.Sheets [].Cells[i,].Text+
"','"+fp2.Sheets [].Cells[i,].Text+"','"+fp2.Sheets [].Cells[i,].Text+"')";
cmd.ExecuteNonQuery ();
}
} conn.Close ();
return true;
}
catch(System.Data.OleDb.OleDbException ex)
{
Console.WriteLine ("写入Excel发生错误:"+ex.Message );
return false;
}
}
二、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文件
private void button1_Click(object sender, EventArgs e)
{
Excel.Application xlApp ;
Excel.Workbook xlWorkBook ;
Excel.Worksheet xlWorkSheet ;
Excel.Range range ; string str;
int rCnt = ;
int cCnt = ; xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Open("csharp.net-informations.xls");
xlWorkSheet = xlWorkBook.Sheets["Sheet1"]; range = xlWorkSheet.UsedRange; for (rCnt = ; rCnt <= range.Rows.Count; rCnt++)
{
for (cCnt = ; cCnt <= range.Columns.Count; cCnt++)
{
str = (string)(range.Cells[rCnt, cCnt] as Excel.Range).Value2 ;
MessageBox.Show(str);
}
} xlWorkBook.Close(true, null, null);
xlApp.Quit();
}
- 写入Excel文件
private void button1_Click(object sender, EventArgs e)
{
Excel.Application xlApp ;
Excel.Workbook xlWorkBook ;
Excel.Worksheet xlWorkSheet ;
object misValue = System.Reflection.Missing.Value; xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = xlWorkBook.Sheets["Sheet1"]; //add some text
xlWorkSheet.Cells[, ] = "http://csharp.net-informations.com";
xlWorkSheet.Cells[, ] = "Adding picture in Excel File"; xlWorkBook.SaveAs("csharp.net-informations.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit(); MessageBox.Show ("File created !");
}
主要参考: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/