ExcelLoader.cs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. using System;
  2. using System.IO;
  3. using System.Data;
  4. using ExcelDataReader;
  5. namespace excel2json {
  6. /// <summary>
  7. /// 将 Excel 文件(*.xls 或者 *.xlsx)加载到内存 DataSet
  8. /// </summary>
  9. class ExcelLoader {
  10. private DataSet mData;
  11. // TODO: add Sheet Struct Define
  12. public ExcelLoader(string filePath, int headerRow) {
  13. using (var stream = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) {
  14. // Auto-detect format, supports:
  15. // - Binary Excel files (2.0-2003 format; *.xls)
  16. // - OpenXml Excel files (2007 format; *.xlsx)
  17. using (var reader = ExcelReaderFactory.CreateReader(stream)) {
  18. // Use the AsDataSet extension method
  19. // The result of each spreadsheet is in result.Tables
  20. var result = reader.AsDataSet(createDataSetReadConfig(headerRow));
  21. this.mData = result;
  22. }
  23. }
  24. if (this.Sheets.Count < 1) {
  25. throw new Exception("Excel file is empty: " + filePath);
  26. }
  27. }
  28. public DataTableCollection Sheets {
  29. get {
  30. return this.mData.Tables;
  31. }
  32. }
  33. private ExcelDataSetConfiguration createDataSetReadConfig(int headerRow) {
  34. var tableConfig = new ExcelDataTableConfiguration() {
  35. // Gets or sets a value indicating whether to use a row from the
  36. // data as column names.
  37. UseHeaderRow = true,
  38. // Gets or sets a callback to determine whether to include the
  39. // current row in the DataTable.
  40. //FilterRow = (rowReader) => {
  41. // return rowReader.Depth > headerRow - 1;
  42. //},
  43. };
  44. return new ExcelDataSetConfiguration() {
  45. // Gets or sets a value indicating whether to set the DataColumn.DataType
  46. // property in a second pass.
  47. UseColumnDataType = true,
  48. // Gets or sets a callback to obtain configuration options for a DataTable.
  49. ConfigureDataTable = (tableReader) => { return tableConfig; },
  50. };
  51. }
  52. }
  53. }