ExcelHandler.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  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 UAS_MES_NEW.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. public string ExportExcel(DataTable dt, string FolderPath,string location)
  34. {
  35. //创建一个内存流,用来接收转换成Excel的内容
  36. MemoryStream ms;
  37. ms = DataTableToExcel(dt);
  38. //以系统当前时间命名文件,FileMode.Create表示创建文件,FileAccess.Write表示拥有写的权限
  39. string filePath = @FolderPath + "\\" + DateTime.Now.ToString("yyyyMMddHHmmss") +location+ ".xls";
  40. FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write);
  41. byte[] data = ms.ToArray();
  42. fs.Write(data, 0, data.Length);
  43. fs.Flush();
  44. //释放当前Excel文件,否则打开文件的时候会显示文件被占用
  45. ms.Dispose();
  46. fs.Dispose();
  47. return filePath;
  48. }
  49. /// <summary>
  50. /// 导入Excel
  51. /// </summary>
  52. public DataTable ImportExcel(string FolderPath, string TableName)
  53. {
  54. DataTable dt = new DataTable();
  55. dt.TableName = TableName;
  56. if (FolderPath.Contains(".xls") || FolderPath.Contains(".xlsx")|| FolderPath.Contains(".XLS") || FolderPath.Contains(".XLSX"))
  57. {
  58. using (FileStream file = new FileStream(FolderPath, FileMode.Open, FileAccess.Read))
  59. {
  60. //获取文件流
  61. HSSFWorkbook workbook = new HSSFWorkbook(file);
  62. ISheet sheet = workbook.GetSheetAt(0);
  63. //获取所有的列名
  64. foreach (ICell item in sheet.GetRow(sheet.FirstRowNum).Cells)
  65. {
  66. dt.Columns.Add(item.ToString().Trim(), typeof(string));
  67. }
  68. System.Collections.IEnumerator rows = sheet.GetRowEnumerator();
  69. while (rows.MoveNext())
  70. {
  71. IRow row = (HSSFRow)rows.Current;
  72. if (row.RowNum == sheet.FirstRowNum)
  73. {
  74. continue;
  75. }
  76. DataRow dr = dt.NewRow();
  77. foreach (ICell item in row.Cells)
  78. {
  79. switch (item.CellType)
  80. {
  81. case CellType.BOOLEAN:
  82. dr[item.ColumnIndex] = item.BooleanCellValue;
  83. break;
  84. case CellType.ERROR:
  85. dr[item.ColumnIndex] = ErrorEval.GetText(item.ErrorCellValue);
  86. break;
  87. case CellType.FORMULA:
  88. switch (item.CachedFormulaResultType)
  89. {
  90. case CellType.BOOLEAN:
  91. dr[item.ColumnIndex] = item.BooleanCellValue;
  92. break;
  93. case CellType.ERROR:
  94. dr[item.ColumnIndex] = ErrorEval.GetText(item.ErrorCellValue);
  95. break;
  96. case CellType.NUMERIC:
  97. if (DateUtil.IsCellDateFormatted(item))
  98. {
  99. dr[item.ColumnIndex] = item.DateCellValue.ToString("yyyy-MM-dd hh:MM:ss");
  100. }
  101. else
  102. {
  103. dr[item.ColumnIndex] = item.NumericCellValue;
  104. }
  105. break;
  106. case CellType.STRING:
  107. string str = item.StringCellValue;
  108. if (!string.IsNullOrEmpty(str))
  109. {
  110. dr[item.ColumnIndex] = str.ToString();
  111. }
  112. else
  113. {
  114. dr[item.ColumnIndex] = null;
  115. }
  116. break;
  117. case CellType.Unknown:
  118. case CellType.BLANK:
  119. default:
  120. dr[item.ColumnIndex] = string.Empty;
  121. break;
  122. }
  123. break;
  124. case CellType.NUMERIC:
  125. if (DateUtil.IsCellDateFormatted(item))
  126. {
  127. dr[item.ColumnIndex] = item.DateCellValue.ToString("yyyy-MM-dd hh:MM:ss");
  128. }
  129. else
  130. {
  131. dr[item.ColumnIndex] = item.NumericCellValue;
  132. }
  133. break;
  134. case CellType.STRING:
  135. string strValue = item.StringCellValue;
  136. if (!string.IsNullOrEmpty(strValue))
  137. {
  138. dr[item.ColumnIndex] = strValue.ToString();
  139. }
  140. else
  141. {
  142. dr[item.ColumnIndex] = null;
  143. }
  144. break;
  145. case CellType.Unknown:
  146. case CellType.BLANK:
  147. default:
  148. dr[item.ColumnIndex] = string.Empty;
  149. break;
  150. }
  151. }
  152. dt.Rows.Add(dr);
  153. }
  154. }
  155. }
  156. if (FolderPath.Contains(".csv"))
  157. {
  158. dt = ReadFromCSV(FolderPath);
  159. }
  160. return dt;
  161. }
  162. /// <summary>
  163. /// 将CSV文件中内容读取到DataTable中
  164. /// </summary>
  165. /// <param name="path">CSV文件路径</param>
  166. /// <param name="hasTitle">是否将CSV文件的第一行读取为DataTable的列名</param>
  167. /// <returns></returns>
  168. public static DataTable ReadFromCSV(string path, bool hasTitle = true)
  169. {
  170. DataTable dt = new DataTable(); //要输出的数据表
  171. StreamReader sr = new StreamReader(path, System.Text.Encoding.GetEncoding("GB2312")); //文件读入流
  172. bool bFirst = true; //指示是否第一次读取数据
  173. //逐行读取
  174. string line;
  175. while ((line = sr.ReadLine()) != null)
  176. {
  177. //string[] elements = line.Replace("\r", "").Replace("\n", "").Replace("\t", "").Split(',');
  178. string[] elements = line.Replace("\r", "").Replace("\n", "").Replace("\t", "").Replace("\"","").Replace(" ","").Split(',');
  179. //第一次读取数据时,要创建数据列
  180. if (bFirst)
  181. {
  182. for (int i = 0; i < elements.Length; i++)
  183. {
  184. dt.Columns.Add();
  185. }
  186. bFirst = false;
  187. }
  188. //有标题行时,第一行当做标题行处理
  189. if (hasTitle)
  190. {
  191. for (int i = 0; i < dt.Columns.Count && i < elements.Length; i++)
  192. {
  193. dt.Columns[i].ColumnName = elements[i];
  194. }
  195. hasTitle = false;
  196. }
  197. else //读取一行数据
  198. {
  199. if (elements.Length == dt.Columns.Count)
  200. {
  201. dt.Rows.Add(elements);
  202. }
  203. else
  204. {
  205. //throw new Exception("CSV格式错误:表格各行列数不一致");
  206. }
  207. }
  208. }
  209. sr.Close();
  210. return dt;
  211. }
  212. public void WriteTxt(DataTable dt, string FolderPath, string FileName)
  213. {
  214. StreamWriter sr;
  215. string filePath = @FolderPath;
  216. if (File.Exists(filePath + "\\" + FileName)) //如果文件存在,则创建File.AppendText对象
  217. {
  218. File.Delete(filePath + "\\" + FileName);
  219. }
  220. sr = File.CreateText(filePath + "\\" + FileName);
  221. StringBuilder sb = new StringBuilder();
  222. string Title = "";
  223. foreach (DataColumn dc in dt.Columns)
  224. {
  225. Title += string.Format("{0,10}", dc.ColumnName.ToString());
  226. }
  227. sr.WriteLine(Title + "\r");
  228. foreach (DataRow dr in dt.Rows)
  229. {
  230. string text = "";
  231. for (int i = 0; i < dt.Columns.Count; i++)
  232. {
  233. text += String.Format("{0,10}", dr[i].ToString());
  234. }
  235. sr.WriteLine(text + "\r");
  236. }
  237. sr.Close();
  238. }
  239. /// <summary>
  240. /// 将DataTable形式的数据转成Excel格式的,然后用字节流的形式写入文件
  241. /// </summary>
  242. /// <param name="DataTable"></param>
  243. /// <returns></returns>
  244. public MemoryStream DataTableToExcel(DataTable DataTable)
  245. {
  246. //创建内存流
  247. MemoryStream ms = new MemoryStream();
  248. //创建一个Book,相当于一个Excel文件
  249. HSSFWorkbook book = new HSSFWorkbook();
  250. //Excel中的Sheet
  251. ISheet sheet = book.CreateSheet("sheet1");
  252. //获取行数量和列数量
  253. int rowNum = DataTable.Rows.Count;
  254. int columnNum = DataTable.Columns.Count;
  255. //设置列的宽度,根据首行的列的内容的长度来设置
  256. for (int i = 0; i < columnNum; i++)
  257. {
  258. int dataLength = DataTable.Columns[i].ColumnName.Length;
  259. sheet.SetColumnWidth(i, dataLength * 700);
  260. }
  261. //首先画好第一行带颜色的,单独写出来,避免写在循环里面
  262. IRow row = sheet.CreateRow(0);
  263. //冻结第一行
  264. sheet.CreateFreezePane(0, 1, 0, 1);
  265. ICellStyle style = book.CreateCellStyle();
  266. style.FillForegroundColor = HSSFColor.PALE_BLUE.index;
  267. style.FillPattern = FillPatternType.BIG_SPOTS;
  268. style.FillBackgroundColor = HSSFColor.LIGHT_GREEN.index;
  269. //设置边框
  270. style.BorderBottom = BorderStyle.THICK;
  271. style.BorderLeft = BorderStyle.THICK;
  272. style.BorderRight = BorderStyle.THICK;
  273. style.BorderTop = BorderStyle.THICK;
  274. row.HeightInPoints = 20;
  275. //固定第一行
  276. //row.RowStyle.IsLocked=true;
  277. //给第一行的标签赋值样式和值
  278. for (int j = 0; j < columnNum; j++)
  279. {
  280. row.CreateCell(j);
  281. row.Cells[j].CellStyle = style;
  282. row.Cells[j].CellStyle.VerticalAlignment = VerticalAlignment.CENTER;
  283. row.Cells[j].CellStyle.Alignment = HorizontalAlignment.CENTER;
  284. row.Cells[j].SetCellValue(DataTable.Columns[j].ColumnName);
  285. }
  286. //将DataTable的值循环赋值给book,Aligment设置居中
  287. //之前已经画了带颜色的第一行,所以从i=1开始画
  288. for (int i = 0; i < rowNum; i++)
  289. {
  290. IRow row1 = sheet.CreateRow(i + 1);
  291. row1.HeightInPoints = 20;
  292. for (int j = 0; j < columnNum; j++)
  293. {
  294. row1.CreateCell(j);
  295. row1.Cells[j].SetCellValue(DataTable.Rows[i][j].ToString());
  296. row1.GetCell(j).CellStyle.VerticalAlignment = VerticalAlignment.CENTER;
  297. }
  298. }
  299. //将book的内容写入内存流中返回
  300. book.Write(ms);
  301. return ms;
  302. }
  303. }
  304. }