ExcelUtil.cs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. using NPOI.HSSF.UserModel;
  2. using NPOI.SS.Formula;
  3. using NPOI.SS.UserModel;
  4. using NPOI.XSSF.UserModel;
  5. using System;
  6. using System.IO;
  7. using System.Linq;
  8. namespace YBEE.EQM.Core;
  9. /// <summary>
  10. /// Excel操作工具
  11. /// </summary>
  12. public static class ExcelUtil
  13. {
  14. /// <summary>
  15. /// 获取 Workbook 实例
  16. /// </summary>
  17. /// <param name="filePath"></param>
  18. /// <param name="fileStream"></param>
  19. /// <returns></returns>
  20. public static IWorkbook GetWorkbook(string filePath, FileStream fileStream)
  21. {
  22. string fileExt = Path.GetExtension(filePath).ToLower();
  23. if (fileExt == ".xls")
  24. {
  25. return new HSSFWorkbook(fileStream);
  26. }
  27. else
  28. {
  29. return new XSSFWorkbook(fileStream);
  30. }
  31. }
  32. /// <summary>
  33. /// 创建 Workbook
  34. /// </summary>
  35. /// <param name="filePath"></param>
  36. /// <returns></returns>
  37. public static IWorkbook GetWorkbook(string filePath)
  38. {
  39. string fileExt = Path.GetExtension(filePath).ToLower();
  40. if (fileExt == ".xls")
  41. {
  42. return new HSSFWorkbook();
  43. }
  44. else
  45. {
  46. return new XSSFWorkbook();
  47. }
  48. }
  49. /// <summary>
  50. /// 获取公式计算器
  51. /// </summary>
  52. /// <param name="workbook"></param>
  53. /// <returns></returns>
  54. public static BaseFormulaEvaluator GetEvaluator(IWorkbook workbook)
  55. {
  56. if (workbook is HSSFWorkbook)
  57. {
  58. return new HSSFFormulaEvaluator(workbook);
  59. }
  60. return new XSSFFormulaEvaluator(workbook);
  61. }
  62. /// <summary>
  63. /// 根据列索引获取字母列名
  64. /// </summary>
  65. /// <param name="index"></param>
  66. /// <returns></returns>
  67. public static string GetColumnNameByIndex(int index)
  68. {
  69. int num = index;
  70. var letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToArray();
  71. string str = "";
  72. while (num >= 0)
  73. {
  74. var n = letters[num % 26];
  75. str = $"{n}{str}";
  76. if (num == 0)
  77. {
  78. break;
  79. }
  80. num = (int)(Math.Floor(num * 1.0 / 26) - 1);
  81. }
  82. return str;
  83. }
  84. }