ExcelHandler.cs 11 KB

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