C# Excel导入相关知识总结

C# Excel导入有以下几点需要我们注意:

1.C# Excel导入只能存储65535行数据,如果你的数据大于65535行,那么就需要将excel分割存放了。

2.C# Excel导入的乱码,这主要是字符设置问题。

1.加载Excel(读取excel内容)返回值是一个DataSet

 
 
 
  1. //加载Excel   
  2. public static DataSet LoadDataFromExcel  
  3. (string filePath)   
  4. {   
  5. try   
  6. {   
  7. string strConn;   
  8. strConn = "Provider=Microsoft.Jet.  
  9. OLEDB.4.0;Data Source=" +   
  10. filePath + ";Extended Properties='Excel   
  11. 8.0;HDR=False;IMEX=1'";   
  12. OleDbConnection OleConn =   
  13. new OleDbConnection(strConn);   
  14. OleConn.Open();   
  15. String sql = "SELECT * FROM    
  16. [Sheet1$]";//可是更改Sheet名称,比如sheet2,等等   
  17.  
  18. OleDbDataAdapter OleDaExcel =   
  19. new OleDbDataAdapter(sql, OleConn);   
  20. DataSet OleDsExcle = new DataSet();   
  21. OleDaExcel.Fill(OleDsExcle, "Sheet1");   
  22. OleConn.Close();   
  23. return OleDsExcle;   
  24. }   
  25. catch (Exception err)   
  26. {   
  27. MessageBox.Show("数据绑定Excel失败!  
  28. 失败原因:" + err.Message, "提示信息",   
  29. MessageBoxButtons.OK, MessageBoxIcon.Information);   
  30. return null;   
  31. }   

2.C# Excel导入内容,参数:excelTable是要导入excel的一个table表

 
 
 
  1. public static bool SaveDataTableToExcel  
  2. (System.Data.DataTable excelTable,   
  3. string filePath)   
  4. {   
  5. Microsoft.Office.Interop.Excel.Application app =   
  6. new Microsoft.Office.Interop.  
  7. Excel.ApplicationClass();   
  8. try   
  9. {   
  10. app.Visible = false;   
  11. Workbook wBook = app.Workbooks.Add(true);   
  12. Worksheet wSheet =   
  13. wBook.Worksheets[1] as Worksheet;   
  14. if (excelTable.Rows.Count 〉0)   
  15. {   
  16. int row = 0;   
  17. row = excelTable.Rows.Count;   
  18. int col = excelTable.Columns.Count;   
  19. for (int i = 0; i < row; i++)   
  20. {   
  21. for (int j = 0; j < col; j++)   
  22. {   
  23. string str = excelTable.Rows[i][j].ToString();   
  24. wSheet.Cells[i + 2, j + 1] = str;   
  25. }   
  26. }   
  27. }   
  28.  
  29. int size = excelTable.Columns.Count;   
  30. for (int i = 0; i < size; i++)   
  31. {   
  32. wSheet.Cells[1, 1 + i] = excelTable.  
  33. Columns[i].ColumnName;   
  34. }   
  35. //设置禁止弹出保存和覆盖的询问提示框   
  36. app.DisplayAlerts = false;   
  37. app.AlertBeforeOverwriting = false;   
  38. //保存工作簿   
  39. wBook.Save();   
  40. //保存excel文件   
  41. app.Save(filePath);   
  42. app.SaveWorkspace(filePath);   
  43. app.Quit();   
  44. app = null;   
  45. return true;   
  46. }   
  47. catch (Exception err)   
  48. {   
  49. MessageBox.Show("导出Excel出错!  
  50. 错误原因:" + err.Message, "提示信息",   
  51. MessageBoxButtons.OK, MessageBoxIcon.  
  52. Information);   
  53. return false;   
  54. }   
  55. finally   
  56. {   
  57. }  

【编辑推荐】

  1. C#中定义装箱和拆箱详解
  2. 浅谈C#类型系统
  3. 三种不同的C#异常类型
  4. 详细介绍C#编译器
  5. C#异常机制的相关解释
THE END