C#操作Excel文件
.Net平臺上對Excel進(jìn)行操作主要有兩種方式。第一種,把Excel文件看成一個數(shù)據(jù)庫,通過OleDb的方式進(jìn)行讀取與操作;第二種,調(diào)用Excel的COM組件。兩種方式各有特點。
注意一些簡單的問題1.excel文件只能存儲65535行數(shù)據(jù),如果你的數(shù)據(jù)大于65535行,那么就需要將excel分割存放了。2.關(guān)于亂碼,這主要是字符設(shè)置問題。
一、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("數(shù)據(jù)綁定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$] (工號,姓名,部門,職務(wù),日期,時間) 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發(fā)生錯誤:"+ex.Message );
return false;
}
}
二、Excel COM組件
一個.NET組件事實上是一個.NET下的DLL,它包含的不僅是運行程序本身,更重要的是包含這個DLL的描述信息(Meta Data,即元數(shù)據(jù)),而一個COM組件是用其類庫(TLB)儲存其描述信息。這些COM組件都是非受管代碼,要在Visual C#中使用這些非受管代碼的COM組件,就必須把他們轉(zhuǎn)換成受管代碼的.NET組件。所以在用Visual C#調(diào)用Excel表格之前,必須完成從COM組件的非受管代碼到受管代碼的類庫的轉(zhuǎn)換。
添加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
總結(jié)
以上是生活随笔為你收集整理的C#操作Excel文件的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【开源】OSharp3.0框架解说系列(
- 下一篇: c# char unsigned_dll