1、1.加载 Excel(读取 excel 内容)返回值是一个 DataSetcsharp view plaincopy1. /加载 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. OleDbConn
2、ection 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. OleC
3、onn.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. 2.写入 Excel 内容,参数:excelTable 是要导入 excel 的一个 table 表csharp view plaincopy1. public static
4、bool SaveDataTableToExcel(System.Data.DataTable excelTable, string filePath) 2. 3. Microsoft.Office.Interop.Excel.Application app = 4. new Microsoft.Office.Interop.Excel.ApplicationClass(); 5. try 6. 7. app.Visible = false; 8. Workbook wBook = app.Workbooks.Add(true); 9. Worksheet wSheet = wBook.Wor
5、ksheets1 as Worksheet; 10. if (excelTable.Rows.Count 0) 11. 12. int row = 0; 13. row = excelTable.Rows.Count; 14. int col = excelTable.Columns.Count; 15. for (int i = 0; i row; i+) 16. 17. for (int j = 0; j col; j+) 18. 19. string str = excelTable.Rowsij.ToString(); 20. wSheet.Cellsi + 2, j + 1 = st
6、r; 21. 22. 23. 24. 25. int size = excelTable.Columns.Count; 26. for (int i = 0; i size; i+) 27. 28. wSheet.Cells1, 1 + i = excelTable.Columnsi.ColumnName; 29. 30. /设置禁止弹出保存和覆盖的询问提示框 31. app.DisplayAlerts = false; 32. app.AlertBeforeOverwriting = false; 33. /保存工作簿 34. wBook.Save(); 35. /保存 excel 文件 3
7、6. app.Save(filePath); 37. app.SaveWorkspace(filePath); 38. app.Quit(); 39. app = null; 40. return true; 41. 42. catch (Exception err) 43. 44. MessageBox.Show(“导出 Excel 出错!错误原因:“ + err.Message, “提示信息“ , 45. MessageBoxButtons.OK, MessageBoxIcon.Information); 46. return false; 47. 48. finally 49. 50. 51.