ExcelHelper.cs 3.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. using System;
  2. using System.Data;
  3. using System.IO;
  4. using System.Windows.Forms;
  5. namespace Core.StlMes.Client.Judge.Commons
  6. {
  7. public class ExcelHelper
  8. {
  9. public static DataTable ExcelToDataTable(bool isFirstRowColumn = true, bool isFirstRowTitle = true)
  10. {
  11. DataTable dt = new DataTable();
  12. string fileName = "";
  13. var openFileDialog = new OpenFileDialog
  14. {
  15. Filter = "外购熔炼成分|*.xls;*.xlsx"
  16. };
  17. if (openFileDialog.ShowDialog() == DialogResult.OK)
  18. {
  19. fileName = openFileDialog.FileName;
  20. }
  21. //excel工作表
  22. //NPOI.SS.UserModel.ISheet sheet = null;
  23. //数据开始行(排除标题行)
  24. int startRow = 0;
  25. try
  26. {
  27. if (!File.Exists(fileName))
  28. {
  29. return null;
  30. }
  31. //根据指定路径读取文件
  32. FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
  33. //根据文件流创建excel数据结构
  34. NPOI.SS.UserModel.IWorkbook workbook = NPOI.SS.UserModel.WorkbookFactory.Create(fs);
  35. //IWorkbook workbook = new HSSFWorkbook(fs);
  36. //sheet页数 workbook.NumberOfSheets
  37. for (int k = 0; k < 1; k++)
  38. {
  39. NPOI.SS.UserModel.ISheet sheet = workbook.GetSheetAt(k);
  40. if (sheet != null)
  41. {
  42. NPOI.SS.UserModel.IRow firstRow = sheet.GetRow(isFirstRowTitle ? 1 : 0);
  43. //一行最后一个cell的编号 即总的列数
  44. int cellCount = firstRow.LastCellNum;
  45. //如果第一行是标题列名
  46. if (isFirstRowColumn)
  47. {
  48. for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
  49. {
  50. NPOI.SS.UserModel.ICell cell = firstRow.GetCell(i);
  51. if (cell != null)
  52. {
  53. string cellValue = cell.StringCellValue;
  54. if (cellValue == null) break;
  55. dt.Columns.Add(cellValue);
  56. }
  57. }
  58. startRow = sheet.FirstRowNum + 1 + (isFirstRowTitle ? 1 : 0);
  59. }
  60. else
  61. {
  62. startRow = sheet.FirstRowNum;
  63. }
  64. //最后一列的标号
  65. int rowCount = sheet.LastRowNum;
  66. for (int i = startRow; i <= rowCount; ++i)
  67. {
  68. NPOI.SS.UserModel.IRow row = sheet.GetRow(i);
  69. if (row == null) continue; //没有数据的行默认是null       
  70. DataRow dr = dt.NewRow();
  71. for (int j = 0; j < dt.Columns.Count; j++)
  72. {
  73. if (row.GetCell(j) == null) continue;
  74. dr[j] = row.GetCell(j).ToString();
  75. }
  76. dt.Rows.Add(dr);
  77. }
  78. }
  79. }
  80. return dt;
  81. }
  82. catch (Exception ex)
  83. {
  84. MessageBox.Show("EXCEL格式错误:" + ex.Message);
  85. return null;
  86. }
  87. }
  88. }
  89. }