ExcelHelper.cs 3.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. using Aitex.Core.RT.Log;
  8. using DocumentFormat.OpenXml;
  9. using DocumentFormat.OpenXml.Packaging;
  10. using DocumentFormat.OpenXml.Spreadsheet;
  11. namespace MECF.Framework.Common.Utilities
  12. {
  13. public class ExcelHelper
  14. {
  15. public static bool ExportToExcel(string filepath, DataSet ds, out string reason)
  16. {
  17. reason = string.Empty;
  18. try
  19. {
  20. SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Create(filepath, SpreadsheetDocumentType.Workbook);
  21. WorkbookPart workbookpart = spreadsheetDocument.AddWorkbookPart();
  22. workbookpart.Workbook = new Workbook();
  23. WorksheetPart worksheetPart = workbookpart.AddNewPart<WorksheetPart>();
  24. worksheetPart.Worksheet = new Worksheet(new SheetData());
  25. Sheets sheets = spreadsheetDocument.WorkbookPart.Workbook.AppendChild<Sheets>(new Sheets());
  26. for (int i = 0; i < ds.Tables.Count; i++)
  27. {
  28. Sheet sheet = new Sheet()
  29. {
  30. Id = spreadsheetDocument.WorkbookPart.GetIdOfPart(worksheetPart),
  31. SheetId = 1,
  32. Name = ds.Tables[i].TableName,
  33. };
  34. sheets.Append(sheet);
  35. var sheetData = worksheetPart.Worksheet.GetFirstChild<SheetData>();
  36. for (int row = 0; row < ds.Tables[i].Rows.Count; row++)
  37. {
  38. Row rowData = new Row();
  39. for (int col = 0; col < ds.Tables[i].Columns.Count; col++)
  40. {
  41. if (row == 0)
  42. {
  43. Cell titleCell = new Cell();
  44. titleCell.CellValue = new CellValue(ds.Tables[i].Columns[col].Caption);
  45. titleCell.DataType = new EnumValue<CellValues>(CellValues.String);
  46. rowData.Append(titleCell);
  47. continue;
  48. }
  49. Cell dataCell = new Cell();
  50. var data = ds.Tables[i].Rows[row][col];
  51. if (data is DateTime time)
  52. {
  53. dataCell.CellValue = new CellValue(time);
  54. dataCell.DataType = new EnumValue<CellValues>(CellValues.String);
  55. }
  56. else if (data is double value)
  57. {
  58. dataCell.CellValue = new CellValue(data.ToString());
  59. dataCell.DataType = new EnumValue<CellValues>(CellValues.Number);
  60. }
  61. else
  62. {
  63. dataCell.CellValue = new CellValue(data.ToString());
  64. dataCell.DataType = new EnumValue<CellValues>(CellValues.String);
  65. }
  66. rowData.Append(dataCell);
  67. }
  68. sheetData.Append(rowData);
  69. }
  70. }
  71. workbookpart.Workbook.Save();
  72. spreadsheetDocument.Close();
  73. }
  74. catch (Exception ex)
  75. {
  76. LOG.WriteExeption(ex);
  77. reason = ex.Message;
  78. return false;
  79. }
  80. return true;
  81. }
  82. }
  83. }