a .NET library that can read/write Office formats without Microsoft Office installed. No COM+, no interop.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

78 lines
1.9 KiB

7 months ago
  1. using BenchmarkDotNet.Attributes;
  2. using NPOI.HSSF.UserModel;
  3. using NPOI.SS.UserModel;
  4. namespace NPOI.Benchmarks;
  5. [SimpleJob]
  6. public class DataFormatReadBenchmark
  7. {
  8. private const string dateFormat = "yyyy/MM/dd";
  9. private const string timeFormat = "HH:mm:ss";
  10. private HSSFWorkbook workbook;
  11. private ISheet sheet1;
  12. [Params(1_000)]
  13. public int RowCount { get; set; }
  14. [GlobalSetup]
  15. public void Setup()
  16. {
  17. workbook = new HSSFWorkbook();
  18. Write(workbook);
  19. }
  20. private void Write(HSSFWorkbook wb)
  21. {
  22. var time = DateTime.UtcNow.AddYears(-1);
  23. IDataFormat df = wb.CreateDataFormat();
  24. var dateStyle = wb.CreateCellStyle();
  25. dateStyle.DataFormat = df.GetFormat(dateFormat);
  26. var timeStyle = wb.CreateCellStyle();
  27. timeStyle.DataFormat = df.GetFormat(timeFormat);
  28. ISheet sheet = wb.CreateSheet();
  29. for(var i = 0; i<RowCount; i++)
  30. {
  31. IRow row = sheet.CreateRow(i);
  32. ICell cellA = row.CreateCell(0);
  33. cellA.SetCellValue(time);
  34. cellA.CellStyle = dateStyle;
  35. ICell cellB = row.CreateCell(1);
  36. cellB.SetCellValue(time);
  37. cellB.CellStyle = timeStyle;
  38. time = time.AddHours(1);
  39. }
  40. }
  41. [Benchmark]
  42. public void Read()
  43. {
  44. DataFormatter df = new DataFormatter();
  45. ISheet sheet = workbook.GetSheetAt(0);
  46. var numRows = sheet.LastRowNum;
  47. for(var r = 0; r<=numRows; r++)
  48. {
  49. IRow row = sheet.GetRow(r);
  50. var numCells = row.LastCellNum;
  51. var readRow = new string[numCells];
  52. for(var c = 0; c<numCells; c++)
  53. {
  54. ICell cell = row.GetCell(c);
  55. if(cell is null) continue;
  56. readRow[c] = df.FormatCellValue(cell);
  57. }
  58. }
  59. }
  60. [GlobalCleanup]
  61. public void Cleanup()
  62. {
  63. workbook.Dispose();
  64. }
  65. }