.net6.0 webapi demo

NpoiHelper.cs 9.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. using NPOI.HSSF.UserModel;
  2. using NPOI.HSSF.Util;
  3. using NPOI.SS.UserModel;
  4. using NPOI.XSSF.UserModel;
  5. using System.Globalization;
  6. using System.Reflection;
  7. namespace Net6Demo_Api.Util
  8. {
  9. public class NpoiHelper
  10. {
  11. /// <summary>
  12. /// 导出excel
  13. /// </summary>
  14. /// <typeparam name="T"></typeparam>
  15. /// <param name="suffix">excel后缀(.xls/.xlsx)</param>
  16. /// <param name="list">列表</param>
  17. /// <param name="cols">列属性</param>
  18. /// <param name="colnames">列属性名</param>
  19. /// <returns></returns>
  20. public static byte[] ExportToExcel<T>(string suffix, List<T> list, string[] cols = null, string[] colnames = null)
  21. {
  22. IWorkbook workbook = new HSSFWorkbook();
  23. if (suffix == ".xlsx")
  24. {
  25. workbook = new XSSFWorkbook();
  26. }
  27. try
  28. {
  29. //表头样式
  30. ICellStyle HeadercellStyle = workbook.CreateCellStyle();
  31. HeadercellStyle.BorderBottom = BorderStyle.Thin;
  32. HeadercellStyle.BorderLeft = BorderStyle.Thin;
  33. HeadercellStyle.BorderRight = BorderStyle.Thin;
  34. HeadercellStyle.BorderTop = BorderStyle.Thin;
  35. HeadercellStyle.Alignment = HorizontalAlignment.Center;
  36. HeadercellStyle.FillForegroundColor = HSSFColor.SkyBlue.Index;
  37. HeadercellStyle.FillPattern = FillPattern.SolidForeground;
  38. HeadercellStyle.FillBackgroundColor = HSSFColor.SkyBlue.Index;
  39. //字体
  40. IFont headerfont = workbook.CreateFont();
  41. headerfont.Boldweight = (short)FontBoldWeight.Bold;
  42. headerfont.FontHeightInPoints = 12;
  43. HeadercellStyle.SetFont(headerfont);
  44. int iRowIndex = 0;
  45. ISheet sheet = workbook.CreateSheet();
  46. IRow headerRow = sheet.CreateRow(0);
  47. var cls = typeof(T).GetProperties();
  48. if (colnames == null || (colnames != null && colnames.Length == 0))
  49. {
  50. if (cols == null || (cols != null && cols.Length == 0))
  51. {
  52. colnames = cls.Select(p => p.Name).ToArray();
  53. }
  54. else
  55. {
  56. colnames = cols;
  57. }
  58. }
  59. for (int c = 0; c < colnames.Length; c++)
  60. {
  61. ICell cell = headerRow.CreateCell(c);
  62. cell.SetCellValue(colnames[c]);
  63. cell.CellStyle = HeadercellStyle;
  64. }
  65. if (list.Count > 0)
  66. {
  67. //内容行样式
  68. ICellStyle cellStyle = workbook.CreateCellStyle();
  69. //为避免日期格式被Excel自动替换,所以设定 format 为 『@』 表示一率当成text來看
  70. cellStyle.DataFormat = HSSFDataFormat.GetBuiltinFormat("@");
  71. cellStyle.BorderBottom = BorderStyle.Thin;
  72. cellStyle.BorderLeft = BorderStyle.Thin;
  73. cellStyle.BorderRight = BorderStyle.Thin;
  74. cellStyle.BorderTop = BorderStyle.Thin;
  75. //字体
  76. IFont cellfont = workbook.CreateFont();
  77. cellfont.Boldweight = (short)FontBoldWeight.Normal;
  78. cellStyle.SetFont(cellfont);
  79. for (int i = 0; i < list.Count; i++)
  80. {
  81. if (suffix != ".xlsx")//excel2003超过60000进行分sheet
  82. {
  83. if (i % 60000 == 0 && i > 0)
  84. {
  85. //if (i > 0)
  86. //{
  87. // //自适应列宽度
  88. // for (int j = 0; j < icolIndex; j++)
  89. // {
  90. // sheet.AutoSizeColumn(j);
  91. // }
  92. //}
  93. iRowIndex = 0;
  94. sheet = workbook.CreateSheet();
  95. headerRow = sheet.CreateRow(0);
  96. for (int c = 0; c < colnames.Length; c++)
  97. {
  98. ICell cell = headerRow.CreateCell(c);
  99. cell.SetCellValue(colnames[c]);
  100. cell.CellStyle = HeadercellStyle;
  101. }
  102. }
  103. }
  104. IRow irow = sheet.CreateRow(iRowIndex + 1);
  105. for (int j = 0; j < colnames.Length; j++)
  106. {
  107. var clsi = cls[j];
  108. string strsj = string.Empty;
  109. if (cols != null && cols.Length > 0)
  110. {
  111. clsi = cls.Where(p => p.Name == cols[j]).FirstOrDefault();
  112. }
  113. strsj = clsi.GetValue(list[i], null)?.ToString() ?? "";
  114. ICell cell = irow.CreateCell(j);
  115. cell.SetCellValue(strsj);
  116. cell.CellStyle = cellStyle;
  117. }
  118. iRowIndex++;
  119. }
  120. }
  121. byte[] data = null;
  122. using (MemoryStream ms = new MemoryStream())
  123. {
  124. workbook.Write(ms);
  125. data = ms.GetBuffer();
  126. ms.Close();
  127. }
  128. return data;
  129. }
  130. catch (Exception ex)
  131. {
  132. LogHelper.Error("导出失败!", ex);
  133. return null;
  134. }
  135. }
  136. /// <summary>
  137. /// 导入excel转换为list
  138. /// </summary>
  139. /// <param name="stream">文件流</param>
  140. /// <param name="suffix">后缀名</param>
  141. /// <param name="headrow">标题行数(默认0代表第一行)</param>
  142. /// <returns></returns>
  143. public static List<T> ExcelToList<T>(Stream stream, string suffix, int headrow=0) where T : new()
  144. {
  145. List<T> list = new List<T>();
  146. IWorkbook workbook = null;
  147. if (suffix == ".xlsx") // 2007版本
  148. {
  149. workbook = new XSSFWorkbook(stream);
  150. }
  151. else if (suffix == ".xls") // 2003版本
  152. {
  153. workbook = new HSSFWorkbook(stream);
  154. }
  155. //获取excel的第一个sheet
  156. ISheet sheet = workbook.GetSheetAt(0);
  157. //获取sheet的第一行
  158. IRow headerRow = sheet.GetRow(headrow);
  159. //一行最后一个方格的编号 即总的列数
  160. int cellCount = headerRow.LastCellNum;
  161. //最后一列的标号 即总的行数
  162. int rowCount = sheet.LastRowNum;
  163. //获取泛型对象T的所有属性
  164. var cls = typeof(T).GetProperties();
  165. for (int i = (sheet.FirstRowNum + headrow + 1); i <= sheet.LastRowNum; i++)
  166. {
  167. var obj = new T();
  168. IRow row = sheet.GetRow(i);
  169. for (int j = row.FirstCellNum; j < cellCount; j++)
  170. {
  171. if (row.GetCell(j) != null)
  172. {
  173. var value = row.GetCell(j).ToString();
  174. string str = cls[j].PropertyType.FullName ?? "";
  175. if (str.Contains("System.String") )
  176. {
  177. cls[j].SetValue(obj, value, null);
  178. }
  179. else if (str.Contains("System.DateTime"))
  180. {
  181. DateTime pdt = Convert.ToDateTime(value, CultureInfo.InvariantCulture);
  182. cls[j].SetValue(obj, pdt, null);
  183. }
  184. else if (str.Contains("System.Boolean"))
  185. {
  186. bool pb = Convert.ToBoolean(value);
  187. cls[j].SetValue(obj, pb, null);
  188. }
  189. else if (str.Contains("System.Int16"))
  190. {
  191. short pi16 = Convert.ToInt16(value);
  192. cls[j].SetValue(obj, pi16, null);
  193. }
  194. else if (str.Contains("System.Int32"))
  195. {
  196. int pi32 = Convert.ToInt32(value);
  197. cls[j].SetValue(obj, pi32, null);
  198. }
  199. else if (str.Contains("System.Int64"))
  200. {
  201. long pi64 = Convert.ToInt64(value);
  202. cls[j].SetValue(obj, pi64, null);
  203. }
  204. else if (str.Contains("System.Byte"))
  205. {
  206. byte pb = Convert.ToByte(value);
  207. cls[j].SetValue(obj, pb, null);
  208. }
  209. else
  210. {
  211. cls[j].SetValue(obj, null, null);
  212. }
  213. }
  214. }
  215. list.Add(obj);
  216. }
  217. sheet = null;
  218. workbook = null;
  219. return list;
  220. }
  221. }
  222. }