ExcelHandler.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. using System.IO;
  2. using System.Data;
  3. using System;
  4. using NPOI.HSSF.UserModel;
  5. using NPOI.SS.UserModel;
  6. using NPOI.HSSF.Util;
  7. using NPOI.SS.Formula.Eval;
  8. using System.Text;
  9. using UAS_MES.Entity;
  10. namespace UAS_MES.DataOperate
  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 string ExportExcel(DataTable dt, string FolderPath)
  38. {
  39. //创建一个内存流,用来接收转换成Excel的内容
  40. MemoryStream ms;
  41. ms = DataTableToExcel(dt);
  42. //以系统当前时间命名文件,FileMode.Create表示创建文件,FileAccess.Write表示拥有写的权限
  43. string filePath = @FolderPath + "\\" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";
  44. FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write);
  45. byte[] data = ms.ToArray();
  46. fs.Write(data, 0, data.Length);
  47. fs.Flush();
  48. //释放当前Excel文件,否则打开文件的时候会显示文件被占用
  49. ms.Dispose();
  50. fs.Dispose();
  51. return filePath;
  52. }
  53. /// <summary>
  54. /// 导入Excel
  55. /// </summary>
  56. public DataTable ImportExcel(string FolderPath, string TableName)
  57. {
  58. DataTable dt = new DataTable();
  59. dt.TableName = TableName;
  60. if (FolderPath.Contains(".xls") || FolderPath.Contains(".xlsx") || FolderPath.Contains(".XLS") || FolderPath.Contains(".XLSX"))
  61. {
  62. using (FileStream file = new FileStream(FolderPath, FileMode.Open, FileAccess.Read))
  63. {
  64. //获取文件流
  65. HSSFWorkbook workbook = new HSSFWorkbook(file);
  66. ISheet sheet = workbook.GetSheetAt(0);
  67. //获取所有的列名
  68. foreach (ICell item in sheet.GetRow(sheet.FirstRowNum).Cells)
  69. {
  70. dt.Columns.Add(item.ToString().Trim(), typeof(string));
  71. }
  72. System.Collections.IEnumerator rows = sheet.GetRowEnumerator();
  73. while (rows.MoveNext())
  74. {
  75. IRow row = (HSSFRow)rows.Current;
  76. if (row.RowNum == sheet.FirstRowNum)
  77. {
  78. continue;
  79. }
  80. DataRow dr = dt.NewRow();
  81. foreach (ICell item in row.Cells)
  82. {
  83. switch (item.CellType)
  84. {
  85. case CellType.BOOLEAN:
  86. dr[item.ColumnIndex] = item.BooleanCellValue;
  87. break;
  88. case CellType.ERROR:
  89. dr[item.ColumnIndex] = ErrorEval.GetText(item.ErrorCellValue);
  90. break;
  91. case CellType.FORMULA:
  92. switch (item.CachedFormulaResultType)
  93. {
  94. case CellType.BOOLEAN:
  95. dr[item.ColumnIndex] = item.BooleanCellValue;
  96. break;
  97. case CellType.ERROR:
  98. dr[item.ColumnIndex] = ErrorEval.GetText(item.ErrorCellValue);
  99. break;
  100. case CellType.NUMERIC:
  101. if (DateUtil.IsCellDateFormatted(item))
  102. {
  103. dr[item.ColumnIndex] = item.DateCellValue.ToString("yyyy-MM-dd hh:MM:ss");
  104. }
  105. else
  106. {
  107. dr[item.ColumnIndex] = item.NumericCellValue;
  108. }
  109. break;
  110. case CellType.STRING:
  111. string str = item.StringCellValue;
  112. if (!string.IsNullOrEmpty(str))
  113. {
  114. dr[item.ColumnIndex] = str.ToString();
  115. }
  116. else
  117. {
  118. dr[item.ColumnIndex] = null;
  119. }
  120. break;
  121. case CellType.Unknown:
  122. case CellType.BLANK:
  123. default:
  124. dr[item.ColumnIndex] = string.Empty;
  125. break;
  126. }
  127. break;
  128. case CellType.NUMERIC:
  129. if (DateUtil.IsCellDateFormatted(item))
  130. {
  131. dr[item.ColumnIndex] = item.DateCellValue.ToString("yyyy-MM-dd hh:MM:ss");
  132. }
  133. else
  134. {
  135. dr[item.ColumnIndex] = item.NumericCellValue;
  136. }
  137. break;
  138. case CellType.STRING:
  139. string strValue = item.StringCellValue;
  140. if (!string.IsNullOrEmpty(strValue))
  141. {
  142. dr[item.ColumnIndex] = strValue.ToString();
  143. }
  144. else
  145. {
  146. dr[item.ColumnIndex] = null;
  147. }
  148. break;
  149. case CellType.Unknown:
  150. case CellType.BLANK:
  151. default:
  152. dr[item.ColumnIndex] = string.Empty;
  153. break;
  154. }
  155. }
  156. dt.Rows.Add(dr);
  157. }
  158. }
  159. }
  160. return dt;
  161. }
  162. /// <summary>
  163. /// 导入Excel
  164. /// </summary>
  165. public void ImportExcel(DataTable DataTable, string TableName)
  166. {
  167. int columnNum = DataTable.Columns.Count;
  168. int rowNum = DataTable.Columns.Count;
  169. string[] field = new string[columnNum];
  170. for (int i = 0; i < columnNum; i++)
  171. {
  172. field[i] = DataTable.Rows[0][i].ToString();
  173. }
  174. }
  175. /// <summary>
  176. /// 将DataTable形式的数据转成Excel格式的,然后用字节流的形式写入文件
  177. /// </summary>
  178. /// <param name="DataTable"></param>
  179. /// <returns></returns>
  180. public MemoryStream DataTableToExcel(DataTable DataTable)
  181. {
  182. //创建内存流
  183. MemoryStream ms = new MemoryStream();
  184. //创建一个Book,相当于一个Excel文件
  185. HSSFWorkbook book = new HSSFWorkbook();
  186. //Excel中的Sheet
  187. ISheet sheet = book.CreateSheet("sheet1");
  188. //获取行数量和列数量
  189. int rowNum = DataTable.Rows.Count;
  190. int columnNum = DataTable.Columns.Count;
  191. //设置列的宽度,根据首行的列的内容的长度来设置
  192. for (int i = 0; i < columnNum; i++)
  193. {
  194. int dataLength;
  195. //如果内容比标题短则取标题长度
  196. if (DataTable.Rows[0][i].ToString().Length < DataTable.Columns[i].ColumnName.Length)
  197. {
  198. dataLength = DataTable.Columns[i].ColumnName.Length;
  199. dataLength = dataLength * 600;
  200. }
  201. else
  202. {
  203. dataLength = DataTable.Rows[0][i].ToString().Length;
  204. dataLength = dataLength * 500;
  205. }
  206. sheet.SetColumnWidth(i, dataLength);
  207. }
  208. //首先画好第一行带颜色的,单独写出来,避免写在循环里面
  209. IRow row = sheet.CreateRow(0);
  210. //冻结第一行
  211. sheet.CreateFreezePane(0, 1, 0, 1);
  212. ICellStyle style = book.CreateCellStyle();
  213. style.FillForegroundColor = HSSFColor.PALE_BLUE.index;
  214. style.FillPattern = FillPatternType.BIG_SPOTS;
  215. style.FillBackgroundColor = HSSFColor.LIGHT_GREEN.index;
  216. //设置边框
  217. style.BorderBottom = BorderStyle.THICK;
  218. style.BorderLeft = BorderStyle.THICK;
  219. style.BorderRight = BorderStyle.THICK;
  220. style.BorderTop = BorderStyle.THICK;
  221. row.HeightInPoints = 20;
  222. //固定第一行
  223. //row.RowStyle.IsLocked=true;
  224. //给第一行的标签赋值样式和值
  225. for (int j = 0; j < columnNum; j++)
  226. {
  227. row.CreateCell(j);
  228. row.Cells[j].CellStyle = style;
  229. row.Cells[j].CellStyle.VerticalAlignment = VerticalAlignment.CENTER;
  230. row.Cells[j].CellStyle.Alignment = HorizontalAlignment.CENTER;
  231. row.Cells[j].SetCellValue(DataTable.Columns[j].ColumnName);
  232. }
  233. //将DataTable的值循环赋值给book,Aligment设置居中
  234. //之前已经画了带颜色的第一行,所以从i=1开始画
  235. for (int i = 0; i < rowNum; i++)
  236. {
  237. IRow row1 = sheet.CreateRow(i + 1);
  238. row1.HeightInPoints = 20;
  239. for (int j = 0; j < columnNum; j++)
  240. {
  241. row1.CreateCell(j);
  242. row1.Cells[j].SetCellValue(DataTable.Rows[i][j].ToString());
  243. row1.GetCell(j).CellStyle.VerticalAlignment = VerticalAlignment.CENTER;
  244. }
  245. }
  246. //将book的内容写入内存流中返回
  247. book.Write(ms);
  248. return ms;
  249. }
  250. }
  251. }