AsposeExcelHelper.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643
  1. using Aspose.Cells;
  2. using Aspose.Cells.Drawing;
  3. using NPOI.SS.Formula.Functions;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Data;
  7. using System.Drawing;
  8. using System.IO;
  9. using System.Linq;
  10. using System.Text;
  11. using System.Text.RegularExpressions;
  12. namespace Bowin.Common.Office
  13. {
  14. public class AsposeExcelHelper
  15. {
  16. private List<IGrouping<Func<Workbook, Style>, AsposeExcelCellStyle>> _cellStyleListField;
  17. private List<IGrouping<Func<Workbook, Style>, AsposeExcelCellStyle>> _cellStyleList
  18. {
  19. get
  20. {
  21. if (_cellStyleListField == null)
  22. {
  23. _cellStyleListField = new List<IGrouping<Func<Workbook, Style>, AsposeExcelCellStyle>>();
  24. }
  25. return _cellStyleListField;
  26. }
  27. set
  28. {
  29. _cellStyleListField = value;
  30. }
  31. }
  32. private static Regex NumberRegex
  33. {
  34. get
  35. {
  36. return new Regex("^-?[0-9]+(\\.[0-9]*[1-9]){0,1}$");
  37. }
  38. }
  39. private static Regex DecimalRegex
  40. {
  41. get
  42. {
  43. return new Regex("^-?[0-9]+(\\.[0-9]*){0,1}$");
  44. }
  45. }
  46. public void PresetCellStyle(List<AsposeExcelCellStyle> cellStyleList)
  47. {
  48. var styleGroup = cellStyleList.GroupBy(x => x.StyleFunc).ToList();
  49. this._cellStyleList = styleGroup;
  50. }
  51. public MemoryStream ExportNoTemplate(List<CellItem> cellItems, List<ListItem> listItems)
  52. {
  53. return ExportNoTemplate(cellItems, listItems, new List<PictureItem>());
  54. }
  55. public MemoryStream ExportNoTemplate(List<CellItem> cellItems, List<ListItem> listItems, List<PictureItem> pictureItems)
  56. {
  57. return ExportNoTemplate(cellItems, listItems, pictureItems, new List<CellArea>());
  58. }
  59. public MemoryStream ExportNoTemplate(List<CellItem> cellItems, List<ListItem> listItems, List<PictureItem> pictureItems, List<CellArea> mergeList)
  60. {
  61. return ExportNoTemplate(new List<PageItem>
  62. {
  63. new AsposePageItem
  64. {
  65. CellItemList = cellItems,
  66. ListItemList = listItems,
  67. PictureItemList = pictureItems,
  68. MergeList = mergeList
  69. }
  70. });
  71. }
  72. public MemoryStream ExportNoTemplate(List<PageItem> pageItems)
  73. {
  74. Workbook wk;
  75. wk = new Workbook();
  76. var result = ExportByWorkbook(wk, pageItems);
  77. return result;
  78. }
  79. public MemoryStream ExportToTemplate(Stream templateFileStream, List<CellItem> cellItems, List<ListItem> listItems)
  80. {
  81. return ExportToTemplate(templateFileStream, cellItems, listItems, new List<PictureItem>());
  82. }
  83. public MemoryStream ExportToTemplate(Stream templateFileStream, List<CellItem> cellItems, List<ListItem> listItems, List<PictureItem> pictureItems)
  84. {
  85. return ExportToTemplate(templateFileStream, cellItems, listItems, pictureItems, new List<CellArea>());
  86. }
  87. public MemoryStream ExportToTemplate(Stream templateFileStream, List<CellItem> cellItems, List<ListItem> listItems, List<PictureItem> pictureItems, List<CellArea> mergeList)
  88. {
  89. return ExportToTemplate(templateFileStream, new List<PageItem>
  90. {
  91. new AsposePageItem
  92. {
  93. CellItemList = cellItems,
  94. ListItemList = listItems,
  95. PictureItemList = pictureItems,
  96. MergeList = mergeList
  97. }
  98. });
  99. }
  100. public MemoryStream ExportToTemplate(Stream templateFileStream, List<PageItem> pageItems, bool? isAutoFitRows = null, bool? isAutoFitColumns = null)
  101. {
  102. Workbook wk;
  103. wk = new Workbook(templateFileStream);
  104. var result = ExportByWorkbook(wk, pageItems, isAutoFitRows, isAutoFitColumns);
  105. templateFileStream.Close();
  106. return result;
  107. }
  108. private MemoryStream ExportByWorkbook(Workbook wk, List<PageItem> pageItems, bool? isAutoFitRows = null, bool? isAutoFitColumns = null)
  109. {
  110. Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
  111. var templateSheetCount = wk.Worksheets.Count;
  112. for (int i = templateSheetCount; i < pageItems.Count; i+= templateSheetCount)
  113. {
  114. for (int index = 0; index < templateSheetCount; index++)
  115. {
  116. wk.Worksheets.AddCopy(index); //.CopyTo(wk, "Sheet" + (i + 1).ToString(), true, true);
  117. }
  118. }
  119. int sheetIndex = 0;
  120. pageItems.ForEach(x =>
  121. {
  122. int addRows = 0;
  123. Dictionary<int?, int?> keyValues = new Dictionary<int?, int?>();
  124. var cellItemStyleList = x.CellItemList.Where(w => w is AsposeCellItem).Where(w => ((AsposeCellItem)w).Style != null).GroupBy(w => ((AsposeCellItem)w).Style)
  125. .SelectMany(w => w.Select(v => new AsposeCellStyle(v.Col, v.Row, w.Key.Invoke(wk)))).ToList();
  126. var listItemStyleList = x.ListItemList.Where(w => w is AsposeListItem).SelectMany(w => ((AsposeListItem)w).StyleList.Select(v => new
  127. {
  128. ListItem = w,
  129. v.RowIndex,
  130. v.ColumnIndex,
  131. v.StyleFunc
  132. })).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();
  133. Worksheet sheet = wk.Worksheets[sheetIndex];
  134. if (!string.IsNullOrEmpty(x.Name))
  135. {
  136. sheet.Name = x.Name;
  137. }
  138. foreach (var columnWith in x.ColumnWidthList)
  139. {
  140. sheet.Cells.SetColumnWidth(columnWith.Key, columnWith.Value);
  141. }
  142. if (x is AsposePageItem)
  143. {
  144. var insertColumnList = ((AsposePageItem)x).InsertColumnItemList;
  145. insertColumnList.OrderByDescending(x => x.ColumnIndex).ToList()
  146. .ForEach(x => {
  147. if (x.InsertCount > 0)
  148. {
  149. sheet.Cells.InsertColumns(x.ColumnIndex, x.InsertCount);
  150. }
  151. });
  152. }
  153. foreach (var cellItem in x.CellItemList)
  154. {
  155. var cell = sheet.Cells[cellItem.Row, cellItem.Col];
  156. if (!string.IsNullOrEmpty(cellItem.Value))
  157. {
  158. if (cell.GetStyle().Number != 49 && cellItem.Value.Length < 10 && NumberRegex.IsMatch(cellItem.Value))
  159. {
  160. cell.PutValue(Convert.ToDecimal(cellItem.Value));
  161. }
  162. else
  163. {
  164. cell.PutValue(cellItem.Value);
  165. }
  166. }
  167. //if (cellItem is AsposeCellItem)
  168. //{
  169. // var customerStyleFunc = ((AsposeCellItem)cellItem).Style;
  170. // if (customerStyleFunc != null)
  171. // {
  172. // cell.SetStyle(customerStyleFunc.Invoke(wk));
  173. // }
  174. //}
  175. //var style = cell.GetStyle();
  176. //if (cell.GetHeightOfValue() > sheet.Cells.GetRowHeight(cell.Row))
  177. //{
  178. // style.IsTextWrapped = true;
  179. // sheet.AutoFitRow(cell.Row);
  180. //}
  181. //cell.SetStyle(style);
  182. //cell.GetStyle().IsTextWrapped = true;
  183. }
  184. /*if (x is AsposePageItem)
  185. {
  186. foreach (var merge in ((AsposePageItem)x).MergeList)
  187. {
  188. sheet.Cells.Merge(merge.StartRow, merge.StartColumn, (merge.EndRow - merge.StartRow + 1), (merge.EndColumn - merge.StartColumn + 1));
  189. }
  190. }*/
  191. foreach (var styleItem in cellItemStyleList)
  192. {
  193. var cell = sheet.Cells[styleItem.RowIndex.Value, styleItem.ColIndex.Value];
  194. cell.SetStyle(styleItem.cellStyle);
  195. }
  196. foreach (var cellItem in x.CellItemList)
  197. {
  198. var cell = sheet.Cells[cellItem.Row, cellItem.Col];
  199. var style = cell.GetStyle();
  200. if (cell.GetHeightOfValue() > sheet.Cells.GetRowHeight(cell.Row))
  201. {
  202. style.IsTextWrapped = true;
  203. cell.SetStyle(style);
  204. sheet.AutoFitRow(cell.Row);
  205. }
  206. else
  207. {
  208. cell.SetStyle(style);
  209. }
  210. }
  211. foreach (var listItem in x.ListItemList)
  212. {
  213. var customerStyleList = listItemStyleList.Where(x => x.ListItem == listItem).ToList();
  214. int startRow = listItem.StartRow + addRows;
  215. int curRow = startRow;
  216. if (!(listItem is AsposeListItem) || ((AsposeListItem)listItem).IsInsertRow == true)
  217. {
  218. for (int i = 1; i < listItem.Values.Length; i++)
  219. {
  220. sheet.Cells.InsertRow(startRow + i);
  221. addRows++;
  222. }
  223. }
  224. for (int itemIndex = 0; itemIndex < listItem.Values.Length; itemIndex++)
  225. {
  226. var item = listItem.Values[itemIndex];
  227. var row = sheet.Cells.GetRow(curRow);
  228. for (int i = 0; i < item.Length; i++)
  229. {
  230. var col = listItem.StartColumn + i;
  231. if (col > listItem.EndColumn)
  232. {
  233. break;
  234. }
  235. var value = item[i];
  236. if (value != null && sheet.Cells[curRow, col].GetStyle().Number != 49 && NumberRegex.IsMatch(value))
  237. {
  238. sheet.Cells[curRow, col].PutValue(Convert.ToDecimal(value));
  239. }
  240. else
  241. {
  242. sheet.Cells[curRow, col].PutValue(value);
  243. }
  244. }
  245. curRow++;
  246. }
  247. if (listItem is AsposeListItem)
  248. {
  249. var mergeList = ((AsposeListItem)listItem).MergeList;
  250. if (mergeList != null)
  251. {
  252. mergeList = mergeList.OrderBy(x => x.StartRow).ThenBy(x => x.StartColumn).ToList();
  253. foreach (var merge in mergeList)
  254. {
  255. sheet.Cells.Merge(startRow + merge.StartRow, merge.StartColumn, (merge.EndRow - merge.StartRow + 1), (merge.EndColumn - merge.StartColumn + 1));
  256. }
  257. }
  258. if (x is AsposePageItem)
  259. {
  260. if (((AsposeListItem)listItem).AutoHeightRowAndPx != null)
  261. {
  262. foreach (var i in ((AsposeListItem)listItem).AutoHeightRowAndPx)
  263. {
  264. keyValues.Add(i.Key, i.Value);
  265. }
  266. }
  267. }
  268. }
  269. foreach (var style in customerStyleList)
  270. {
  271. var row = sheet.Cells.GetRow(startRow + style.RowIndex);
  272. var col = listItem.StartColumn + style.ColumnIndex;
  273. var cell = row.GetCellOrNull(col);
  274. if (cell == null)
  275. {
  276. sheet.Cells[startRow + style.RowIndex, col].PutValue("");
  277. cell = row.GetCellOrNull(col);
  278. }
  279. cell.SetStyle(style.CellStyle);
  280. }
  281. for (int itemIndex = 0; itemIndex < listItem.Values.Length; itemIndex++)
  282. {
  283. var item = listItem.Values[itemIndex];
  284. var row = sheet.Cells.GetRow(startRow + itemIndex);
  285. for (int i = 0; i < item.Length; i++)
  286. {
  287. var col = listItem.StartColumn + i;
  288. if (col > listItem.EndColumn)
  289. {
  290. break;
  291. }
  292. var cell = row.GetCellOrNull(col);
  293. if (cell.GetHeightOfValue() > sheet.Cells.GetRowHeight(cell.Row))
  294. {
  295. var style = cell.GetStyle();
  296. style.IsTextWrapped = true;
  297. cell.SetStyle(style);
  298. sheet.AutoFitRow(cell.Row);
  299. }
  300. }
  301. }
  302. }
  303. if (x.PictureItemList != null)
  304. {
  305. foreach (var pictureItem in x.PictureItemList)
  306. {
  307. int startRow = pictureItem.StartRow + addRows;
  308. int iIndex = sheet.Pictures.Add(pictureItem.StartRow , pictureItem.StartColumn, pictureItem.EndRow , pictureItem.EndColumn, pictureItem.Picture);
  309. /* Aspose.Cells.Drawing.Picture pic = sheet.Pictures[iIndex];
  310. pic.Placement = Aspose.Cells.Drawing.PlacementType.FreeFloating;
  311. pic.Height = 130;
  312. pic.Width = 100;*/
  313. }
  314. }
  315. if (x is AsposePageItem)
  316. {
  317. foreach (var columnSequence in ((AsposePageItem)x).ColumnSequenceList)
  318. {
  319. var area = CellArea.CreateCellArea(columnSequence.ColumnName, columnSequence.ColumnName);
  320. var validate = sheet.Validations[sheet.Validations.Add(area)];
  321. validate.Type = ValidationType.List;
  322. validate.Operator = OperatorType.None;
  323. validate.InCellDropDown = true;
  324. validate.Formula1 = string.Join(',', columnSequence.SequenceList);
  325. validate.ShowError = true;
  326. validate.AlertStyle = ValidationAlertType.Stop;
  327. validate.ErrorTitle = "错误";
  328. validate.ErrorMessage = "请选择列表中的拖轮。";
  329. }
  330. foreach (var formular in ((AsposePageItem)x).FormularList)
  331. {
  332. var cell = sheet.Cells[formular.Row, formular.Col];
  333. if (!string.IsNullOrEmpty(formular.Value))
  334. {
  335. cell.Formula = "=" + formular.Value;
  336. }
  337. }
  338. }
  339. if (x is AsposePageItem)
  340. {
  341. var headerList = ((AsposePageItem)x).HeaderFormaterList;
  342. var footerList = ((AsposePageItem)x).FooterFormaterList;
  343. headerList.ForEach(header => {
  344. if (header != null)
  345. {
  346. sheet.PageSetup.SetHeader((int)header.Section, header.Formater.Invoke(sheet.PageSetup.GetHeader((int)header.Section)));
  347. }
  348. });
  349. footerList.ForEach(footer => {
  350. if (footer != null)
  351. {
  352. sheet.PageSetup.SetFooter((int)footer.Section, footer.Formater.Invoke(sheet.PageSetup.GetFooter((int)footer.Section)));
  353. }
  354. });
  355. foreach (var merge in ((AsposePageItem)x).MergeList)
  356. {
  357. sheet.Cells.Merge(merge.StartRow, merge.StartColumn, (merge.EndRow - merge.StartRow + 1), (merge.EndColumn - merge.StartColumn + 1));
  358. }
  359. }
  360. //sheet.AutoFitRows();
  361. if (isAutoFitRows.HasValue && isAutoFitRows.Value == true)
  362. {
  363. sheet.AutoFitRows();
  364. }
  365. if (isAutoFitColumns.HasValue && isAutoFitColumns.Value == true)
  366. {
  367. sheet.AutoFitColumns();
  368. }
  369. foreach (var k in keyValues)
  370. {
  371. if (k.Key.HasValue)
  372. {
  373. int colCount = sheet.Cells.MaxColumn; //获取表页的最大行数
  374. sheet.AutoFitRow(k.Key.Value - 1, 0, colCount);
  375. if (k.Value != 0)
  376. sheet.Cells.SetRowHeightPixel(k.Key.Value - 1, sheet.Cells.GetRowHeightPixel(k.Key.Value - 1) + k.Value.Value);
  377. }
  378. }
  379. sheetIndex++;
  380. });
  381. MemoryStream file = new MemoryStream();
  382. wk.Save(file, SaveFormat.Xlsx);
  383. file.Flush();
  384. return file;
  385. }
  386. private Workbook Export(DataTable dtSource, string[] CloumnList, int[] stringColumnList = null)
  387. {
  388. Workbook workbook = new Workbook();
  389. Worksheet sheet1 = workbook.Worksheets[0];
  390. //默认宽度-高度
  391. //sheet1.DefaultColumnWidth = 1 * 15;
  392. Style style = workbook.CreateStyle();
  393. style.SetBorder(BorderType.BottomBorder, CellBorderType.Thin, Color.FromArgb(0, 0, 0));
  394. style.SetBorder(BorderType.LeftBorder, CellBorderType.Thin, Color.FromArgb(0, 0, 0));
  395. style.SetBorder(BorderType.RightBorder, CellBorderType.Thin, Color.FromArgb(0, 0, 0));
  396. style.SetBorder(BorderType.TopBorder, CellBorderType.Thin, Color.FromArgb(0, 0, 0));
  397. //居中
  398. style.HorizontalAlignment = TextAlignmentType.Center;
  399. style.VerticalAlignment = TextAlignmentType.Center;
  400. //设置字体
  401. style.Font.Size = 12;
  402. style.Font.IsBold = true;
  403. var customerStyleGroupList = _cellStyleList
  404. .Select(x => new { Style = x.Key.Invoke(workbook), CellList = x.Select(w => new { w.RowIndex, w.ColumnIndex }).ToList() })
  405. .ToList();
  406. if (CloumnList.Length > 0)
  407. {
  408. for (int i = 0; i < CloumnList.Length; i++)
  409. {
  410. Cell cell = sheet1.Cells[0, i];
  411. cell.PutValue(CloumnList[i]);
  412. sheet1.Cells.SetColumnWidth(i, 15);
  413. }
  414. }
  415. if (dtSource.Rows.Count > 0)
  416. {
  417. for (int i = 0; i < dtSource.Rows.Count; i++)
  418. {
  419. sheet1.Cells.InsertRow(i + 1);
  420. var rowsub = sheet1.Cells.Rows[i + 1];
  421. for (int j = 0; j < dtSource.Columns.Count; j++)
  422. {
  423. var cell = sheet1.Cells[i + 1, j];
  424. if (dtSource.Rows[i][j].ToString() != "" && dtSource.Rows[i][j] != null)
  425. {
  426. if (dtSource.Rows[i][j].ToString().StartsWith("="))
  427. {
  428. cell.Formula = dtSource.Rows[i][j].ToString();
  429. }
  430. else
  431. {
  432. if (DecimalRegex.IsMatch(dtSource.Rows[i][j].ToString()) && cell.GetStyle().Number != 49)
  433. {
  434. if (stringColumnList != null && stringColumnList.Contains(j))
  435. {
  436. cell.PutValue(dtSource.Rows[i][j].ToString());
  437. }
  438. else
  439. {
  440. cell.PutValue(dtSource.Rows[i][j].ToString(), true, false);//如果是值类型、那么以原格式输出
  441. }
  442. }
  443. else
  444. {
  445. cell.PutValue(dtSource.Rows[i][j].ToString());
  446. }
  447. }
  448. }
  449. else
  450. {
  451. cell.PutValue(dtSource.Rows[i][j] as string);
  452. }
  453. var customCellStyle = customerStyleGroupList.FirstOrDefault(x => x.CellList.Any(w => w.ColumnIndex == j && w.RowIndex == i));
  454. if (customCellStyle != null)
  455. {
  456. cell.SetStyle(customCellStyle.Style);
  457. }
  458. }
  459. }
  460. }
  461. for (int i = 0; i < CloumnList.Length; i++)
  462. {
  463. Cell cell = sheet1.Cells[0, i];
  464. var customCellStyle = customerStyleGroupList.FirstOrDefault(x => x.CellList.Any(w => w.ColumnIndex == i && w.RowIndex == -1));
  465. if (customCellStyle != null)
  466. {
  467. cell.SetStyle(customCellStyle.Style);
  468. }
  469. else
  470. {
  471. cell.SetStyle(style);
  472. }
  473. }
  474. return workbook;
  475. }
  476. /// <summary>
  477. /// 导出
  478. /// </summary>
  479. /// <param name="dtSource">数据源</param>
  480. /// <param name="CloumnList">中文列名列表</param>
  481. /// <param name="HeaderText">表头</param>
  482. /// <param name="SavePath">保存路径</param>
  483. public string ExportToFile(DataTable dtSource, string[] CloumnList, string filePath, int[] stringColumnList = null)
  484. {
  485. string fileName = Guid.NewGuid().ToString() + ".xls";
  486. var workbook = this.Export(dtSource, CloumnList, stringColumnList);
  487. var fileFullPath = System.IO.Path.Combine(filePath, fileName);
  488. workbook.Save(fileFullPath);
  489. return fileName;
  490. }
  491. /// <summary>
  492. /// 导出
  493. /// </summary>
  494. /// <param name="dtSource">数据源</param>
  495. /// <param name="CloumnList">中文列名列表</param>
  496. /// <param name="HeaderText">表头</param>
  497. /// <param name="SavePath">保存路径</param>
  498. public MemoryStream ExportToStream(DataTable dtSource, string[] CloumnList, int[] stringColumnList = null)
  499. {
  500. var workbook = this.Export(dtSource, CloumnList, stringColumnList);
  501. var stream = workbook.SaveToStream();
  502. return stream;
  503. }
  504. /// <summary>
  505. /// 将指定路径的文件,写入table中,带列标题,返回该DataTable
  506. /// </summary>
  507. /// <param name="FilePath"></param>
  508. /// <returns></returns>
  509. public DataTable Import(string filePath)
  510. {
  511. var stream = File.Open(filePath, FileMode.Open);
  512. return Import(stream);
  513. }
  514. /// <summary>
  515. /// 将指定路径的文件,写入table中,带列标题,返回该DataTable
  516. /// </summary>
  517. /// <param name="FilePath"></param>
  518. /// <returns></returns>
  519. public DataTable Import(Stream fileStream, int firstRow = 0, int firstColumn = 0)
  520. {
  521. Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
  522. DataTable dt = new DataTable();
  523. Workbook wk = new Workbook(fileStream);
  524. Worksheet sheet = wk.Worksheets[0];
  525. int rowCount = sheet.Cells.MaxDataRow + 1;
  526. int columnCount = sheet.Cells.Rows[firstRow].LastDataCell.Column + 1;
  527. dt = sheet.Cells.ExportDataTable(firstRow, firstColumn, rowCount, columnCount, true);
  528. sheet = null;
  529. wk = null;
  530. return dt;
  531. }
  532. public DataTable ImportAsString(Stream fileStream, int firstRow = 0, int firstColumn = 0)
  533. {
  534. Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
  535. DataTable dt = new DataTable();
  536. Workbook wk = new Workbook(fileStream);
  537. Worksheet sheet = wk.Worksheets[0];
  538. int rowCount = sheet.Cells.MaxDataRow + 1;
  539. int columnCount = sheet.Cells.Rows[firstRow].LastDataCell.Column + 1;
  540. dt = sheet.Cells.ExportDataTableAsString(firstRow, firstColumn, rowCount, columnCount, true);
  541. sheet = null;
  542. wk = null;
  543. return dt;
  544. }
  545. public string RepeatColumn(Stream fileStream, int firstRow = 0)
  546. {
  547. Workbook wk = new Workbook(fileStream);
  548. Worksheet sheet = wk.Worksheets[0];
  549. List<string> columnList = new List<string>();
  550. var columns = sheet.Cells.Rows[firstRow];
  551. for (int i = 0; i <= columns.LastDataCell.Column; i++)
  552. {
  553. columnList.Add(columns.GetCellOrNull(i).Value?.ToString());
  554. }
  555. sheet = null;
  556. wk = null;
  557. return string.Join(",", columnList.GroupBy(g => g).Where(s => s.Count() > 1).Select(s => s.Key).ToList());
  558. }
  559. }
  560. public static class AsposeExcelHelperExtensions
  561. {
  562. public static string ToExcelColumnName(this int index)
  563. {
  564. if (index < 0) { throw new Exception("列号必须是从0开始的整数"); }
  565. List<string> chars = new List<string>();
  566. do
  567. {
  568. if (chars.Count > 0) index--;
  569. chars.Insert(0, ((char)(index % 26 + (int)'A')).ToString());
  570. index = (int)((index - index % 26) / 26);
  571. } while (index > 0);
  572. return String.Join(string.Empty, chars.ToArray());
  573. }
  574. public static string ToCellName(this AsposeExcelCellPosition position)
  575. {
  576. var index = position.ColumnIndex;
  577. if (position.RowIndex < 0) { throw new Exception("行号必须是从0开始的整数"); }
  578. return index.ToExcelColumnName() + (position.RowIndex + 1).ToString();
  579. }
  580. public static string ToExcelFile(this MemoryStream stream, string physicalPath)
  581. {
  582. var fileName = Guid.NewGuid().ToString() + ".xlsx";
  583. var excelFile = new FileStream(Path.Combine(physicalPath, fileName), FileMode.OpenOrCreate, FileAccess.ReadWrite);
  584. stream.WriteTo(excelFile);
  585. excelFile.Flush();
  586. excelFile.Close();
  587. return fileName;
  588. }
  589. }
  590. }