ExcelHandler.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  1. using System.IO;
  2. using System.Data;
  3. using NPOI.HSSF.UserModel;
  4. using NPOI.SS.UserModel;
  5. using NPOI.HSSF.Util;
  6. using NPOI.XSSF.UserModel;
  7. using System;
  8. using UAS_LabelMachine.Entity;
  9. using UAS_LabelMachine.PublicMethod;
  10. namespace UAS_LabelMachine
  11. {
  12. class ExcelHandler
  13. {
  14. DataHelper dh = SystemInf.dh;
  15. /// <summary>
  16. /// 导出Excel,返回文件在客户端的路径
  17. /// </summary>
  18. public string ExportExcel(DataTable dt, string FolderPath, string FileName)
  19. {
  20. //创建一个内存流,用来接收转换成Excel的内容
  21. MemoryStream ms;
  22. ms = DataTableToExcel(dt);
  23. //以系统当前时间命名文件,FileMode.Create表示创建文件,FileAccess.Write表示拥有写的权限
  24. string filePath = @FolderPath + "\\" + FileName + ".xls";
  25. FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write);
  26. byte[] data = ms.ToArray();
  27. fs.Write(data, 0, data.Length);
  28. fs.Flush();
  29. //释放当前Excel文件,否则打开文件的时候会显示文件被占用
  30. ms.Dispose();
  31. fs.Dispose();
  32. return filePath;
  33. }
  34. /// <summary>
  35. /// 导入Excel
  36. /// </summary>
  37. public void ImportExcel(DataTable DataTable, string TableName)
  38. {
  39. int columnNum = DataTable.Columns.Count;
  40. int rowNum = DataTable.Columns.Count;
  41. string[] field = new string[columnNum];
  42. for (int i = 0; i < columnNum; i++)
  43. {
  44. field[i] = DataTable.Rows[0][i].ToString();
  45. }
  46. }
  47. public static DataTable ExcelToDataTable(string filePath, bool isColumnName)
  48. {
  49. DataTable dataTable = null;
  50. FileStream fs = null;
  51. DataColumn column = null;
  52. DataRow dataRow = null;
  53. IWorkbook workbook = null;
  54. ISheet sheet = null;
  55. IRow row = null;
  56. ICell cell = null;
  57. int startRow = 0;
  58. try
  59. {
  60. using (fs = File.OpenRead(filePath))
  61. {
  62. // 2007版本
  63. if (filePath.IndexOf(".xlsx") > 0)
  64. {
  65. workbook = new XSSFWorkbook(fs);
  66. }
  67. // 2003版本
  68. else if (filePath.IndexOf(".xls") > 0)
  69. {
  70. workbook = new HSSFWorkbook(fs);
  71. }
  72. if (workbook != null)
  73. {
  74. sheet = workbook.GetSheetAt(0);//读取第一个sheet,当然也可以循环读取每个sheet
  75. dataTable = new DataTable();
  76. if (sheet != null)
  77. {
  78. int rowCount = sheet.LastRowNum;//总行数
  79. if (rowCount > 0)
  80. {
  81. IRow firstRow = sheet.GetRow(0);//第一行
  82. int cellCount = firstRow.LastCellNum;//列数
  83. //构建datatable的列
  84. if (isColumnName)
  85. {
  86. startRow = 1;//如果第一行是列名,则从第二行开始读取
  87. for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
  88. {
  89. cell = firstRow.GetCell(i);
  90. if (cell != null)
  91. {
  92. if (cell.StringCellValue != null)
  93. {
  94. column = new DataColumn(cell.StringCellValue);
  95. dataTable.Columns.Add(column);
  96. }
  97. }
  98. }
  99. }
  100. else
  101. {
  102. for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
  103. {
  104. column = new DataColumn("column" + (i + 1));
  105. dataTable.Columns.Add(column);
  106. }
  107. }
  108. //填充行
  109. for (int i = startRow; i <= rowCount; ++i)
  110. {
  111. row = sheet.GetRow(i);
  112. if (row == null) continue;
  113. dataRow = dataTable.NewRow();
  114. for (int j = row.FirstCellNum; j < cellCount; ++j)
  115. {
  116. cell = row.GetCell(j);
  117. if (cell == null)
  118. {
  119. dataRow[j] = "";
  120. }
  121. else
  122. {
  123. //CellType(Unknown = -1,Numeric = 0,String = 1,Formula = 2,Blank = 3,Boolean = 4,Error = 5,)
  124. switch (cell.CellType)
  125. {
  126. case CellType.Blank:
  127. dataRow[j] = "";
  128. break;
  129. case CellType.Numeric:
  130. short format = cell.CellStyle.DataFormat;
  131. //对时间格式(2015.12.5、2015/12/5、2015-12-5等)的处理
  132. if (format == 14 || format == 31 || format == 57 || format == 58)
  133. dataRow[j] = cell.DateCellValue;
  134. else
  135. dataRow[j] = cell.NumericCellValue;
  136. break;
  137. case CellType.String:
  138. dataRow[j] = cell.StringCellValue;
  139. break;
  140. }
  141. }
  142. }
  143. dataTable.Rows.Add(dataRow);
  144. }
  145. }
  146. }
  147. }
  148. }
  149. return dataTable;
  150. }
  151. catch (Exception)
  152. {
  153. if (fs != null)
  154. {
  155. fs.Close();
  156. }
  157. return null;
  158. }
  159. }
  160. /// <summary>
  161. /// 将DataTable形式的数据转成Excel格式的,然后用字节流的形式写入文件
  162. /// </summary>
  163. /// <param name="DataTable"></param>
  164. /// <returns></returns>
  165. public MemoryStream DataTableToExcel(DataTable DataTable)
  166. {
  167. //创建内存流
  168. MemoryStream ms = new MemoryStream();
  169. //创建一个Book,相当于一个Excel文件
  170. HSSFWorkbook book = new HSSFWorkbook();
  171. //Excel中的Sheet
  172. ISheet sheet = book.CreateSheet("sheet1");
  173. //获取行数量和列数量
  174. int rowNum = DataTable.Rows.Count;
  175. int columnNum = DataTable.Columns.Count;
  176. //设置列的宽度,根据首行的列的内容的长度来设置
  177. for (int i = 0; i < columnNum; i++)
  178. {
  179. int dataLength;
  180. //如果内容比标题短则取标题长度
  181. if (DataTable.Rows[0][i].ToString().Length < DataTable.Columns[i].ColumnName.Length)
  182. {
  183. dataLength = DataTable.Columns[i].ColumnName.Length;
  184. dataLength = dataLength * 600;
  185. }
  186. else
  187. {
  188. dataLength = DataTable.Rows[0][i].ToString().Length;
  189. dataLength = dataLength * 500;
  190. }
  191. sheet.SetColumnWidth(i, dataLength);
  192. }
  193. //首先画好第一行带颜色的,单独写出来,避免写在循环里面
  194. IRow row = sheet.CreateRow(0);
  195. //冻结第一行
  196. sheet.CreateFreezePane(0, 1, 0, 1);
  197. ICellStyle style = book.CreateCellStyle();
  198. style.FillForegroundColor = HSSFColor.PaleBlue.Index;
  199. style.FillPattern = FillPattern.BigSpots;
  200. style.FillBackgroundColor = HSSFColor.LightGreen.Index;
  201. //设置边框
  202. style.BorderBottom = BorderStyle.Thick;
  203. style.BorderLeft = BorderStyle.Thick;
  204. style.BorderRight = BorderStyle.Thick;
  205. style.BorderTop = BorderStyle.Thick;
  206. row.HeightInPoints = 20;
  207. //固定第一行
  208. //row.RowStyle.IsLocked=true;
  209. //给第一行的标签赋值样式和值
  210. for (int j = 0; j < columnNum; j++)
  211. {
  212. row.CreateCell(j);
  213. row.Cells[j].CellStyle = style;
  214. row.Cells[j].CellStyle.VerticalAlignment = VerticalAlignment.Center;
  215. row.Cells[j].CellStyle.Alignment = HorizontalAlignment.Center;
  216. row.Cells[j].SetCellValue(DataTable.Columns[j].ColumnName);
  217. }
  218. //将DataTable的值循环赋值给book,Aligment设置居中
  219. //之前已经画了带颜色的第一行,所以从i=1开始画
  220. for (int i = 0; i < rowNum; i++)
  221. {
  222. IRow row1 = sheet.CreateRow(i + 1);
  223. row1.HeightInPoints = 20;
  224. for (int j = 0; j < columnNum; j++)
  225. {
  226. row1.CreateCell(j);
  227. row1.Cells[j].SetCellValue(DataTable.Rows[i][j].ToString());
  228. row1.GetCell(j).CellStyle.VerticalAlignment = VerticalAlignment.Center;
  229. }
  230. }
  231. //将book的内容写入内存流中返回
  232. book.Write(ms);
  233. return ms;
  234. }
  235. }
  236. }