NPOIExcle.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  1. using DocumentFormat.OpenXml.Spreadsheet;
  2. using NPOI.HSSF.UserModel;
  3. using NPOI.SS.UserModel;
  4. using NPOI.XSSF.UserModel;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.Data;
  8. using System.IO;
  9. using System.Linq;
  10. using System.Security.Policy;
  11. using System.Text;
  12. using System.Threading.Tasks;
  13. using CellType = NPOI.SS.UserModel.CellType;
  14. using IndexedColors = NPOI.SS.UserModel.IndexedColors;
  15. namespace wispro.sp.utility
  16. {
  17. public class NPOIExcel
  18. {
  19. /// <summary>
  20. /// 将excel导入到datatable
  21. /// </summary>
  22. /// <param name="filePath">excel路径</param>
  23. /// <param name="isColumnName">是否有列名</param>
  24. /// <param name="ColumnNameRow">列名的所在行,0为第一行</param>
  25. /// <param name="IgnoreZeroHightRow">是否忽略隐藏行</param>
  26. /// <returns>返回datatable</returns>
  27. public static DataTable ExcelToDataTable(string filePath, bool isColumnName,bool IgnoreZeroHightRow = false,int ColumnNameRow=0,int iSheet=0)
  28. {
  29. DataTable dataTable = null;
  30. FileStream fs = null;
  31. DataColumn column = null;
  32. DataRow dataRow = null;
  33. IWorkbook workbook = null;
  34. ISheet sheet = null;
  35. IRow row = null;
  36. ICell cell = null;
  37. int startRow = 0;
  38. try
  39. {
  40. using (fs = File.OpenRead(filePath))
  41. {
  42. // 2007版本
  43. if (filePath.IndexOf(".xlsx") > 0)
  44. workbook = new XSSFWorkbook(fs);
  45. // 2003版本
  46. else if (filePath.IndexOf(".xls") > 0)
  47. workbook = new HSSFWorkbook(fs);
  48. if (workbook != null)
  49. {
  50. sheet = workbook.GetSheetAt(iSheet);//读取第一个sheet,当然也可以循环读取每个sheet
  51. dataTable = new DataTable();
  52. if (sheet != null)
  53. {
  54. int rowCount = sheet.LastRowNum;//总行数
  55. if (rowCount > 0)
  56. {
  57. IRow firstRow = sheet.GetRow(ColumnNameRow);//列头行
  58. int cellCount = firstRow.LastCellNum;//列数
  59. //构建datatable的列
  60. if (isColumnName)
  61. {
  62. startRow = ColumnNameRow+1;//如果有列名,则从第列头行的下一行开始读取
  63. for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
  64. {
  65. cell = firstRow.GetCell(i);
  66. if (cell != null)
  67. {
  68. if (cell.StringCellValue != null)
  69. {
  70. column = new DataColumn(cell.StringCellValue);
  71. dataTable.Columns.Add(column);
  72. }
  73. }
  74. }
  75. }
  76. else
  77. {
  78. for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
  79. {
  80. column = new DataColumn("column" + (i + 1));
  81. dataTable.Columns.Add(column);
  82. }
  83. }
  84. //填充行
  85. for (int i = startRow; i <= rowCount; ++i)
  86. {
  87. row = sheet.GetRow(i);
  88. //if(row.GetCell(1).ToString()== "PACN2110126")
  89. //{
  90. // System.Diagnostics.Debug.WriteLine("");
  91. //}
  92. if (row != null && IgnoreZeroHightRow && row.ZeroHeight)
  93. {
  94. System.Diagnostics.Debug.WriteLine (string.Format("[{0}]隐藏行:{1}", filePath, i));
  95. continue;
  96. }
  97. if (row == null || row.Cells.Count ==0) continue;
  98. dataRow = dataTable.NewRow();
  99. for (int j = row.FirstCellNum; j < cellCount; ++j)
  100. {
  101. cell = row.GetCell(j);
  102. if (cell == null)
  103. {
  104. dataRow[j] = "";
  105. }
  106. else
  107. {
  108. //CellType(Unknown = -1,Numeric = 0,String = 1,Formula = 2,Blank = 3,Boolean = 4,Error = 5,)
  109. switch (cell.CellType)
  110. {
  111. case CellType.Blank:
  112. dataRow[j] = "";
  113. break;
  114. case CellType.Numeric:
  115. short format = cell.CellStyle.DataFormat;
  116. //对时间格式(2015.12.5、2015/12/5、2015-12-5等)的处理
  117. if (DateUtil.IsCellDateFormatted(cell))// || format == 14 || format == 31 || format == 57 || format == 58 || format == 165 || format == 177 || format == 176)
  118. try
  119. {
  120. dataRow[j] = cell.DateCellValue;
  121. }
  122. catch
  123. {
  124. //dataRow[j] = null;
  125. }
  126. else
  127. dataRow[j] = cell.NumericCellValue;
  128. break;
  129. case CellType.String:
  130. dataRow[j] = cell.StringCellValue;
  131. break;
  132. }
  133. }
  134. }
  135. dataTable.Rows.Add(dataRow);
  136. }
  137. }
  138. }
  139. }
  140. }
  141. return dataTable;
  142. }
  143. catch (Exception ex)
  144. {
  145. if (fs != null)
  146. {
  147. fs.Close();
  148. }
  149. return null;
  150. }
  151. }
  152. public static DataTable ExcelToDataTable(string v)
  153. {
  154. return ExcelToDataTable(v, false, true);
  155. }
  156. // 创建超链接对象(兼容 xls/xlsx)
  157. private static IHyperlink CreateHyperlink(IWorkbook workbook, HyperlinkType type, string address)
  158. {
  159. if (workbook is XSSFWorkbook)
  160. return new XSSFHyperlink(type) { Address = address };
  161. else
  162. return new HSSFHyperlink(type) { Address = address };
  163. }
  164. // 设置超链接样式
  165. private static void SetHyperlinkStyle(IWorkbook workbook, ICell cell)
  166. {
  167. IFont font = workbook.CreateFont();
  168. font.Underline = FontUnderlineType.Single;
  169. font.Color = IndexedColors.Blue.Index;
  170. ICellStyle cellStyle = workbook.CreateCellStyle();
  171. cellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
  172. cellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
  173. cellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
  174. cellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
  175. cellStyle.WrapText = true;// 指定单元格自动换行
  176. cellStyle.VerticalAlignment = VerticalAlignment.Center;//垂直居中
  177. cellStyle.Alignment = HorizontalAlignment.Center;
  178. cellStyle.SetFont(font);
  179. cell.CellStyle = cellStyle;
  180. }
  181. /// <summary>
  182. /// 写入excel
  183. /// </summary>
  184. /// <param name="dt">datatable</param>
  185. /// <param name="strFile">strFile</param>
  186. /// <returns></returns>
  187. public static bool DataTableToExcel(DataTable dt, string strFile,bool isAutoColumnWidth=true,bool isLink=false,int linkCol=0,string linkFortmat="")
  188. {
  189. bool result = false;
  190. IWorkbook workbook = null;
  191. FileStream fs = null;
  192. IRow row = null;
  193. ISheet sheet = null;
  194. ICell cell = null;
  195. try
  196. {
  197. if (dt != null && dt.Rows.Count > 0)
  198. {
  199. workbook = new XSSFWorkbook();
  200. sheet = workbook.CreateSheet("Sheet0");//创建一个名称为Sheet0的表
  201. int rowCount = dt.Rows.Count;//行数
  202. int columnCount = dt.Columns.Count;//列数
  203. //设置列头
  204. row = sheet.CreateRow(0);//excel第一行设为列头
  205. for (int c = 0; c < columnCount; c++)
  206. {
  207. cell = row.CreateCell(c);
  208. cell.SetCellValue(dt.Columns[c].ColumnName);
  209. ICellStyle cellStyleColumn = workbook.CreateCellStyle();
  210. cellStyleColumn.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
  211. cellStyleColumn.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
  212. cellStyleColumn.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
  213. cellStyleColumn.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
  214. cellStyleColumn.WrapText = true;// 指定单元格自动换行
  215. cellStyleColumn.VerticalAlignment = VerticalAlignment.Center;//垂直居中
  216. cellStyleColumn.Alignment = HorizontalAlignment.Center; //水平居中
  217. IFont font = workbook.CreateFont();
  218. font.IsBold = true;
  219. cellStyleColumn.SetFont(font);
  220. cell.CellStyle = cellStyleColumn;
  221. }
  222. #region 设置边框
  223. ICellStyle cellStyle = workbook.CreateCellStyle();
  224. cellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
  225. cellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
  226. cellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
  227. cellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
  228. cellStyle.WrapText = true;// 指定单元格自动换行
  229. cellStyle.VerticalAlignment = VerticalAlignment.Center;//垂直居中
  230. cellStyle.Alignment = HorizontalAlignment.Center;
  231. #endregion
  232. //设置每行每列的单元格,
  233. for (int i = 0; i < rowCount; i++)
  234. {
  235. row = sheet.CreateRow(i + 1);
  236. row.Height = 30*20;
  237. for (int j = 0; j < columnCount; j++)
  238. {
  239. cell = row.CreateCell(j);//excel第二行开始写入数据
  240. if(dt.Rows[i][j] is System.DBNull)
  241. {
  242. cell.SetCellValue("");
  243. }
  244. else
  245. {
  246. switch (dt.Rows[i][j].GetType().ToString())
  247. {
  248. case "System.String":
  249. cell.SetCellValue(dt.Rows[i][j].ToString());
  250. break;
  251. case "System.Double":
  252. case "System.Int32":
  253. case "System.Int64":
  254. case "System.Float":
  255. case "System.Decimal":
  256. cell.SetCellValue(double.Parse(dt.Rows[i][j].ToString()));
  257. cellStyle.DataFormat = HSSFDataFormat.GetBuiltinFormat("###0.00");//(short)CellType.NUMERIC;
  258. break;
  259. case "System.DateTime":
  260. cell.SetCellValue(DateTime.Parse(dt.Rows[i][j].ToString()));
  261. break;
  262. default:
  263. cell.SetCellValue(dt.Rows[i][j].ToString());
  264. break;
  265. }
  266. }
  267. cell.CellStyle = cellStyle;
  268. if (isLink && linkCol == j)
  269. {
  270. var url = string.Format(linkFortmat, cell.StringCellValue);
  271. cell.Hyperlink = CreateHyperlink(workbook, HyperlinkType.Url, url);
  272. SetHyperlinkStyle(workbook, cell);
  273. }
  274. }
  275. }
  276. #region 设定列宽
  277. if (isAutoColumnWidth)
  278. {
  279. for (int i = 0; i < columnCount; i++)
  280. {
  281. sheet.AutoSizeColumn(i);
  282. }
  283. //获取当前列的宽度,然后对比本列的长度,取最大值
  284. for (int columnNum = 0; columnNum <= columnCount; columnNum++)
  285. {
  286. int columnWidth = sheet.GetColumnWidth(columnNum) / 256;
  287. for (int rowNum = 0; rowNum <1; rowNum++)
  288. {
  289. IRow currentRow;
  290. //当前行未被使用过
  291. if (sheet.GetRow(rowNum) == null)
  292. {
  293. currentRow = sheet.CreateRow(rowNum);
  294. }
  295. else
  296. {
  297. currentRow = sheet.GetRow(rowNum);
  298. }
  299. if (currentRow.GetCell(columnNum) != null)
  300. {
  301. ICell currentCell = currentRow.GetCell(columnNum);
  302. int length = Encoding.Default.GetBytes(currentCell.ToString()).Length;
  303. if (columnWidth < length)
  304. {
  305. columnWidth = length;
  306. }
  307. }
  308. }
  309. sheet.SetColumnWidth(columnNum, columnWidth * 256);
  310. }
  311. }
  312. #endregion
  313. using (fs = File.OpenWrite(strFile))
  314. {
  315. workbook.Write(fs);//向打开的这个xls文件中写入数据
  316. result = true;
  317. fs.Close();
  318. }
  319. }
  320. return result;
  321. }
  322. catch (Exception ex)
  323. {
  324. if (fs != null)
  325. {
  326. fs.Close();
  327. }
  328. return false;
  329. }
  330. }
  331. /// <summary>
  332. /// Excel导入成Datable
  333. /// </summary>
  334. /// <param name="file">导入路径(包含文件名与扩展名)</param>
  335. /// <returns></returns>
  336. public static DataTable ExcelToTable(string file)
  337. {
  338. DataTable dt = new DataTable();
  339. IWorkbook workbook;
  340. string fileExt = Path.GetExtension(file).ToLower();
  341. using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read))
  342. {
  343. //XSSFWorkbook 适用XLSX格式,HSSFWorkbook 适用XLS格式
  344. if (fileExt == ".xlsx") { workbook = new XSSFWorkbook(fs); } else if (fileExt == ".xls") { workbook = new HSSFWorkbook(fs); } else { workbook = null; }
  345. if (workbook == null) { return null; }
  346. ISheet sheet = workbook.GetSheetAt(0);
  347. //表头
  348. IRow header = sheet.GetRow(sheet.FirstRowNum);
  349. List<int> columns = new List<int>();
  350. for (int i = 0; i < header.LastCellNum; i++)
  351. {
  352. object obj = GetValueType(header.GetCell(i));
  353. if (obj == null || obj.ToString() == string.Empty)
  354. {
  355. dt.Columns.Add(new DataColumn("Columns" + i.ToString()));
  356. }
  357. else
  358. dt.Columns.Add(new DataColumn(obj.ToString()));
  359. columns.Add(i);
  360. }
  361. //数据
  362. for (int i = sheet.FirstRowNum + 1; i <= sheet.LastRowNum; i++)
  363. {
  364. DataRow dr = dt.NewRow();
  365. bool hasValue = false;
  366. foreach (int j in columns)
  367. {
  368. dr[j] = GetValueType(sheet.GetRow(i).GetCell(j));
  369. if (dr[j] != null && dr[j].ToString() != string.Empty)
  370. {
  371. hasValue = true;
  372. }
  373. }
  374. if (hasValue)
  375. {
  376. dt.Rows.Add(dr);
  377. }
  378. }
  379. }
  380. return dt;
  381. }
  382. /// <summary>
  383. /// 获取单元格类型
  384. /// </summary>
  385. /// <param name="cell"></param>
  386. /// <returns></returns>
  387. private static object GetValueType(ICell cell)
  388. {
  389. if (cell == null)
  390. return null;
  391. switch (cell.CellType)
  392. {
  393. case CellType.Blank: //BLANK:
  394. return null;
  395. case CellType.Boolean: //BOOLEAN:
  396. return cell.BooleanCellValue;
  397. case CellType.Numeric: //NUMERIC:
  398. return cell.NumericCellValue;
  399. case CellType.String: //STRING:
  400. return cell.StringCellValue;
  401. case CellType.Error: //ERROR:
  402. return cell.ErrorCellValue;
  403. case CellType.Formula: //FORMULA:
  404. default:
  405. return "=" + cell.CellFormula;
  406. }
  407. }
  408. }
  409. }