ExcelHandler.cs 10 KB

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