NPOIOperate.cs 3.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. using NPOI.HSSF.UserModel;
  2. using NPOI.SS.UserModel;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Data;
  6. using System.Globalization;
  7. using System.IO;
  8. using System.Linq;
  9. using System.Text;
  10. using System.Threading;
  11. using System.Threading.Tasks;
  12. namespace MainForm.ClassFile
  13. {
  14. public class NPOIOperate
  15. {
  16. private static Mutex mutex = new Mutex();
  17. /// <summary>
  18. /// 向已存在的excel写入数据
  19. /// </summary>
  20. /// <param name="fileName">excel路径</param>
  21. /// <param name="headData">列索引<列索引,单元格值></param>
  22. /// <param name="cellData">列索引<列索引,单元格值></param>
  23. public static string AddExcelData(string fileName, IDictionary<int, string> headData, IDictionary<int, string> cellData)
  24. {
  25. mutex.WaitOne();
  26. string ret = string.Empty;
  27. FileStream fileRead = null;
  28. FileStream fileWrite = null;
  29. try
  30. {
  31. if (!File.Exists(fileName))
  32. CreateExcel(fileName, headData);
  33. IWorkbook workbook = null;
  34. //读
  35. fileRead = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
  36. workbook = new HSSFWorkbook(fileRead);
  37. ISheet sheet = workbook.GetSheetAt(0);
  38. IRow row = sheet.CreateRow(sheet.LastRowNum + 1);
  39. ICell cell = null;
  40. foreach (KeyValuePair<int, string> keyValue in cellData)
  41. {
  42. cell = row.CreateCell(keyValue.Key);
  43. cell.SetCellValue(keyValue.Value);
  44. } //写
  45. fileWrite = new FileStream(fileName, FileMode.Open, FileAccess.Write, FileShare.ReadWrite);
  46. workbook.Write(fileWrite);
  47. workbook.Close();
  48. ret = "写入成功";
  49. }
  50. catch(Exception ex)
  51. {
  52. ret = ex.Message.ToString();
  53. }
  54. finally
  55. {
  56. fileRead?.Close();
  57. fileWrite?.Close();
  58. }
  59. mutex.ReleaseMutex();
  60. return ret;
  61. }
  62. /// <summary>
  63. /// 创建excel写入头
  64. /// </summary>
  65. /// <param name="fileName"></param>
  66. /// <param name="headData"></param>
  67. public static void CreateExcel(string fileName, IDictionary<int, string> headData)
  68. {
  69. using (FileStream fileWrite = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read))
  70. {
  71. IWorkbook workbook = new HSSFWorkbook();
  72. ISheet sheet = workbook.CreateSheet("加工数据");//获取工作表
  73. IRow row = sheet.CreateRow(0); //创建新行
  74. ICell cell = null;
  75. foreach (KeyValuePair<int, string> keyValue in headData)
  76. {
  77. cell = row.CreateCell(keyValue.Key);
  78. cell.SetCellValue(keyValue.Value);
  79. }
  80. workbook.Write(fileWrite);
  81. workbook.Close();
  82. }
  83. }
  84. }
  85. }