ExcelHelper.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546
  1. using NPOI.HPSF;
  2. using NPOI.HSSF.UserModel;
  3. using NPOI.SS.UserModel;
  4. using System.Data;
  5. using System.IO;
  6. using System.Text;
  7. using System.Web;
  8. using System.Drawing;
  9. using NPOI.HSSF.Util;
  10. using System;
  11. using System.Collections.Generic;
  12. using NPOI.XSSF.UserModel;
  13. namespace LeaRun.Util.Offices
  14. {
  15. /// <summary>
  16. ///版 本 V1.0
  17. ///Copyright (c) 2010-2015 上海力软信息技术有限公司                          
  18. ///创建人:刘晓雷
  19. ///日 期:2015/11/25
  20. ///描 述:NPOI Excel DataTable操作类
  21. public class ExcelHelper
  22. {
  23. #region Excel导出方法 ExcelDownload
  24. /// <summary>
  25. /// Excel导出下载
  26. /// </summary>
  27. /// <param name="dtSource">DataTable数据源</param>
  28. /// <param name="excelConfig">导出设置包含文件名、标题、列设置</param>
  29. public static void ExcelDownload(DataTable dtSource, ExcelConfig excelConfig)
  30. {
  31. HttpContext curContext = HttpContext.Current;
  32. // 设置编码和附件格式
  33. curContext.Response.ContentType = "application/ms-excel";
  34. curContext.Response.ContentEncoding = Encoding.UTF8;
  35. curContext.Response.Charset = "";
  36. curContext.Response.AppendHeader("Content-Disposition",
  37. "attachment;filename=" + HttpUtility.UrlEncode(excelConfig.FileName, Encoding.UTF8));
  38. //调用导出具体方法Export()
  39. curContext.Response.BinaryWrite(ExportMemoryStream(dtSource, excelConfig).GetBuffer());
  40. curContext.Response.End();
  41. }
  42. /// <summary>
  43. /// Excel导出下载
  44. /// </summary>
  45. /// <param name="list">数据源</param>
  46. /// <param name="templdateName">模板文件名</param>
  47. /// <param name="newFileName">文件名</param>
  48. public static void ExcelDownload(List<TemplateMode> list, string templdateName, string newFileName)
  49. {
  50. HttpResponse response = System.Web.HttpContext.Current.Response;
  51. response.Clear();
  52. response.Charset = "UTF-8";
  53. response.ContentType = "application/vnd-excel";//"application/vnd.ms-excel";
  54. System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment; filename=" + newFileName));
  55. System.Web.HttpContext.Current.Response.BinaryWrite(ExportListByTempale(list, templdateName).ToArray());
  56. }
  57. #endregion
  58. #region DataTable导出到Excel文件excelConfig中FileName设置为全路径
  59. /// <summary>
  60. /// DataTable导出到Excel文件 Export()
  61. /// </summary>
  62. /// <param name="dtSource">DataTable数据源</param>
  63. /// <param name="excelConfig">导出设置包含文件名、标题、列设置</param>
  64. public static void ExcelExport(DataTable dtSource, ExcelConfig excelConfig)
  65. {
  66. using (MemoryStream ms = ExportMemoryStream(dtSource, excelConfig))
  67. {
  68. using (FileStream fs = new FileStream(excelConfig.FileName, FileMode.Create, FileAccess.Write))
  69. {
  70. byte[] data = ms.ToArray();
  71. fs.Write(data, 0, data.Length);
  72. fs.Flush();
  73. }
  74. }
  75. }
  76. #endregion
  77. #region DataTable导出到Excel的MemoryStream
  78. /// <summary>
  79. /// DataTable导出到Excel的MemoryStream Export()
  80. /// </summary>
  81. /// <param name="dtSource">DataTable数据源</param>
  82. /// <param name="excelConfig">导出设置包含文件名、标题、列设置</param>
  83. public static MemoryStream ExportMemoryStream(DataTable dtSource, ExcelConfig excelConfig)
  84. {
  85. for (int i = 0; i < dtSource.Columns.Count; )
  86. {
  87. bool IsExists = false;
  88. DataColumn column = dtSource.Columns[i];
  89. for (int j = 0; j < excelConfig.ColumnEntity.Count; j++)
  90. {
  91. if (excelConfig.ColumnEntity[j].Column == column.ColumnName)
  92. {
  93. IsExists = true;
  94. break;
  95. }
  96. }
  97. if (!IsExists)
  98. {
  99. dtSource.Columns.Remove(column);
  100. }
  101. else
  102. {
  103. i++;
  104. }
  105. }
  106. HSSFWorkbook workbook = new HSSFWorkbook();
  107. ISheet sheet = workbook.CreateSheet();
  108. #region 右击文件 属性信息
  109. {
  110. DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();
  111. dsi.Company = "NPOI";
  112. workbook.DocumentSummaryInformation = dsi;
  113. SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
  114. si.Author = "刘晓雷"; //填加xls文件作者信息
  115. si.ApplicationName = "力软信息"; //填加xls文件创建程序信息
  116. si.LastAuthor = "刘晓雷"; //填加xls文件最后保存者信息
  117. si.Comments = "刘晓雷"; //填加xls文件作者信息
  118. si.Title = "标题信息"; //填加xls文件标题信息
  119. si.Subject = "主题信息";//填加文件主题信息
  120. si.CreateDateTime = System.DateTime.Now;
  121. workbook.SummaryInformation = si;
  122. }
  123. #endregion
  124. #region 设置标题样式
  125. ICellStyle headStyle = workbook.CreateCellStyle();
  126. int[] arrColWidth = new int[dtSource.Columns.Count];
  127. string[] arrColName = new string[dtSource.Columns.Count];//列名
  128. ICellStyle[] arryColumStyle = new ICellStyle[dtSource.Columns.Count];//样式表
  129. headStyle.Alignment = HorizontalAlignment.Center; // ------------------
  130. if (excelConfig.Background != new Color())
  131. {
  132. if (excelConfig.Background != new Color())
  133. {
  134. headStyle.FillPattern = FillPattern.SolidForeground;
  135. headStyle.FillForegroundColor = GetXLColour(workbook, excelConfig.Background);
  136. }
  137. }
  138. IFont font = workbook.CreateFont();
  139. font.FontHeightInPoints = excelConfig.TitlePoint;
  140. if (excelConfig.ForeColor != new Color())
  141. {
  142. font.Color = GetXLColour(workbook, excelConfig.ForeColor);
  143. }
  144. font.Boldweight = 700;
  145. headStyle.SetFont(font);
  146. #endregion
  147. #region 列头及样式
  148. ICellStyle cHeadStyle = workbook.CreateCellStyle();
  149. cHeadStyle.Alignment = HorizontalAlignment.Center; // ------------------
  150. IFont cfont = workbook.CreateFont();
  151. cfont.FontHeightInPoints = excelConfig.HeadPoint;
  152. cHeadStyle.SetFont(cfont);
  153. #endregion
  154. #region 设置内容单元格样式
  155. foreach (DataColumn item in dtSource.Columns)
  156. {
  157. ICellStyle columnStyle = workbook.CreateCellStyle();
  158. columnStyle.Alignment = HorizontalAlignment.Center;
  159. arrColWidth[item.Ordinal] = Encoding.GetEncoding(936).GetBytes(item.ColumnName.ToString()).Length;
  160. arrColName[item.Ordinal] = item.ColumnName.ToString();
  161. if (excelConfig.ColumnEntity != null)
  162. {
  163. ColumnEntity columnentity = excelConfig.ColumnEntity.Find(t => t.Column == item.ColumnName);
  164. if (columnentity != null)
  165. {
  166. arrColName[item.Ordinal] = columnentity.ExcelColumn;
  167. if (columnentity.Width != 0)
  168. {
  169. arrColWidth[item.Ordinal] = columnentity.Width;
  170. }
  171. if (columnentity.Background != new Color())
  172. {
  173. if (columnentity.Background != new Color())
  174. {
  175. columnStyle.FillPattern = FillPattern.SolidForeground;
  176. columnStyle.FillForegroundColor = GetXLColour(workbook, columnentity.Background);
  177. }
  178. }
  179. if (columnentity.Font != null || columnentity.Point != 0 || columnentity.ForeColor != new Color())
  180. {
  181. IFont columnFont = workbook.CreateFont();
  182. columnFont.FontHeightInPoints = 10;
  183. if (columnentity.Font != null)
  184. {
  185. columnFont.FontName = columnentity.Font;
  186. }
  187. if (columnentity.Point != 0)
  188. {
  189. columnFont.FontHeightInPoints = columnentity.Point;
  190. }
  191. if (columnentity.ForeColor != new Color())
  192. {
  193. columnFont.Color = GetXLColour(workbook, columnentity.ForeColor);
  194. }
  195. columnStyle.SetFont(font);
  196. }
  197. columnStyle.Alignment = getAlignment(columnentity.Alignment);
  198. }
  199. }
  200. arryColumStyle[item.Ordinal] = columnStyle;
  201. }
  202. if (excelConfig.IsAllSizeColumn)
  203. {
  204. #region 根据列中最长列的长度取得列宽
  205. for (int i = 0; i < dtSource.Rows.Count; i++)
  206. {
  207. for (int j = 0; j < dtSource.Columns.Count; j++)
  208. {
  209. if (arrColWidth[j] != 0)
  210. {
  211. int intTemp = Encoding.GetEncoding(936).GetBytes(dtSource.Rows[i][j].ToString()).Length;
  212. if (intTemp > arrColWidth[j])
  213. {
  214. arrColWidth[j] = intTemp;
  215. }
  216. }
  217. }
  218. }
  219. #endregion
  220. }
  221. #endregion
  222. #region 填充数据
  223. #endregion
  224. ICellStyle dateStyle = workbook.CreateCellStyle();
  225. IDataFormat format = workbook.CreateDataFormat();
  226. dateStyle.DataFormat = format.GetFormat("yyyy-mm-dd");
  227. int rowIndex = 0;
  228. foreach (DataRow row in dtSource.Rows)
  229. {
  230. #region 新建表,填充表头,填充列头,样式
  231. if (rowIndex == 65535 || rowIndex == 0)
  232. {
  233. if (rowIndex != 0)
  234. {
  235. sheet = workbook.CreateSheet();
  236. }
  237. #region 表头及样式
  238. {
  239. if (excelConfig.Title != null)
  240. {
  241. IRow headerRow = sheet.CreateRow(0);
  242. if (excelConfig.TitleHeight != 0)
  243. {
  244. headerRow.Height = (short)(excelConfig.TitleHeight * 20);
  245. }
  246. headerRow.HeightInPoints = 25;
  247. headerRow.CreateCell(0).SetCellValue(excelConfig.Title);
  248. headerRow.GetCell(0).CellStyle = headStyle;
  249. sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(0, 0, 0, dtSource.Columns.Count - 1)); // ------------------
  250. }
  251. }
  252. #endregion
  253. #region 列头及样式
  254. {
  255. IRow headerRow = sheet.CreateRow(1);
  256. #region 如果设置了列标题就按列标题定义列头,没定义直接按字段名输出
  257. foreach (DataColumn column in dtSource.Columns)
  258. {
  259. headerRow.CreateCell(column.Ordinal).SetCellValue(arrColName[column.Ordinal]);
  260. headerRow.GetCell(column.Ordinal).CellStyle = cHeadStyle;
  261. //设置列宽
  262. sheet.SetColumnWidth(column.Ordinal, (arrColWidth[column.Ordinal] + 1) * 256);
  263. }
  264. #endregion
  265. }
  266. #endregion
  267. rowIndex = 2;
  268. }
  269. #endregion
  270. #region 填充内容
  271. IRow dataRow = sheet.CreateRow(rowIndex);
  272. foreach (DataColumn column in dtSource.Columns)
  273. {
  274. ICell newCell = dataRow.CreateCell(column.Ordinal);
  275. newCell.CellStyle = arryColumStyle[column.Ordinal];
  276. string drValue = row[column].ToString();
  277. SetCell(newCell, dateStyle, column.DataType, drValue);
  278. }
  279. #endregion
  280. rowIndex++;
  281. }
  282. using (MemoryStream ms = new MemoryStream())
  283. {
  284. workbook.Write(ms);
  285. ms.Flush();
  286. ms.Position = 0;
  287. return ms;
  288. }
  289. }
  290. #endregion
  291. #region ListExcel导出(加载模板)
  292. /// <summary>
  293. /// List根据模板导出ExcelMemoryStream
  294. /// </summary>
  295. /// <param name="list"></param>
  296. /// <param name="templdateName"></param>
  297. public static MemoryStream ExportListByTempale(List<TemplateMode> list, string templdateName)
  298. {
  299. try
  300. {
  301. string templatePath = HttpContext.Current.Server.MapPath("/") + "/Resource/ExcelTemplate/";
  302. string templdateName1 = string.Format("{0}{1}", templatePath, templdateName);
  303. FileStream fileStream = new FileStream(templdateName1, FileMode.Open, FileAccess.Read);
  304. ISheet sheet = null;
  305. if (templdateName.IndexOf(".xlsx") == -1)//2003
  306. {
  307. HSSFWorkbook hssfworkbook = new HSSFWorkbook(fileStream);
  308. sheet = hssfworkbook.GetSheetAt(0);
  309. SetPurchaseOrder(sheet, list);
  310. sheet.ForceFormulaRecalculation = true;
  311. using (MemoryStream ms = new MemoryStream())
  312. {
  313. hssfworkbook.Write(ms);
  314. ms.Flush();
  315. return ms;
  316. }
  317. }
  318. else//2007
  319. {
  320. XSSFWorkbook xssfworkbook = new XSSFWorkbook(fileStream);
  321. sheet = xssfworkbook.GetSheetAt(0);
  322. SetPurchaseOrder(sheet, list);
  323. sheet.ForceFormulaRecalculation = true;
  324. using (MemoryStream ms = new MemoryStream())
  325. {
  326. xssfworkbook.Write(ms);
  327. ms.Flush();
  328. return ms;
  329. }
  330. }
  331. }
  332. catch (Exception)
  333. {
  334. throw;
  335. }
  336. }
  337. /// <summary>
  338. /// 赋值单元格
  339. /// </summary>
  340. /// <param name="sheet"></param>
  341. /// <param name="list"></param>
  342. private static void SetPurchaseOrder(ISheet sheet, List<TemplateMode> list)
  343. {
  344. try
  345. {
  346. foreach (var item in list)
  347. {
  348. IRow row = null;
  349. ICell cell = null;
  350. row = sheet.GetRow(item.row);
  351. if (row == null)
  352. {
  353. row = sheet.CreateRow(item.row);
  354. }
  355. cell = row.GetCell(item.cell);
  356. if (cell == null)
  357. {
  358. cell = row.CreateCell(item.cell);
  359. }
  360. cell.SetCellValue(item.value);
  361. }
  362. }
  363. catch (Exception)
  364. {
  365. throw;
  366. }
  367. }
  368. #endregion
  369. #region 设置表格内容
  370. private static void SetCell(ICell newCell, ICellStyle dateStyle, Type dataType, string drValue)
  371. {
  372. switch (dataType.ToString())
  373. {
  374. case "System.String"://字符串类型
  375. newCell.SetCellValue(drValue);
  376. break;
  377. case "System.DateTime"://日期类型
  378. System.DateTime dateV;
  379. if (System.DateTime.TryParse(drValue, out dateV))
  380. {
  381. newCell.SetCellValue(dateV);
  382. }
  383. else
  384. {
  385. newCell.SetCellValue("");
  386. }
  387. newCell.CellStyle = dateStyle;//格式化显示
  388. break;
  389. case "System.Boolean"://布尔型
  390. bool boolV = false;
  391. bool.TryParse(drValue, out boolV);
  392. newCell.SetCellValue(boolV);
  393. break;
  394. case "System.Int16"://整型
  395. case "System.Int32":
  396. case "System.Int64":
  397. case "System.Byte":
  398. int intV = 0;
  399. int.TryParse(drValue, out intV);
  400. newCell.SetCellValue(intV);
  401. break;
  402. case "System.Decimal"://浮点型
  403. case "System.Double":
  404. double doubV = 0;
  405. double.TryParse(drValue, out doubV);
  406. newCell.SetCellValue(doubV);
  407. break;
  408. case "System.DBNull"://空值处理
  409. newCell.SetCellValue("");
  410. break;
  411. default:
  412. newCell.SetCellValue("");
  413. break;
  414. }
  415. }
  416. #endregion
  417. #region 从Excel导入
  418. /// <summary>
  419. /// 读取excel ,默认第一行为标头
  420. /// </summary>
  421. /// <param name="strFileName">excel文档路径</param>
  422. /// <returns></returns>
  423. public static DataTable ExcelImport(string strFileName)
  424. {
  425. DataTable dt = new DataTable();
  426. ISheet sheet = null;
  427. using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read))
  428. {
  429. if (strFileName.IndexOf(".xlsx") == -1)//2003
  430. {
  431. HSSFWorkbook hssfworkbook = new HSSFWorkbook(file);
  432. sheet = hssfworkbook.GetSheetAt(0);
  433. }
  434. else//2007
  435. {
  436. XSSFWorkbook xssfworkbook = new XSSFWorkbook(file);
  437. sheet = xssfworkbook.GetSheetAt(0);
  438. }
  439. }
  440. System.Collections.IEnumerator rows = sheet.GetRowEnumerator();
  441. IRow headerRow = sheet.GetRow(0);
  442. int cellCount = headerRow.LastCellNum;
  443. for (int j = 0; j < cellCount; j++)
  444. {
  445. ICell cell = headerRow.GetCell(j);
  446. dt.Columns.Add(cell.ToString());
  447. }
  448. for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++)
  449. {
  450. IRow row = sheet.GetRow(i);
  451. DataRow dataRow = dt.NewRow();
  452. for (int j = row.FirstCellNum; j < cellCount; j++)
  453. {
  454. if (row.GetCell(j) != null)
  455. dataRow[j] = row.GetCell(j).ToString();
  456. }
  457. dt.Rows.Add(dataRow);
  458. }
  459. return dt;
  460. }
  461. #endregion
  462. #region RGB颜色转NPOI颜色
  463. private static short GetXLColour(HSSFWorkbook workbook, Color SystemColour)
  464. {
  465. short s = 0;
  466. HSSFPalette XlPalette = workbook.GetCustomPalette();
  467. NPOI.HSSF.Util.HSSFColor XlColour = XlPalette.FindColor(SystemColour.R, SystemColour.G, SystemColour.B);
  468. if (XlColour == null)
  469. {
  470. if (NPOI.HSSF.Record.PaletteRecord.STANDARD_PALETTE_SIZE < 255)
  471. {
  472. XlColour = XlPalette.FindSimilarColor(SystemColour.R, SystemColour.G, SystemColour.B);
  473. s = XlColour.Indexed;
  474. }
  475. }
  476. else
  477. s = XlColour.Indexed;
  478. return s;
  479. }
  480. #endregion
  481. #region 设置列的对齐方式
  482. /// <summary>
  483. /// 设置对齐方式
  484. /// </summary>
  485. /// <param name="style"></param>
  486. /// <returns></returns>
  487. private static HorizontalAlignment getAlignment(string style)
  488. {
  489. switch (style)
  490. {
  491. case "center":
  492. return HorizontalAlignment.Center;
  493. case "left":
  494. return HorizontalAlignment.Left;
  495. case "right":
  496. return HorizontalAlignment.Right;
  497. case "fill":
  498. return HorizontalAlignment.Fill;
  499. case "justify":
  500. return HorizontalAlignment.Justify;
  501. case "centerselection":
  502. return HorizontalAlignment.CenterSelection;
  503. case "distributed":
  504. return HorizontalAlignment.Distributed;
  505. }
  506. return NPOI.SS.UserModel.HorizontalAlignment.General;
  507. }
  508. #endregion
  509. }
  510. }