ExcelHandler.cs 15 KB

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