AsposeExcelHelper.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using Aspose.Cells;
  6. using System.Data;
  7. using System.IO;
  8. using System.Text.RegularExpressions;
  9. using System.Drawing;
  10. namespace EMIS.Utility
  11. {
  12. public class AsposeCellStyle
  13. {
  14. public int RowIndex;
  15. public int ColIndex;
  16. public Style cellStyle;
  17. public AsposeCellStyle(int aColIndex, int aRowIndex, Style aCellStyle)
  18. {
  19. this.RowIndex = aRowIndex;
  20. this.ColIndex = aColIndex;
  21. this.cellStyle = aCellStyle;
  22. }
  23. }
  24. public class AsposeExcelCellStyle
  25. {
  26. /// <summary>
  27. /// 应用样式的列序号,从0开始
  28. /// </summary>
  29. public int ColumnIndex { get; set; }
  30. /// <summary>
  31. /// 应用样式的行序号,从0开始
  32. /// </summary>
  33. public int RowIndex { get; set; }
  34. public Func<Workbook, Style> StyleFunc { get; set; }
  35. }
  36. public class AsposeExcelHelper
  37. {
  38. private List<IGrouping<Func<Workbook, Style>, AsposeExcelCellStyle>> _cellStyleListField;
  39. private List<IGrouping<Func<Workbook, Style>, AsposeExcelCellStyle>> _cellStyleList
  40. {
  41. get
  42. {
  43. if (_cellStyleListField == null)
  44. {
  45. _cellStyleListField = new List<IGrouping<Func<Workbook, Style>, AsposeExcelCellStyle>>();
  46. }
  47. return _cellStyleListField;
  48. }
  49. set
  50. {
  51. _cellStyleListField = value;
  52. }
  53. }
  54. private static Regex NumberRegex
  55. {
  56. get
  57. {
  58. return new Regex("^-?[0-9]+(\\.[0-9]*[1-9]){0,1}$");
  59. }
  60. }
  61. public void PresetCellStyle(List<AsposeExcelCellStyle> cellStyleList)
  62. {
  63. var styleGroup = cellStyleList.GroupBy(x => x.StyleFunc).ToList();
  64. this._cellStyleList = styleGroup;
  65. }
  66. public MemoryStream ExportToTemplate(Stream templateFileStream, List<CellItem> cellItems, List<ListItem> listItems)
  67. {
  68. return ExportToTemplate(templateFileStream, cellItems, listItems, new List<PictureItem>());
  69. }
  70. public MemoryStream ExportToTemplate(Stream templateFileStream, List<CellItem> cellItems, List<ListItem> listItems, List<PictureItem> pictureItems)
  71. {
  72. return ExportToTemplate(templateFileStream, cellItems, listItems, pictureItems, new List<CellArea>());
  73. }
  74. public MemoryStream ExportToTemplate(Stream templateFileStream, List<CellItem> cellItems, List<ListItem> listItems, List<PictureItem> pictureItems, List<CellArea> mergeList)
  75. {
  76. return ExportToTemplate(templateFileStream, new List<PageItem>
  77. {
  78. new AsposePageItem
  79. {
  80. CellItemList = cellItems,
  81. ListItemList = listItems,
  82. PictureItemList = pictureItems,
  83. MergeList = mergeList
  84. }
  85. });
  86. }
  87. public MemoryStream ExportToTemplate(Stream templateFileStream, List<PageItem> pageItems)
  88. {
  89. //Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
  90. Workbook wk;
  91. wk = new Workbook(templateFileStream);
  92. var templateSheetCount = wk.Worksheets.Count;
  93. for (int i = templateSheetCount; i < pageItems.Count; i += templateSheetCount)
  94. {
  95. for (int index = 0; index < templateSheetCount; index++)
  96. {
  97. wk.Worksheets.AddCopy(index); //.CopyTo(wk, "Sheet" + (i + 1).ToString(), true, true);
  98. }
  99. }
  100. int sheetIndex = 0;
  101. pageItems.ForEach(x =>
  102. {
  103. int addRows = 0;
  104. var cellItemStyleList = x.CellItemList.Where(w => w is AsposeCellItem).Where(w => ((AsposeCellItem)w).Style != null).GroupBy(w => ((AsposeCellItem)w).Style)
  105. .SelectMany(w => w.Select(v => new AsposeCellStyle(v.Col, v.Row, w.Key.Invoke(wk)))).ToList();
  106. var listItemStyleList = x.ListItemList.Where(w => w is AsposeListItem).SelectMany(w => ((AsposeListItem)w).StyleList.Select(v => new
  107. {
  108. ListItem = w,
  109. v.RowIndex,
  110. v.ColumnIndex,
  111. v.StyleFunc
  112. })).Where(w => w.StyleFunc != null).GroupBy(w => w.StyleFunc).SelectMany(w => w.Select(v => new { v.ListItem, v.ColumnIndex, v.RowIndex, CellStyle = w.Key.Invoke(wk) })).ToList();
  113. Worksheet sheet = wk.Worksheets[sheetIndex];
  114. if (!string.IsNullOrEmpty(x.Name))
  115. {
  116. sheet.Name = x.Name;
  117. }
  118. foreach (var columnWith in x.ColumnWidthList)
  119. {
  120. sheet.Cells.SetColumnWidth(columnWith.Key, columnWith.Value);
  121. }
  122. if (x is AsposePageItem)
  123. {
  124. var insertColumnList = ((AsposePageItem)x).InsertColumnItemList;
  125. insertColumnList.OrderByDescending(y => y.ColumnIndex).ToList()
  126. .ForEach(y =>
  127. {
  128. if (y.InsertCount > 0)
  129. {
  130. sheet.Cells.InsertColumns(y.ColumnIndex, y.InsertCount);
  131. }
  132. });
  133. }
  134. foreach (var cellItem in x.CellItemList)
  135. {
  136. var cell = sheet.Cells[cellItem.Row, cellItem.Col];
  137. if (!string.IsNullOrEmpty(cellItem.Value))
  138. {
  139. if (cell.GetStyle().Number != 49 && NumberRegex.IsMatch(cellItem.Value))
  140. {
  141. cell.PutValue(Convert.ToDecimal(cellItem.Value));
  142. }
  143. else
  144. {
  145. cell.PutValue(cellItem.Value);
  146. }
  147. }
  148. //if (cellItem is AsposeCellItem)
  149. //{
  150. // var customerStyleFunc = ((AsposeCellItem)cellItem).Style;
  151. // if (customerStyleFunc != null)
  152. // {
  153. // cell.SetStyle(customerStyleFunc.Invoke(wk));
  154. // }
  155. //}
  156. //var style = cell.GetStyle();
  157. //if (cell.GetHeightOfValue() > sheet.Cells.GetRowHeight(cell.Row))
  158. //{
  159. // style.IsTextWrapped = true;
  160. // sheet.AutoFitRow(cell.Row);
  161. //}
  162. //cell.SetStyle(style);
  163. //cell.GetStyle().IsTextWrapped = true;
  164. }
  165. if (x is AsposePageItem)
  166. {
  167. foreach (var merge in ((AsposePageItem)x).MergeList)
  168. {
  169. sheet.Cells.Merge(merge.StartRow, merge.StartColumn, (merge.EndRow - merge.StartRow + 1), (merge.EndColumn - merge.StartColumn + 1));
  170. }
  171. }
  172. foreach (var styleItem in cellItemStyleList)
  173. {
  174. var cell = sheet.Cells[styleItem.RowIndex, styleItem.ColIndex];
  175. cell.SetStyle(styleItem.cellStyle);
  176. }
  177. foreach (var cellItem in x.CellItemList)
  178. {
  179. var cell = sheet.Cells[cellItem.Row, cellItem.Col];
  180. var style = cell.GetStyle();
  181. if (cell.GetHeightOfValue() > sheet.Cells.GetRowHeight(cell.Row))
  182. {
  183. style.IsTextWrapped = true;
  184. sheet.AutoFitRow(cell.Row);
  185. }
  186. cell.SetStyle(style);
  187. }
  188. foreach (var listItem in x.ListItemList)
  189. {
  190. var customerStyleList = listItemStyleList.Where(y => y.ListItem == listItem).ToList();
  191. int startRow = listItem.StartRow + addRows;
  192. int curRow = startRow;
  193. if (!(listItem is AsposeListItem) || ((AsposeListItem)listItem).IsInsertRow == true)
  194. {
  195. for (int i = 1; i < listItem.Values.Length; i++)
  196. {
  197. sheet.Cells.InsertRow(startRow + i);
  198. addRows++;
  199. }
  200. }
  201. for (int itemIndex = 0; itemIndex < listItem.Values.Length; itemIndex++)
  202. {
  203. var item = listItem.Values[itemIndex];
  204. var row = sheet.Cells.GetRow(curRow);
  205. for (int i = 0; i < item.Length; i++)
  206. {
  207. var col = listItem.StartColumn + i;
  208. if (col > listItem.EndColumn)
  209. {
  210. break;
  211. }
  212. var value = item[i];
  213. if (value != null && sheet.Cells[curRow, col].GetStyle().Number != 49 && NumberRegex.IsMatch(value))
  214. {
  215. sheet.Cells[curRow, col].PutValue(Convert.ToDecimal(value));
  216. }
  217. else
  218. {
  219. sheet.Cells[curRow, col].PutValue(value);
  220. }
  221. }
  222. curRow++;
  223. }
  224. if (listItem is AsposeListItem)
  225. {
  226. var mergeList = ((AsposeListItem)listItem).MergeList;
  227. if (mergeList != null)
  228. {
  229. mergeList = mergeList.OrderBy(y => y.StartRow).ThenBy(y => y.StartColumn).ToList();
  230. foreach (var merge in mergeList)
  231. {
  232. sheet.Cells.Merge(startRow + merge.StartRow, merge.StartColumn, (merge.EndRow - merge.StartRow + 1), (merge.EndColumn - merge.StartColumn + 1));
  233. }
  234. }
  235. }
  236. foreach (var style in customerStyleList)
  237. {
  238. var row = sheet.Cells.GetRow(startRow + style.RowIndex);
  239. var col = listItem.StartColumn + style.ColumnIndex;
  240. var cell = row.GetCellOrNull(col);
  241. if (cell == null)
  242. {
  243. sheet.Cells[startRow + style.RowIndex, col].PutValue("");
  244. cell = row.GetCellOrNull(col);
  245. }
  246. cell.SetStyle(style.CellStyle);
  247. }
  248. for (int itemIndex = 0; itemIndex < listItem.Values.Length; itemIndex++)
  249. {
  250. var item = listItem.Values[itemIndex];
  251. var row = sheet.Cells.GetRow(startRow + itemIndex);
  252. for (int i = 0; i < item.Length; i++)
  253. {
  254. var col = listItem.StartColumn + i;
  255. if (col > listItem.EndColumn)
  256. {
  257. break;
  258. }
  259. var cell = row.GetCellOrNull(col);
  260. if (cell.GetHeightOfValue() > sheet.Cells.GetRowHeight(cell.Row))
  261. {
  262. var style = cell.GetStyle();
  263. style.IsTextWrapped = true;
  264. sheet.AutoFitRow(cell.Row);
  265. cell.SetStyle(style);
  266. }
  267. }
  268. }
  269. }
  270. if (x.PictureItemList != null)
  271. {
  272. foreach (var pictureItem in x.PictureItemList)
  273. {
  274. int startRow = pictureItem.StartRow + addRows;
  275. sheet.Pictures.Add(pictureItem.StartRow + addRows, pictureItem.StartColumn, pictureItem.EndRow + addRows, pictureItem.EndColumn, pictureItem.Picture);
  276. }
  277. }
  278. if (x is AsposePageItem)
  279. {
  280. var headerList = ((AsposePageItem)x).HeaderFormaterList;
  281. var footerList = ((AsposePageItem)x).FooterFormaterList;
  282. headerList.ForEach(header =>
  283. {
  284. if (header != null)
  285. {
  286. sheet.PageSetup.SetHeader((int)header.Section, header.Formater.Invoke(sheet.PageSetup.GetHeader((int)header.Section)));
  287. }
  288. });
  289. footerList.ForEach(footer =>
  290. {
  291. if (footer != null)
  292. {
  293. sheet.PageSetup.SetFooter((int)footer.Section, footer.Formater.Invoke(sheet.PageSetup.GetFooter((int)footer.Section)));
  294. }
  295. });
  296. }
  297. //sheet.AutoFitRows();
  298. sheetIndex++;
  299. });
  300. MemoryStream file = new MemoryStream();
  301. wk.Save(file, SaveFormat.Xlsx);
  302. templateFileStream.Close();
  303. file.Flush();
  304. return file;
  305. }
  306. private Workbook Export(DataTable dtSource, string[] CloumnList, string filePath)
  307. {
  308. Workbook workbook = new Workbook();
  309. Worksheet sheet1 = workbook.Worksheets[0];
  310. //默认宽度-高度
  311. //sheet1.DefaultColumnWidth = 1 * 15;
  312. Style style = workbook.CreateStyle();
  313. style.SetBorder(BorderType.BottomBorder, CellBorderType.Thin, Color.FromArgb(0, 0, 0));
  314. style.SetBorder(BorderType.LeftBorder, CellBorderType.Thin, Color.FromArgb(0, 0, 0));
  315. style.SetBorder(BorderType.RightBorder, CellBorderType.Thin, Color.FromArgb(0, 0, 0));
  316. style.SetBorder(BorderType.TopBorder, CellBorderType.Thin, Color.FromArgb(0, 0, 0));
  317. //居中
  318. style.HorizontalAlignment = TextAlignmentType.Center;
  319. style.VerticalAlignment = TextAlignmentType.Center;
  320. //设置字体
  321. style.Font.Size = 12;
  322. style.Font.IsBold = true;
  323. var customerStyleGroupList = _cellStyleList
  324. .Select(x => new { Style = x.Key.Invoke(workbook), CellList = x.Select(w => new { w.RowIndex, w.ColumnIndex }).ToList() })
  325. .ToList();
  326. if (CloumnList.Length > 0)
  327. {
  328. for (int i = 0; i < CloumnList.Length; i++)
  329. {
  330. Cell cell = sheet1.Cells[0, i];
  331. cell.PutValue(CloumnList[i]);
  332. sheet1.Cells.SetColumnWidth(i, 15);
  333. }
  334. }
  335. if (dtSource.Rows.Count > 0)
  336. {
  337. for (int i = 0; i < dtSource.Rows.Count; i++)
  338. {
  339. sheet1.Cells.InsertRow(i + 1);
  340. var rowsub = sheet1.Cells.Rows[i + 1];
  341. for (int j = 0; j < dtSource.Columns.Count; j++)
  342. {
  343. var cell = sheet1.Cells[i + 1, j];
  344. if (dtSource.Rows[i][j].ToString() != "" && dtSource.Rows[i][j] != null)
  345. {
  346. if (NumberRegex.IsMatch(dtSource.Rows[i][j].ToString()))
  347. {
  348. cell.PutValue(dtSource.Rows[i][j].ToString(), true, false);//如果是值类型、那么以原格式输出
  349. }
  350. else
  351. {
  352. cell.PutValue(dtSource.Rows[i][j].ToString());
  353. }
  354. }
  355. else
  356. {
  357. cell.PutValue(dtSource.Rows[i][j] as string);
  358. }
  359. var customCellStyle = customerStyleGroupList.FirstOrDefault(x => x.CellList.Any(w => w.ColumnIndex == j && w.RowIndex == i));
  360. if (customCellStyle != null)
  361. {
  362. cell.SetStyle(customCellStyle.Style);
  363. }
  364. }
  365. }
  366. }
  367. for (int i = 0; i < CloumnList.Length; i++)
  368. {
  369. Cell cell = sheet1.Cells[0, i];
  370. var customCellStyle = customerStyleGroupList.FirstOrDefault(x => x.CellList.Any(w => w.ColumnIndex == i && w.RowIndex == -1));
  371. if (customCellStyle != null)
  372. {
  373. cell.SetStyle(customCellStyle.Style);
  374. }
  375. else
  376. {
  377. cell.SetStyle(style);
  378. }
  379. }
  380. return workbook;
  381. }
  382. /// <summary>
  383. /// 导出
  384. /// </summary>
  385. /// <param name="dtSource">数据源</param>
  386. /// <param name="CloumnList">中文列名列表</param>
  387. /// <param name="HeaderText">表头</param>
  388. /// <param name="SavePath">保存路径</param>
  389. public string ExportToFile(DataTable dtSource, string[] CloumnList, string filePath)
  390. {
  391. string fileName = Guid.NewGuid().ToString() + ".xls";
  392. var workbook = this.Export(dtSource, CloumnList, filePath);
  393. var fileFullPath = System.IO.Path.Combine(filePath, fileName);
  394. workbook.Save(fileFullPath);
  395. return fileName;
  396. }
  397. /// <summary>
  398. /// 导出
  399. /// </summary>
  400. /// <param name="dtSource">数据源</param>
  401. /// <param name="CloumnList">中文列名列表</param>
  402. /// <param name="HeaderText">表头</param>
  403. /// <param name="SavePath">保存路径</param>
  404. public MemoryStream ExportToStream(DataTable dtSource, string[] CloumnList, string filePath)
  405. {
  406. var workbook = this.Export(dtSource, CloumnList, filePath);
  407. var stream = workbook.SaveToStream();
  408. return stream;
  409. }
  410. /// <summary>
  411. /// 将指定路径的文件,写入table中,带列标题,返回该DataTable
  412. /// </summary>
  413. /// <param name="FilePath"></param>
  414. /// <returns></returns>
  415. public DataTable Import(string filePath)
  416. {
  417. var stream = File.Open(filePath, FileMode.Open);
  418. return Import(stream);
  419. }
  420. /// <summary>
  421. /// 将指定路径的文件,写入table中,带列标题,返回该DataTable
  422. /// </summary>
  423. /// <param name="FilePath"></param>
  424. /// <returns></returns>
  425. public DataTable Import(Stream fileStream, int firstRow = 0, int firstColumn = 0)
  426. {
  427. //Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
  428. DataTable dt = new DataTable();
  429. Workbook wk = new Workbook(fileStream);
  430. Worksheet sheet = wk.Worksheets[0];
  431. int rowCount = sheet.Cells.MaxDataRow + 1;
  432. int columnCount = sheet.Cells.Rows[firstRow].LastDataCell.Column + 1;
  433. dt = sheet.Cells.ExportDataTable(firstRow, firstColumn, rowCount, columnCount, true);
  434. sheet = null;
  435. wk = null;
  436. return dt;
  437. }
  438. }
  439. public static class AsposeExcelHelperExtensions
  440. {
  441. public static string ToExcelFile(this MemoryStream stream, string physicalPath)
  442. {
  443. var fileName = Guid.NewGuid().ToString() + ".xlsx";
  444. var excelFile = new FileStream(Path.Combine(physicalPath, fileName), FileMode.OpenOrCreate, FileAccess.ReadWrite);
  445. stream.WriteTo(excelFile);
  446. excelFile.Flush();
  447. excelFile.Close();
  448. return fileName;
  449. }
  450. }
  451. public class ExcelToPDF
  452. {
  453. public static MemoryStream Export(Stream excelStream)
  454. {
  455. //Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
  456. Workbook wb = new Workbook(excelStream, new LoadOptions(LoadFormat.Auto));
  457. var pdfStream = new MemoryStream();
  458. wb.Save(pdfStream, new PdfSaveOptions(SaveFormat.Pdf)
  459. {
  460. });
  461. return pdfStream;
  462. }
  463. /// <summary>
  464. ///
  465. /// </summary>
  466. /// <param name="excelStream"></param>
  467. /// <param name="filePath">相对路径</param>
  468. /// <returns></returns>
  469. public static string ExportToFile(MemoryStream excelStream, string filePath)
  470. {
  471. //Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
  472. var pdfFileName = Guid.NewGuid().ToString() + ".pdf";
  473. var fullPath = filePath + (!filePath.EndsWith("/") ? "/" : "") + pdfFileName;
  474. var physicalFullPath = System.Web.HttpContext.Current.Server.MapPath(fullPath);
  475. Workbook wb = new Workbook(excelStream, new LoadOptions(LoadFormat.Auto));
  476. wb.Save(physicalFullPath, SaveFormat.Pdf);
  477. return fullPath;
  478. }
  479. }
  480. }