C# Excel導(dǎo)入相關(guān)知識(shí)總結(jié)
作者:佚名
Excel只能存儲(chǔ)65535行數(shù)據(jù),在使用C# Excel導(dǎo)入數(shù)據(jù)時(shí)需要注意這一問(wèn)題;另外,亂碼的問(wèn)題也值得我們關(guān)注。本文向您提供這兩種問(wèn)題的解決方法。
C# Excel導(dǎo)入有以下幾點(diǎn)需要我們注意:
1.C# Excel導(dǎo)入只能存儲(chǔ)65535行數(shù)據(jù),如果你的數(shù)據(jù)大于65535行,那么就需要將excel分割存放了。
2.C# Excel導(dǎo)入的亂碼,這主要是字符設(shè)置問(wèn)題。
1.加載Excel(讀取excel內(nèi)容)返回值是一個(gè)DataSet
- //加載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名稱(chēng),比如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;
- }
- }
2.C# Excel導(dǎo)入內(nèi)容,參數(shù):excelTable是要導(dǎo)入excel的一個(gè)table表
- public static bool SaveDataTableToExcel
- (System.Data.DataTable excelTable,
- string filePath)
- {
- Microsoft.Office.Interop.Excel.Application app =
- new Microsoft.Office.Interop.
- Excel.ApplicationClass();
- try
- {
- app.Visible = false;
- Workbook wBook = app.Workbooks.Add(true);
- Worksheet wSheet =
- wBook.Worksheets[1] as Worksheet;
- if (excelTable.Rows.Count 〉0)
- {
- int row = 0;
- row = excelTable.Rows.Count;
- int col = excelTable.Columns.Count;
- for (int i = 0; i < row; i++)
- {
- for (int j = 0; j < col; j++)
- {
- string str = excelTable.Rows[i][j].ToString();
- wSheet.Cells[i + 2, j + 1] = str;
- }
- }
- }
- int size = excelTable.Columns.Count;
- for (int i = 0; i < size; i++)
- {
- wSheet.Cells[1, 1 + i] = excelTable.
- Columns[i].ColumnName;
- }
- //設(shè)置禁止彈出保存和覆蓋的詢問(wèn)提示框
- app.DisplayAlerts = false;
- app.AlertBeforeOverwriting = false;
- //保存工作簿
- wBook.Save();
- //保存excel文件
- app.Save(filePath);
- app.SaveWorkspace(filePath);
- app.Quit();
- app = null;
- return true;
- }
- catch (Exception err)
- {
- MessageBox.Show("導(dǎo)出Excel出錯(cuò)!
- 錯(cuò)誤原因:" + err.Message, "提示信息",
- MessageBoxButtons.OK, MessageBoxIcon.
- Information);
- return false;
- }
- finally
- {
- }
【編輯推薦】
責(zé)任編輯:冰荷
來(lái)源:
hoopchina