ExcelHelper.cs 21 KB

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