ExcelHelper.cs 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990
  1. using Microsoft.AspNetCore.Mvc;
  2. using NPOI.HPSF;
  3. using NPOI.HSSF.UserModel;
  4. using NPOI.SS.UserModel;
  5. using NPOI.XSSF.UserModel;
  6. using System;
  7. using System.Collections.Generic;
  8. using System.Data;
  9. using System.Drawing;
  10. using System.IO;
  11. using System.Text;
  12. using System.Web;
  13. namespace WMS.Util
  14. {
  15. /// <summary>
  16. /// 描 述:NPOI Excel DataTable操作类
  17. /// </summary>
  18. public class ExcelHelper
  19. {
  20. public ExcelHelper()
  21. {
  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(MemoryStream ms, string FileName)
  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(FileName, Encoding.UTF8));
  38. // //调用导出具体方法Export()
  39. // curContext.Response.BinaryWrite(ms.GetBuffer());
  40. // curContext.Response.End();
  41. //}
  42. public static FileStreamResult ExcelDownload(MemoryStream ms, string fileName)
  43. {
  44. ms.Position = 0;
  45. return new FileStreamResult(ms, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
  46. {
  47. FileDownloadName = fileName
  48. };
  49. }
  50. /// <summary>
  51. /// Excel导出下载
  52. /// </summary>
  53. /// <param name="dtSource">DataTable数据源</param>
  54. /// <param name="excelConfig">导出设置包含文件名、标题、列设置</param>
  55. public static void ExcelDownload(DataTable dtSource, ExcelConfig excelConfig)
  56. {
  57. // var ms= ExportMemoryStream(dtSource, excelConfig);
  58. // ExcelDownload(ms, string fileName);
  59. //HttpContext curContext = HttpContext.Current;
  60. // // 设置编码和附件格式
  61. // curContext.Response.ContentType = "application/ms-excel";
  62. // curContext.Response.ContentEncoding = Encoding.UTF8;
  63. // curContext.Response.Charset = "";
  64. // curContext.Response.AppendHeader("Content-Disposition",
  65. // "attachment;filename=" + HttpUtility.UrlEncode(excelConfig.FileName, Encoding.UTF8));
  66. // //调用导出具体方法Export()
  67. // curContext.Response.BinaryWrite(ExportMemoryStream(dtSource, excelConfig).GetBuffer());
  68. // curContext.Response.End();
  69. }
  70. /// <summary>
  71. /// Excel导出下载
  72. /// </summary>
  73. /// <param name="list">数据源</param>
  74. /// <param name="templdateName">模板文件名</param>
  75. /// <param name="newFileName">文件名</param>
  76. public static void ExcelDownload(List<TemplateDataModel> list, string templdateName, string newFileName)
  77. {
  78. //HttpResponse response = System.Web.HttpContext.Current.Response;
  79. //response.Clear();
  80. //response.Charset = "UTF-8";
  81. //response.ContentType = "application/vnd-excel";//"application/vnd.ms-excel";
  82. //System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment; filename=" + newFileName));
  83. //System.Web.HttpContext.Current.Response.BinaryWrite(ExportListByTempale(list, templdateName).ToArray());
  84. }
  85. #endregion
  86. #region DataTable导出到Excel文件excelConfig中FileName设置为全路径
  87. /// <summary>
  88. /// DataTable导出到Excel文件 Export()
  89. /// </summary>
  90. /// <param name="dtSource">DataTable数据源</param>
  91. /// <param name="excelConfig">导出设置包含文件名、标题、列设置</param>
  92. public static void ExcelExport(DataTable dtSource, ExcelConfig excelConfig)
  93. {
  94. using (MemoryStream ms = ExportMemoryStream(dtSource, excelConfig))
  95. {
  96. using (FileStream fs = new FileStream(excelConfig.FileName, FileMode.Create, FileAccess.Write))
  97. {
  98. byte[] data = ms.ToArray();
  99. fs.Write(data, 0, data.Length);
  100. fs.Flush();
  101. }
  102. }
  103. }
  104. #endregion
  105. #region DataTable导出到Excel的MemoryStream
  106. /// <summary>
  107. /// DataTable导出到Excel的MemoryStream Export()
  108. /// </summary>
  109. /// <param name="dtSource">DataTable数据源</param>
  110. /// <param name="excelConfig">导出设置包含文件名、标题、列设置</param>
  111. public static MemoryStream ExportMemoryStream(DataTable dtSource, ExcelConfig excelConfig)
  112. {
  113. int colint = 0;
  114. for (int i = 0; i < dtSource.Columns.Count;)
  115. {
  116. DataColumn column = dtSource.Columns[i];
  117. if (excelConfig.ColumnEntity[colint].Column != column.ColumnName)
  118. {
  119. dtSource.Columns.Remove(column.ColumnName);
  120. }
  121. else
  122. {
  123. i++;
  124. if (colint < excelConfig.ColumnEntity.Count - 1)
  125. {
  126. colint++;
  127. }
  128. }
  129. }
  130. HSSFWorkbook workbook = new HSSFWorkbook();
  131. ISheet sheet = workbook.CreateSheet();
  132. #region 右击文件 属性信息
  133. {
  134. DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();
  135. dsi.Company = " ";
  136. workbook.DocumentSummaryInformation = dsi;
  137. SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
  138. si.Author = "BOZHON"; //填加xls文件作者信息
  139. si.ApplicationName = "BOZHON"; //填加xls文件创建程序信息
  140. si.LastAuthor = "BOZHON"; //填加xls文件最后保存者信息
  141. si.Comments = "BOZHON"; //填加xls文件作者信息
  142. si.Title = "标题信息"; //填加xls文件标题信息
  143. si.Subject = "主题信息";//填加文件主题信息
  144. si.CreateDateTime = System.DateTime.Now;
  145. workbook.SummaryInformation = si;
  146. }
  147. #endregion
  148. #region 设置标题样式
  149. ICellStyle headStyle = workbook.CreateCellStyle();
  150. int[] arrColWidth = new int[dtSource.Columns.Count];
  151. string[] arrColName = new string[dtSource.Columns.Count];//列名
  152. ICellStyle[] arryColumStyle = new ICellStyle[dtSource.Columns.Count];//样式表
  153. headStyle.Alignment = HorizontalAlignment.Center; // ------------------
  154. if (excelConfig.Background != new Color())
  155. {
  156. if (excelConfig.Background != new Color())
  157. {
  158. headStyle.FillPattern = FillPattern.SolidForeground;
  159. headStyle.FillForegroundColor = GetXLColour(workbook, excelConfig.Background);
  160. }
  161. }
  162. IFont font = workbook.CreateFont();
  163. font.FontHeightInPoints = excelConfig.TitlePoint;
  164. if (excelConfig.ForeColor != new Color())
  165. {
  166. font.Color = GetXLColour(workbook, excelConfig.ForeColor);
  167. }
  168. font.Boldweight = 700;
  169. headStyle.SetFont(font);
  170. #endregion
  171. #region 列头及样式
  172. ICellStyle cHeadStyle = workbook.CreateCellStyle();
  173. cHeadStyle.Alignment = HorizontalAlignment.Center; // ------------------
  174. IFont cfont = workbook.CreateFont();
  175. cfont.FontHeightInPoints = excelConfig.HeadPoint;
  176. cHeadStyle.SetFont(cfont);
  177. #endregion
  178. #region 设置内容单元格样式
  179. foreach (DataColumn item in dtSource.Columns)
  180. {
  181. ICellStyle columnStyle = workbook.CreateCellStyle();
  182. columnStyle.Alignment = HorizontalAlignment.Center;
  183. arrColWidth[item.Ordinal] = Encoding.GetEncoding(936).GetBytes(item.ColumnName.ToString()).Length;
  184. arrColName[item.Ordinal] = item.ColumnName.ToString();
  185. if (excelConfig.ColumnEntity != null)
  186. {
  187. ColumnModel columnentity = excelConfig.ColumnEntity.Find(t => t.Column == item.ColumnName);
  188. if (columnentity != null)
  189. {
  190. arrColName[item.Ordinal] = columnentity.ExcelColumn;
  191. if (columnentity.Width != 0)
  192. {
  193. arrColWidth[item.Ordinal] = columnentity.Width;
  194. }
  195. if (columnentity.Background != new Color())
  196. {
  197. if (columnentity.Background != new Color())
  198. {
  199. columnStyle.FillPattern = FillPattern.SolidForeground;
  200. columnStyle.FillForegroundColor = GetXLColour(workbook, columnentity.Background);
  201. }
  202. }
  203. if (columnentity.Font != null || columnentity.Point != 0 || columnentity.ForeColor != new Color())
  204. {
  205. IFont columnFont = workbook.CreateFont();
  206. columnFont.FontHeightInPoints = 10;
  207. if (columnentity.Font != null)
  208. {
  209. columnFont.FontName = columnentity.Font;
  210. }
  211. if (columnentity.Point != 0)
  212. {
  213. columnFont.FontHeightInPoints = columnentity.Point;
  214. }
  215. if (columnentity.ForeColor != new Color())
  216. {
  217. columnFont.Color = GetXLColour(workbook, columnentity.ForeColor);
  218. }
  219. columnStyle.SetFont(font);
  220. }
  221. columnStyle.Alignment = getAlignment(columnentity.Alignment);
  222. }
  223. }
  224. arryColumStyle[item.Ordinal] = columnStyle;
  225. }
  226. if (excelConfig.IsAllSizeColumn)
  227. {
  228. #region 根据列中最长列的长度取得列宽
  229. for (int i = 0; i < dtSource.Rows.Count; i++)
  230. {
  231. for (int j = 0; j < dtSource.Columns.Count; j++)
  232. {
  233. if (arrColWidth[j] != 0)
  234. {
  235. int intTemp = Encoding.GetEncoding(936).GetBytes(dtSource.Rows[i][j].ToString()).Length;
  236. if (intTemp > arrColWidth[j])
  237. {
  238. arrColWidth[j] = intTemp;
  239. }
  240. }
  241. }
  242. }
  243. #endregion
  244. }
  245. #endregion
  246. int rowIndex = 0;
  247. #region 表头及样式
  248. if (excelConfig.Title != null)
  249. {
  250. IRow headerRow = sheet.CreateRow(rowIndex);
  251. rowIndex++;
  252. if (excelConfig.TitleHeight != 0)
  253. {
  254. headerRow.Height = (short)(excelConfig.TitleHeight * 20);
  255. }
  256. headerRow.HeightInPoints = 25;
  257. headerRow.CreateCell(0).SetCellValue(excelConfig.Title);
  258. headerRow.GetCell(0).CellStyle = headStyle;
  259. sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(0, 0, 0, dtSource.Columns.Count - 1)); // ------------------
  260. }
  261. #endregion
  262. #region 列头及样式
  263. {
  264. IRow headerRow = sheet.CreateRow(rowIndex);
  265. rowIndex++;
  266. #region 如果设置了列标题就按列标题定义列头,没定义直接按字段名输出
  267. foreach (DataColumn column in dtSource.Columns)
  268. {
  269. headerRow.CreateCell(column.Ordinal).SetCellValue(arrColName[column.Ordinal]);
  270. headerRow.GetCell(column.Ordinal).CellStyle = cHeadStyle;
  271. //设置列宽
  272. //sheet.SetColumnWidth(column.Ordinal, (arrColWidth[column.Ordinal] + 1) * 256);
  273. int colWidth = (arrColWidth[column.Ordinal] + 1) * 256;
  274. if (colWidth < 255 * 256)
  275. {
  276. sheet.SetColumnWidth(column.Ordinal, colWidth < 3000 ? 3000 : colWidth);
  277. }
  278. else
  279. {
  280. sheet.SetColumnWidth(column.Ordinal, 6000);
  281. }
  282. }
  283. #endregion
  284. }
  285. #endregion
  286. ICellStyle dateStyle = workbook.CreateCellStyle();
  287. IDataFormat format = workbook.CreateDataFormat();
  288. dateStyle.DataFormat = format.GetFormat("yyyy-mm-dd");
  289. foreach (DataRow row in dtSource.Rows)
  290. {
  291. #region 新建表,填充表头,填充列头,样式
  292. if (rowIndex == 65535)
  293. {
  294. sheet = workbook.CreateSheet();
  295. rowIndex = 0;
  296. #region 表头及样式
  297. {
  298. if (excelConfig.Title != null)
  299. {
  300. IRow headerRow = sheet.CreateRow(rowIndex);
  301. rowIndex++;
  302. if (excelConfig.TitleHeight != 0)
  303. {
  304. headerRow.Height = (short)(excelConfig.TitleHeight * 20);
  305. }
  306. headerRow.HeightInPoints = 25;
  307. headerRow.CreateCell(0).SetCellValue(excelConfig.Title);
  308. headerRow.GetCell(0).CellStyle = headStyle;
  309. sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(0, 0, 0, dtSource.Columns.Count - 1)); // ------------------
  310. }
  311. }
  312. #endregion
  313. #region 列头及样式
  314. {
  315. IRow headerRow = sheet.CreateRow(rowIndex);
  316. rowIndex++;
  317. #region 如果设置了列标题就按列标题定义列头,没定义直接按字段名输出
  318. foreach (DataColumn column in dtSource.Columns)
  319. {
  320. headerRow.CreateCell(column.Ordinal).SetCellValue(arrColName[column.Ordinal]);
  321. headerRow.GetCell(column.Ordinal).CellStyle = cHeadStyle;
  322. //设置列宽
  323. sheet.SetColumnWidth(column.Ordinal, (arrColWidth[column.Ordinal] + 1) * 256);
  324. }
  325. #endregion
  326. }
  327. #endregion
  328. }
  329. #endregion
  330. #region 填充内容
  331. IRow dataRow = sheet.CreateRow(rowIndex);
  332. foreach (DataColumn column in dtSource.Columns)
  333. {
  334. ICell newCell = dataRow.CreateCell(column.Ordinal);
  335. newCell.CellStyle = arryColumStyle[column.Ordinal];
  336. string drValue = row[column].ToString();
  337. SetCell(newCell, dateStyle, column.DataType, drValue);
  338. }
  339. #endregion
  340. rowIndex++;
  341. }
  342. MemoryStream ms = new MemoryStream();
  343. workbook.Write(ms);
  344. ms.Flush();
  345. ms.Position = 0;
  346. return ms;
  347. }
  348. #endregion
  349. #region DataTable导出到Excel的MemoryStream
  350. /// <summary>
  351. /// DataTable导出到Excel的MemoryStream Export()
  352. /// </summary>
  353. /// <param name="dtSource">DataTable数据源</param>
  354. /// <param name="excelConfig">导出设置包含文件名、标题、列设置</param>
  355. public static MemoryStream NewExportMemoryStream(DataTable dtSource, ExcelConfig excelConfig)
  356. {
  357. DataTable dt = dtSource.Clone();
  358. var columns = dt.Columns;
  359. foreach (DataColumn column in columns)
  360. {
  361. bool v = excelConfig.ColumnEntity.Exists(t => t.Column == column.ColumnName);
  362. if (!v)
  363. {
  364. dtSource.Columns.Remove(column.ColumnName);
  365. }
  366. }
  367. HSSFWorkbook workbook = new HSSFWorkbook();
  368. ISheet sheet = workbook.CreateSheet();
  369. #region 右击文件 属性信息
  370. {
  371. DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();
  372. dsi.Company = "BZ";
  373. workbook.DocumentSummaryInformation = dsi;
  374. SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
  375. si.Author = "BOZHON"; //填加xls文件作者信息
  376. si.ApplicationName = "BOZHON"; //填加xls文件创建程序信息
  377. si.LastAuthor = "BOZHON"; //填加xls文件最后保存者信息
  378. si.Comments = "BOZHON"; //填加xls文件作者信息
  379. si.Title = "标题信息"; //填加xls文件标题信息
  380. si.Subject = "主题信息";//填加文件主题信息
  381. si.CreateDateTime = System.DateTime.Now;
  382. workbook.SummaryInformation = si;
  383. }
  384. #endregion
  385. #region 设置标题样式
  386. ICellStyle headStyle = workbook.CreateCellStyle();
  387. int[] arrColWidth = new int[dtSource.Columns.Count];
  388. string[] arrColName = new string[dtSource.Columns.Count];//列名
  389. ICellStyle[] arryColumStyle = new ICellStyle[dtSource.Columns.Count];//样式表
  390. headStyle.Alignment = HorizontalAlignment.Center; // ------------------
  391. if (excelConfig.Background != new Color())
  392. {
  393. if (excelConfig.Background != new Color())
  394. {
  395. headStyle.FillPattern = FillPattern.SolidForeground;
  396. headStyle.FillForegroundColor = GetXLColour(workbook, excelConfig.Background);
  397. }
  398. }
  399. IFont font = workbook.CreateFont();
  400. font.FontHeightInPoints = excelConfig.TitlePoint;
  401. if (excelConfig.ForeColor != new Color())
  402. {
  403. font.Color = GetXLColour(workbook, excelConfig.ForeColor);
  404. }
  405. font.IsBold = true;
  406. headStyle.SetFont(font);
  407. #endregion
  408. #region 列头及样式
  409. ICellStyle cHeadStyle = workbook.CreateCellStyle();
  410. cHeadStyle.Alignment = HorizontalAlignment.Center; // ------------------
  411. IFont cfont = workbook.CreateFont();
  412. cfont.FontHeightInPoints = excelConfig.HeadPoint;
  413. cHeadStyle.SetFont(cfont);
  414. #endregion
  415. #region 设置内容单元格样式
  416. foreach (DataColumn item in dtSource.Columns)
  417. {
  418. ICellStyle columnStyle = workbook.CreateCellStyle();
  419. columnStyle.Alignment = HorizontalAlignment.Center;
  420. arrColWidth[item.Ordinal] = Encoding.GetEncoding(936).GetBytes(item.ColumnName.ToString()).Length;
  421. arrColName[item.Ordinal] = item.ColumnName.ToString();
  422. if (excelConfig.ColumnEntity != null)
  423. {
  424. ColumnModel columnentity = excelConfig.ColumnEntity.Find(t => t.Column == item.ColumnName);
  425. if (columnentity != null)
  426. {
  427. arrColName[item.Ordinal] = columnentity.ExcelColumn;
  428. if (columnentity.Width != 0)
  429. {
  430. arrColWidth[item.Ordinal] = columnentity.Width;
  431. }
  432. if (columnentity.Background != new Color())
  433. {
  434. if (columnentity.Background != new Color())
  435. {
  436. columnStyle.FillPattern = FillPattern.SolidForeground;
  437. columnStyle.FillForegroundColor = GetXLColour(workbook, columnentity.Background);
  438. }
  439. }
  440. if (columnentity.Font != null || columnentity.Point != 0 || columnentity.ForeColor != new Color())
  441. {
  442. IFont columnFont = workbook.CreateFont();
  443. columnFont.FontHeightInPoints = 10;
  444. if (columnentity.Font != null)
  445. {
  446. columnFont.FontName = columnentity.Font;
  447. }
  448. if (columnentity.Point != 0)
  449. {
  450. columnFont.FontHeightInPoints = columnentity.Point;
  451. }
  452. if (columnentity.ForeColor != new Color())
  453. {
  454. columnFont.Color = GetXLColour(workbook, columnentity.ForeColor);
  455. }
  456. columnStyle.SetFont(font);
  457. }
  458. columnStyle.Alignment = getAlignment(columnentity.Alignment);
  459. }
  460. }
  461. arryColumStyle[item.Ordinal] = columnStyle;
  462. }
  463. if (excelConfig.IsAllSizeColumn)
  464. {
  465. #region 根据列中最长列的长度取得列宽
  466. for (int i = 0; i < dtSource.Rows.Count; i++)
  467. {
  468. for (int j = 0; j < dtSource.Columns.Count; j++)
  469. {
  470. if (arrColWidth[j] != 0)
  471. {
  472. int intTemp = Encoding.GetEncoding(936).GetBytes(dtSource.Rows[i][j].ToString()).Length;
  473. if (intTemp > arrColWidth[j])
  474. {
  475. arrColWidth[j] = intTemp;
  476. }
  477. }
  478. }
  479. }
  480. #endregion
  481. }
  482. #endregion
  483. int rowIndex = 0;
  484. #region 表头及样式
  485. if (excelConfig.Title != null)
  486. {
  487. IRow headerRow = sheet.CreateRow(rowIndex);
  488. rowIndex++;
  489. if (excelConfig.TitleHeight != 0)
  490. {
  491. headerRow.Height = (short)(excelConfig.TitleHeight * 20);
  492. }
  493. headerRow.HeightInPoints = 25;
  494. headerRow.CreateCell(0).SetCellValue(excelConfig.Title);
  495. headerRow.GetCell(0).CellStyle = headStyle;
  496. if (dtSource.Columns.Count > 1)
  497. {
  498. sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(0, 0, 0, dtSource.Columns.Count - 1)); // ------------------
  499. }
  500. }
  501. #endregion
  502. #region 列头及样式
  503. {
  504. IRow headerRow = sheet.CreateRow(rowIndex);
  505. rowIndex++;
  506. #region 如果设置了列标题就按列标题定义列头,没定义直接按字段名输出
  507. foreach (DataColumn column in dtSource.Columns)
  508. {
  509. headerRow.CreateCell(column.Ordinal).SetCellValue(arrColName[column.Ordinal]);
  510. headerRow.GetCell(column.Ordinal).CellStyle = cHeadStyle;
  511. //设置列宽
  512. //sheet.SetColumnWidth(column.Ordinal, (arrColWidth[column.Ordinal] + 1) * 256);
  513. int colWidth = (arrColWidth[column.Ordinal] + 1) * 256;
  514. if (colWidth < 255 * 256)
  515. {
  516. sheet.SetColumnWidth(column.Ordinal, colWidth < 3000 ? 3000 : colWidth);
  517. }
  518. else
  519. {
  520. sheet.SetColumnWidth(column.Ordinal, 6000);
  521. }
  522. }
  523. #endregion
  524. }
  525. #endregion
  526. ICellStyle dateStyle = workbook.CreateCellStyle();
  527. IDataFormat format = workbook.CreateDataFormat();
  528. dateStyle.DataFormat = format.GetFormat("yyyy-mm-dd");
  529. foreach (DataRow row in dtSource.Rows)
  530. {
  531. #region 新建表,填充表头,填充列头,样式
  532. if (rowIndex == 65535)
  533. {
  534. sheet = workbook.CreateSheet();
  535. rowIndex = 0;
  536. #region 表头及样式
  537. {
  538. if (excelConfig.Title != null)
  539. {
  540. IRow headerRow = sheet.CreateRow(rowIndex);
  541. rowIndex++;
  542. if (excelConfig.TitleHeight != 0)
  543. {
  544. headerRow.Height = (short)(excelConfig.TitleHeight * 20);
  545. }
  546. headerRow.HeightInPoints = 25;
  547. headerRow.CreateCell(0).SetCellValue(excelConfig.Title);
  548. headerRow.GetCell(0).CellStyle = headStyle;
  549. sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(0, 0, 0, dtSource.Columns.Count - 1)); // ------------------
  550. }
  551. }
  552. #endregion
  553. #region 列头及样式
  554. {
  555. IRow headerRow = sheet.CreateRow(rowIndex);
  556. rowIndex++;
  557. #region 如果设置了列标题就按列标题定义列头,没定义直接按字段名输出
  558. foreach (DataColumn column in dtSource.Columns)
  559. {
  560. headerRow.CreateCell(column.Ordinal).SetCellValue(arrColName[column.Ordinal]);
  561. headerRow.GetCell(column.Ordinal).CellStyle = cHeadStyle;
  562. //设置列宽
  563. sheet.SetColumnWidth(column.Ordinal, (arrColWidth[column.Ordinal] + 1) * 256);
  564. }
  565. #endregion
  566. }
  567. #endregion
  568. }
  569. #endregion
  570. #region 填充内容
  571. IRow dataRow = sheet.CreateRow(rowIndex);
  572. foreach (DataColumn column in dtSource.Columns)
  573. {
  574. ICell newCell = dataRow.CreateCell(column.Ordinal);
  575. newCell.CellStyle = arryColumStyle[column.Ordinal];
  576. string drValue = row[column].ToString();
  577. SetCell(newCell, dateStyle, column.DataType, drValue);
  578. }
  579. #endregion
  580. rowIndex++;
  581. }
  582. MemoryStream ms = new MemoryStream();
  583. workbook.Write(ms);
  584. ms.Flush();
  585. ms.Position = 0;
  586. return ms;
  587. }
  588. #endregion
  589. #region ListExcel导出(加载模板)
  590. /// <summary>
  591. /// List根据模板导出ExcelMemoryStream
  592. /// </summary>
  593. /// <param name="list"></param>
  594. /// <param name="templdateName"></param>
  595. public static MemoryStream ExportListByTempale(List<TemplateDataModel> list, string templdateName)
  596. {
  597. try
  598. {
  599. string templatePath = "";// HttpContext.Current.Server.MapPath("/") + "/Resource/ExcelTemplate/";
  600. string templdateName1 = string.Format("{0}{1}", templatePath, templdateName);
  601. FileStream fileStream = new FileStream(templdateName1, FileMode.Open, FileAccess.Read);
  602. ISheet sheet = null;
  603. if (templdateName.IndexOf(".xlsx") == -1)//2003
  604. {
  605. HSSFWorkbook hssfworkbook = new HSSFWorkbook(fileStream);
  606. sheet = hssfworkbook.GetSheetAt(0);
  607. SetPurchaseOrder(sheet, list);
  608. sheet.ForceFormulaRecalculation = true;
  609. using (MemoryStream ms = new MemoryStream())
  610. {
  611. hssfworkbook.Write(ms);
  612. ms.Flush();
  613. return ms;
  614. }
  615. }
  616. else//2007
  617. {
  618. XSSFWorkbook xssfworkbook = new XSSFWorkbook(fileStream);
  619. sheet = xssfworkbook.GetSheetAt(0);
  620. SetPurchaseOrder(sheet, list);
  621. sheet.ForceFormulaRecalculation = true;
  622. using (MemoryStream ms = new MemoryStream())
  623. {
  624. xssfworkbook.Write(ms);
  625. ms.Flush();
  626. return ms;
  627. }
  628. }
  629. }
  630. catch (Exception)
  631. {
  632. throw;
  633. }
  634. }
  635. /// <summary>
  636. /// 赋值单元格
  637. /// </summary>
  638. /// <param name="sheet"></param>
  639. /// <param name="list"></param>
  640. private static void SetPurchaseOrder(ISheet sheet, List<TemplateDataModel> list)
  641. {
  642. try
  643. {
  644. foreach (var item in list)
  645. {
  646. IRow row = null;
  647. ICell cell = null;
  648. row = sheet.GetRow(item.row);
  649. if (row == null)
  650. {
  651. row = sheet.CreateRow(item.row);
  652. }
  653. cell = row.GetCell(item.cell);
  654. if (cell == null)
  655. {
  656. cell = row.CreateCell(item.cell);
  657. }
  658. cell.SetCellValue(item.value);
  659. }
  660. }
  661. catch (Exception)
  662. {
  663. throw;
  664. }
  665. }
  666. #endregion
  667. #region 设置表格内容
  668. public static void SetCell(ICell newCell, ICellStyle dateStyle, Type dataType, string drValue)
  669. {
  670. switch (dataType.ToString())
  671. {
  672. case "System.String"://字符串类型
  673. newCell.SetCellValue(drValue);
  674. break;
  675. case "System.DateTime"://日期类型
  676. System.DateTime dateV;
  677. if (System.DateTime.TryParse(drValue, out dateV))
  678. {
  679. newCell.SetCellValue(dateV);
  680. }
  681. else
  682. {
  683. newCell.SetCellValue("");
  684. }
  685. newCell.CellStyle = dateStyle;//格式化显示
  686. break;
  687. case "System.Boolean"://布尔型
  688. bool boolV = false;
  689. bool.TryParse(drValue, out boolV);
  690. newCell.SetCellValue(boolV);
  691. break;
  692. case "System.Int16"://整型
  693. case "System.Int32":
  694. case "System.Int64":
  695. case "System.Byte":
  696. int intV = 0;
  697. int.TryParse(drValue, out intV);
  698. newCell.SetCellValue(intV);
  699. break;
  700. case "System.Decimal"://浮点型
  701. case "System.Double":
  702. double doubV = 0;
  703. double.TryParse(drValue, out doubV);
  704. newCell.SetCellValue(doubV);
  705. break;
  706. case "System.DBNull"://空值处理
  707. newCell.SetCellValue("");
  708. break;
  709. default:
  710. newCell.SetCellValue("");
  711. break;
  712. }
  713. }
  714. #endregion
  715. #region 从Excel导入
  716. /// <summary>
  717. /// 读取excel ,默认第一行为标头
  718. /// </summary>
  719. /// <param name="strFileName">excel文档路径</param>
  720. /// <returns></returns>
  721. public static DataTable ExcelImport(string strFileName)
  722. {
  723. DataTable dt = new DataTable();
  724. ISheet sheet = null;
  725. using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read))
  726. {
  727. if (strFileName.IndexOf(".xlsx") == -1)//2003
  728. {
  729. HSSFWorkbook hssfworkbook = new HSSFWorkbook(file);
  730. sheet = hssfworkbook.GetSheetAt(0);
  731. }
  732. else//2007
  733. {
  734. XSSFWorkbook xssfworkbook = new XSSFWorkbook(file);
  735. sheet = xssfworkbook.GetSheetAt(0);
  736. }
  737. }
  738. System.Collections.IEnumerator rows = sheet.GetRowEnumerator();
  739. IRow headerRow = sheet.GetRow(0);
  740. int cellCount = headerRow.LastCellNum;
  741. for (int j = 0; j < cellCount; j++)
  742. {
  743. ICell cell = headerRow.GetCell(j);
  744. dt.Columns.Add(cell.ToString());
  745. }
  746. for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++)
  747. {
  748. IRow row = sheet.GetRow(i);
  749. DataRow dataRow = dt.NewRow();
  750. for (int j = row.FirstCellNum; j < cellCount; j++)
  751. {
  752. if (row.GetCell(j) != null)
  753. dataRow[j] = row.GetCell(j).ToString();
  754. }
  755. dt.Rows.Add(dataRow);
  756. }
  757. return dt;
  758. }
  759. public static DataTable ExcelImport(string strFileName, string SheetName, int heatRow)
  760. {
  761. DataTable dt = new DataTable();
  762. ISheet sheet = null;
  763. using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read))
  764. {
  765. if (strFileName.ToLower().IndexOf(".xlsx") == -1)//2003
  766. {
  767. HSSFWorkbook hssfworkbook = new HSSFWorkbook(file);
  768. sheet = hssfworkbook.GetSheet(SheetName);//.GetSheetAt(sheetindex);
  769. }
  770. else//2007
  771. {
  772. XSSFWorkbook xssfworkbook = new XSSFWorkbook(file);
  773. sheet = xssfworkbook.GetSheet(SheetName);//.GetSheetAt(sheetindex);
  774. }
  775. }
  776. System.Collections.IEnumerator rows = sheet.GetRowEnumerator();
  777. IRow headerRow = sheet.GetRow(heatRow);
  778. int cellCount = headerRow.LastCellNum;
  779. for (int j = 0; j < cellCount; j++)
  780. {
  781. ICell cell = headerRow.GetCell(j);
  782. dt.Columns.Add(cell.ToString());
  783. }
  784. for (int i = (sheet.FirstRowNum + heatRow + 1); i <= sheet.LastRowNum; i++)
  785. {
  786. IRow row = sheet.GetRow(i);
  787. DataRow dataRow = dt.NewRow();
  788. for (int j = row.FirstCellNum; j < cellCount; j++)
  789. {
  790. if (row.GetCell(j) != null)
  791. dataRow[j] = row.GetCell(j).ToString();
  792. }
  793. dt.Rows.Add(dataRow);
  794. }
  795. return dt;
  796. }
  797. /// <summary>
  798. /// 读取excel ,默认第一行为标头
  799. /// </summary>
  800. /// <param name="fileStream">文件数据流</param>
  801. /// <returns></returns>
  802. public static DataTable ExcelImport(Stream fileStream, string flieType)
  803. {
  804. DataTable dt = new DataTable();
  805. ISheet sheet = null;
  806. if (flieType == ".xls")
  807. {
  808. HSSFWorkbook hssfworkbook = new HSSFWorkbook(fileStream);
  809. sheet = hssfworkbook.GetSheetAt(0);
  810. }
  811. else
  812. {
  813. fileStream.Position = 0;
  814. XSSFWorkbook xssfworkbook = new XSSFWorkbook(fileStream);
  815. sheet = xssfworkbook.GetSheetAt(0);
  816. }
  817. System.Collections.IEnumerator rows = sheet.GetRowEnumerator();
  818. IRow headerRow = sheet.GetRow(0);
  819. int cellCount = headerRow.LastCellNum;
  820. for (int j = 0; j < cellCount; j++)
  821. {
  822. ICell cell = headerRow.GetCell(j);
  823. dt.Columns.Add(cell.ToString());
  824. }
  825. int l = 0;
  826. try
  827. {
  828. for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++)
  829. {
  830. IRow row = sheet.GetRow(i);
  831. if (row == null)
  832. continue;
  833. DataRow dataRow = dt.NewRow();
  834. for (int j = row.FirstCellNum; j < cellCount; j++)
  835. {
  836. if (row.GetCell(j) != null)
  837. {
  838. //如果是公式Cell
  839. //则仅读取其Cell单元格的显示值 而不是读取公式
  840. if (row.GetCell(j).CellType == CellType.Formula)
  841. {
  842. row.GetCell(j).SetCellType(CellType.String);
  843. dataRow[j] = row.GetCell(j).StringCellValue;
  844. }
  845. else
  846. {
  847. dataRow[j] = row.GetCell(j).ToString();
  848. }
  849. //dataRow[j] = row.GetCell(j).ToString();
  850. }
  851. }
  852. l = i;
  853. dt.Rows.Add(dataRow);
  854. }
  855. }
  856. catch (Exception ex)
  857. {
  858. throw;
  859. }
  860. return dt;
  861. }
  862. #endregion
  863. #region RGB颜色转NPOI颜色
  864. private static short GetXLColour(HSSFWorkbook workbook, Color SystemColour)
  865. {
  866. short s = 0;
  867. HSSFPalette XlPalette = workbook.GetCustomPalette();
  868. NPOI.HSSF.Util.HSSFColor XlColour = XlPalette.FindColor(SystemColour.R, SystemColour.G, SystemColour.B);
  869. if (XlColour == null)
  870. {
  871. if (NPOI.HSSF.Record.PaletteRecord.STANDARD_PALETTE_SIZE < 255)
  872. {
  873. XlColour = XlPalette.FindSimilarColor(SystemColour.R, SystemColour.G, SystemColour.B);
  874. s = XlColour.Indexed;
  875. }
  876. }
  877. else
  878. s = XlColour.Indexed;
  879. return s;
  880. }
  881. #endregion
  882. #region 设置列的对齐方式
  883. /// <summary>
  884. /// 设置对齐方式
  885. /// </summary>
  886. /// <param name="style"></param>
  887. /// <returns></returns>
  888. private static HorizontalAlignment getAlignment(string style)
  889. {
  890. switch (style)
  891. {
  892. case "center":
  893. return HorizontalAlignment.Center;
  894. case "left":
  895. return HorizontalAlignment.Left;
  896. case "right":
  897. return HorizontalAlignment.Right;
  898. case "fill":
  899. return HorizontalAlignment.Fill;
  900. case "justify":
  901. return HorizontalAlignment.Justify;
  902. case "centerselection":
  903. return HorizontalAlignment.CenterSelection;
  904. case "distributed":
  905. return HorizontalAlignment.Distributed;
  906. }
  907. return NPOI.SS.UserModel.HorizontalAlignment.General;
  908. }
  909. #endregion
  910. }
  911. }