ExcelHelper.cs 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185
  1. using NPOI.HSSF.UserModel;
  2. using NPOI.SS.Formula.Eval;
  3. using NPOI.SS.UserModel;
  4. using NPOI.SS.Util;
  5. using NPOI.XSSF.UserModel;
  6. using System;
  7. using System.Collections.Generic;
  8. using System.Data;
  9. using System.IO;
  10. using System.Text;
  11. namespace AIPlatform.Protocol.Utilities
  12. {
  13. /// <summary>
  14. /// 单元格
  15. /// </summary>
  16. public class MergedRegion
  17. {
  18. /// <summary>
  19. /// 起始行
  20. /// </summary>
  21. public int FirstRow { get; set; }
  22. /// <summary>
  23. /// 结束行
  24. /// </summary>
  25. public int LastRow { get; set; }
  26. /// <summary>
  27. /// 起始列
  28. /// </summary>
  29. public int FirstCol { get; set; }
  30. /// <summary>
  31. /// 结束列
  32. /// </summary>
  33. public int LastCol { get; set; }
  34. }
  35. public class ExcelHelper
  36. {
  37. private IWorkbook _workbook = null;
  38. private FileStream _fs = null;
  39. private bool _disposed;
  40. public ExcelHelper()
  41. {
  42. _disposed = false;
  43. }
  44. /// <summary>
  45. /// 将DataTable数据导入到excel中
  46. /// </summary>
  47. /// <param name="data">要导入的数据</param>
  48. /// <param name="isColumnWritten">DataTable的列名是否要导入</param>
  49. /// <param name="sheetName">要导入的excel的sheet的名称</param>
  50. /// <returns>导入数据行数(包含列名那一行)</returns>
  51. public int DataTableToExcel(string _fileName, DataTable data, string sheetName, bool isColumnWritten)
  52. {
  53. _fs = new FileStream(_fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite);
  54. if (_fileName.IndexOf(".xlsx", StringComparison.Ordinal) > 0) // 2007版本
  55. _workbook = new XSSFWorkbook();
  56. else if (_fileName.IndexOf(".xls", StringComparison.Ordinal) > 0) // 2003版本
  57. _workbook = new HSSFWorkbook();
  58. try
  59. {
  60. ISheet sheet = null;
  61. if (_workbook != null)
  62. {
  63. sheet = _workbook.CreateSheet(sheetName);
  64. }
  65. else
  66. {
  67. return -1;
  68. }
  69. var count = 0;
  70. var j = 0;
  71. if (isColumnWritten == true) //写入DataTable的列名
  72. {
  73. IRow row = sheet.CreateRow(0);
  74. for (j = 0; j < data.Columns.Count; ++j)
  75. {
  76. row.CreateCell(j).SetCellValue(data.Columns[j].ColumnName);
  77. }
  78. count = 1;
  79. }
  80. else
  81. {
  82. count = 0;
  83. }
  84. var i = 0;
  85. for (i = 0; i < data.Rows.Count; ++i)
  86. {
  87. IRow row = sheet.CreateRow(count);
  88. for (j = 0; j < data.Columns.Count; ++j)
  89. {
  90. row.CreateCell(j).SetCellValue(data.Rows[i][j].ToString());
  91. }
  92. ++count;
  93. }
  94. _workbook.Write(_fs); //写入到excel
  95. return count;
  96. }
  97. catch (Exception ex)
  98. {
  99. Logger.WriteLineError("DataTable to excel failed: " + ex.Message);
  100. return -1;
  101. }
  102. }
  103. /// <summary>
  104. /// 将excel中的数据导入到DataTable中
  105. /// </summary>
  106. /// <param name="sheetName">excel工作薄sheet的名称</param>
  107. /// <param name="isFirstRowColumn">第一行是否是DataTable的列名</param>
  108. /// <returns>返回的DataTable</returns>
  109. public DataTable ExcelToDataTable(string _fileName, string sheetName = "Sheet1", bool isFirstRowColumn = true)
  110. {
  111. DataTable data = new DataTable();
  112. try
  113. {
  114. _fs = new FileStream(_fileName, FileMode.Open, FileAccess.Read);
  115. if (_fileName.IndexOf(".xlsx", StringComparison.Ordinal) > 0) // 2007版本
  116. _workbook = new XSSFWorkbook(_fs);
  117. else if (_fileName.IndexOf(".xls", StringComparison.Ordinal) > 0) // 2003版本
  118. _workbook = new HSSFWorkbook(_fs);
  119. ISheet sheet = null;
  120. if (sheetName != null)
  121. {
  122. sheet = _workbook.GetSheet(sheetName);
  123. if (sheet == null) //如果没有找到指定的sheetName对应的sheet,则尝试获取第一个sheet
  124. {
  125. sheet = _workbook.GetSheetAt(0);
  126. }
  127. }
  128. else
  129. {
  130. sheet = _workbook.GetSheetAt(0);
  131. }
  132. if (sheet != null)
  133. {
  134. IRow firstRow = sheet.GetRow(0);
  135. int cellCount = firstRow.LastCellNum; //一行最后一个cell的编号 即总的列数
  136. var startRow = 0;
  137. if (isFirstRowColumn)
  138. {
  139. for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
  140. {
  141. ICell cell = firstRow.GetCell(i);
  142. if (cell != null)
  143. {
  144. string cellValue = cell.StringCellValue.Trim();
  145. if (cellValue != null)
  146. {
  147. DataColumn column = new DataColumn(cellValue);
  148. data.Columns.Add(column);
  149. }
  150. }
  151. }
  152. startRow = sheet.FirstRowNum + 1;
  153. }
  154. else
  155. {
  156. startRow = sheet.FirstRowNum;
  157. }
  158. //最后一列的标号
  159. int rowCount = sheet.LastRowNum;
  160. for (int i = startRow; i <= rowCount; ++i)
  161. {
  162. IRow row = sheet.GetRow(i);
  163. if (row == null || row.FirstCellNum < 0) continue; //没有数据的行默认是null       
  164. DataRow dataRow = data.NewRow();
  165. for (int j = row.FirstCellNum; j < cellCount; ++j)
  166. {
  167. if (row.GetCell(j) != null) //同理,没有数据的单元格都默认是null
  168. dataRow[j] = row.GetCell(j).ToString().Trim();
  169. }
  170. data.Rows.Add(dataRow);
  171. }
  172. }
  173. return data;
  174. }
  175. catch (Exception ex)
  176. {
  177. Logger.WriteLineError("Excel to dataTable failed: " + ex);
  178. return null;
  179. }
  180. }
  181. public DataTable ExcelToDataTable(string _fileName, out string productName, string sheetName = "Sheet1", bool isFirstRowColumn = true)
  182. {
  183. productName = string.Empty;
  184. DataTable data = new DataTable();
  185. try
  186. {
  187. _fs = new FileStream(_fileName, FileMode.Open, FileAccess.Read);
  188. if (_fileName.IndexOf(".xlsx", StringComparison.Ordinal) > 0) // 2007版本
  189. _workbook = new XSSFWorkbook(_fs);
  190. else if (_fileName.IndexOf(".xls", StringComparison.Ordinal) > 0) // 2003版本
  191. _workbook = new HSSFWorkbook(_fs);
  192. ISheet sheet = null;
  193. if (sheetName != null)
  194. {
  195. sheet = _workbook.GetSheet(sheetName);
  196. if (sheet == null) //如果没有找到指定的sheetName对应的sheet,则尝试获取第一个sheet
  197. {
  198. sheet = _workbook.GetSheetAt(0);
  199. }
  200. }
  201. else
  202. {
  203. sheet = _workbook.GetSheetAt(0);
  204. }
  205. if (sheet != null)
  206. {
  207. IRow firstRow = sheet.GetRow(0);
  208. int cellCount = firstRow.LastCellNum; //一行最后一个cell的编号 即总的列数
  209. productName = firstRow.GetCell(4).StringCellValue;
  210. var startRow = 0;
  211. if (isFirstRowColumn)
  212. {
  213. for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
  214. {
  215. ICell cell = firstRow.GetCell(i);
  216. if (cell != null)
  217. {
  218. string cellValue = cell.StringCellValue.Trim();
  219. if (cellValue != null)
  220. {
  221. DataColumn column = new DataColumn(cellValue);
  222. data.Columns.Add(column);
  223. }
  224. }
  225. }
  226. startRow = sheet.FirstRowNum + 1;
  227. }
  228. else
  229. {
  230. startRow = sheet.FirstRowNum;
  231. }
  232. //最后一列的标号
  233. int rowCount = sheet.LastRowNum;
  234. for (int i = startRow; i <= rowCount; ++i)
  235. {
  236. IRow row = sheet.GetRow(i);
  237. if (row == null || row.FirstCellNum < 0) continue; //没有数据的行默认是null       
  238. DataRow dataRow = data.NewRow();
  239. for (int j = row.FirstCellNum; j < cellCount; ++j)
  240. {
  241. if (row.GetCell(j) != null) //同理,没有数据的单元格都默认是null
  242. dataRow[j] = row.GetCell(j).ToString().Trim();
  243. }
  244. data.Rows.Add(dataRow);
  245. }
  246. }
  247. return data;
  248. }
  249. catch (Exception ex)
  250. {
  251. Logger.WriteLineError("Excel to dataTable failed: " + ex);
  252. return null;
  253. }
  254. }
  255. /// <summary>
  256. /// 将Excel中的数据导入到DataTable中
  257. /// </summary>
  258. /// <param name="_fileName">文件名</param>
  259. /// <param name="colNames">列名</param>
  260. /// <param name="categorties">分类</param>
  261. /// <param name="sheetName">工作表名</param>
  262. /// <param name="isFirstRowColumn">第一行是否是DataTable的列名</param>
  263. /// <returns></returns>
  264. public DataTable ExcelToDataTable(string _fileName, out List<string> colNames, out List<string> categorties, string sheetName = "Sheet1", bool isFirstRowColumn = true)
  265. {
  266. colNames = new List<string>();
  267. categorties = new List<string>();
  268. DataTable data = new DataTable();
  269. try
  270. {
  271. _fs = new FileStream(_fileName, FileMode.Open, FileAccess.Read);
  272. if (_fileName.IndexOf(".xlsx", StringComparison.Ordinal) > 0) // 2007版本
  273. _workbook = new XSSFWorkbook(_fs);
  274. else if (_fileName.IndexOf(".xls", StringComparison.Ordinal) > 0) // 2003版本
  275. _workbook = new HSSFWorkbook(_fs);
  276. ISheet sheet = null;
  277. if (sheetName != null)
  278. {
  279. sheet = _workbook.GetSheet(sheetName);
  280. if (sheet == null) //如果没有找到指定的sheetName对应的sheet,则尝试获取第一个sheet
  281. {
  282. sheet = _workbook.GetSheetAt(0);
  283. }
  284. }
  285. else
  286. {
  287. sheet = _workbook.GetSheetAt(0);
  288. }
  289. if (sheet != null)
  290. {
  291. IRow firstRow = sheet.GetRow(0);
  292. int cellCount = firstRow.LastCellNum; //一行最后一个cell的编号 即总的列数
  293. var startRow = 0;
  294. if (isFirstRowColumn)
  295. {
  296. for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
  297. {
  298. ICell cell = firstRow.GetCell(i);
  299. if (cell != null)
  300. {
  301. string cellValue = cell.StringCellValue.Trim();
  302. if (cellValue != null)
  303. {
  304. DataColumn column = new DataColumn(cellValue);
  305. data.Columns.Add(column);
  306. colNames.Add(cellValue);
  307. }
  308. }
  309. }
  310. startRow = sheet.FirstRowNum + 1;
  311. }
  312. else
  313. {
  314. startRow = sheet.FirstRowNum;
  315. }
  316. //最后一列的标号
  317. int rowCount = sheet.LastRowNum;
  318. for (int i = startRow; i <= rowCount; ++i)
  319. {
  320. IRow row = sheet.GetRow(i);
  321. if (row == null || row.FirstCellNum < 0) continue; //没有数据的行默认是null       
  322. DataRow dataRow = data.NewRow();
  323. for (int j = row.FirstCellNum; j < cellCount; ++j)
  324. {
  325. if (row.GetCell(j) != null) //同理,没有数据的单元格都默认是null
  326. {
  327. dataRow[j] = row.GetCell(j).ToString().Trim();
  328. //获取分类
  329. var font = row.GetCell(j).CellStyle.GetFont(_workbook);
  330. if (!string.IsNullOrEmpty(dataRow[j].ToString()) && font.IsItalic && font.IsBold) //字体加粗、斜体默认为分类
  331. {
  332. categorties.Add(dataRow[j].ToString());
  333. }
  334. }
  335. }
  336. data.Rows.Add(dataRow);
  337. }
  338. }
  339. return data;
  340. }
  341. catch (Exception ex)
  342. {
  343. Logger.WriteLineError("Excel to dataTable failed: " + ex);
  344. return null;
  345. }
  346. }
  347. public DataTable ExcelToDataTableByStream(Stream fileStream, string sheetName = "Sheet1", bool isFirstRowColumn = true)
  348. {
  349. DataTable data = new DataTable();
  350. try
  351. {
  352. if (fileStream == null)
  353. {
  354. return data;
  355. }
  356. _workbook = new XSSFWorkbook(fileStream);
  357. ISheet sheet = null;
  358. if (sheetName != null)
  359. {
  360. sheet = _workbook.GetSheet(sheetName);
  361. if (sheet == null) //如果没有找到指定的sheetName对应的sheet,则尝试获取第一个sheet
  362. {
  363. sheet = _workbook.GetSheetAt(0);
  364. }
  365. }
  366. else
  367. {
  368. sheet = _workbook.GetSheetAt(0);
  369. }
  370. if (sheet != null)
  371. {
  372. IRow firstRow = sheet.GetRow(0);
  373. int cellCount = firstRow.LastCellNum; //一行最后一个cell的编号 即总的列数
  374. var startRow = 0;
  375. if (isFirstRowColumn)
  376. {
  377. for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
  378. {
  379. ICell cell = firstRow.GetCell(i);
  380. if (cell != null)
  381. {
  382. string cellValue = cell.StringCellValue.Trim();
  383. if (cellValue != null)
  384. {
  385. DataColumn column = new DataColumn(cellValue);
  386. data.Columns.Add(column);
  387. }
  388. }
  389. }
  390. startRow = sheet.FirstRowNum + 1;
  391. }
  392. else
  393. {
  394. startRow = sheet.FirstRowNum;
  395. }
  396. //最后一列的标号
  397. int rowCount = sheet.LastRowNum;
  398. for (int i = startRow; i <= rowCount; ++i)
  399. {
  400. IRow row = sheet.GetRow(i);
  401. if (row == null || row.FirstCellNum < 0) continue; //没有数据的行默认是null       
  402. DataRow dataRow = data.NewRow();
  403. for (int j = row.FirstCellNum; j < cellCount; ++j)
  404. {
  405. if (row.GetCell(j) != null) //同理,没有数据的单元格都默认是null
  406. {
  407. dataRow[j] = row.GetCell(j).ToString().Trim();
  408. }
  409. }
  410. data.Rows.Add(dataRow);
  411. }
  412. }
  413. return data;
  414. }
  415. catch (Exception ex)
  416. {
  417. Logger.WriteLineError("ProductSpecExcelToDataTableByStream failed: " + ex);
  418. return null;
  419. }
  420. }
  421. /// <summary>
  422. /// 写值
  423. /// </summary>
  424. /// <param name="sheet">工作表</param>
  425. /// <param name="row">行号,从1计</param>
  426. /// <param name="column">列号,从1计</param>
  427. /// <param name="value"></param>
  428. /// <param name="isWrapText">自动换行</param>
  429. /// <param name="heightInPoints">行高</param>
  430. /// <param name="IsCenter">居中</param>
  431. public void SetValue(ISheet sheet, int row, int column, string value, bool isWrapText = false, int heightInPoints = 20, bool IsCenter = false, bool fontName = false)
  432. {
  433. row -= 1;
  434. IRow xrow = sheet.GetRow(row);
  435. if (xrow == null)
  436. {
  437. xrow = sheet.CreateRow(row);
  438. }
  439. //行高
  440. xrow.HeightInPoints = heightInPoints;
  441. column -= 1;
  442. var cell = xrow.GetCell(column);
  443. if (cell == null)
  444. {
  445. cell = xrow.CreateCell(column);
  446. }
  447. if (IsCenter)
  448. {
  449. cell.CellStyle.Alignment = HorizontalAlignment.Center;//居中
  450. }
  451. if (fontName)
  452. {
  453. }
  454. //设置单元格内容换行
  455. if (isWrapText)
  456. {
  457. cell.CellStyle.WrapText = true;
  458. }
  459. cell.SetCellValue(value ?? string.Empty);
  460. }
  461. public void SetStyleValue(ISheet sheet, int row, int column, string value, XSSFWorkbook book, bool isWrapText = false, int heightInPoints = 20, bool IsCenter = false, string strValue = null, string descriptionEnglish = null)
  462. {
  463. row -= 1;
  464. IRow xrow = sheet.GetRow(row);
  465. if (xrow == null)
  466. {
  467. xrow = sheet.CreateRow(row);
  468. }
  469. //行高
  470. xrow.HeightInPoints = heightInPoints;
  471. column -= 1;
  472. var cell = xrow.GetCell(column);
  473. if (cell == null)
  474. {
  475. cell = xrow.CreateCell(column);
  476. }
  477. if (IsCenter)
  478. {
  479. cell.CellStyle.Alignment = HorizontalAlignment.Center;//居中
  480. }
  481. IFont font2 = book.CreateFont(); ;
  482. font2.Color = IndexedColors.Black.Index;
  483. font2.FontName = "黑体";
  484. font2.FontHeightInPoints = (short)10;
  485. var rts1 = new XSSFRichTextString(strValue + descriptionEnglish + value);
  486. if (!string.IsNullOrEmpty(strValue + descriptionEnglish + value))
  487. {
  488. IFont monthFont = book.CreateFont();
  489. monthFont.FontHeightInPoints = 11;
  490. monthFont.FontName = "黑体";
  491. monthFont.Boldweight = (short)FontBoldWeight.Bold;
  492. if (!string.IsNullOrEmpty(strValue))
  493. rts1.ApplyFont(0, strValue.Length - 1, monthFont);
  494. if (!string.IsNullOrEmpty(descriptionEnglish))
  495. rts1.ApplyFont(strValue.Length, (strValue + descriptionEnglish).Length - 1, monthFont);
  496. if (!string.IsNullOrEmpty(value))
  497. rts1.ApplyFont((strValue + descriptionEnglish).Length, (strValue + value + descriptionEnglish).Length - 1, font2);
  498. }
  499. if (!string.IsNullOrEmpty(descriptionEnglish))
  500. {
  501. //设置单元格内容换行
  502. if (isWrapText)
  503. {
  504. cell.CellStyle.WrapText = true;
  505. }
  506. }
  507. cell.SetCellValue(rts1);
  508. // cell.SetCellValue(value);
  509. }
  510. /// <summary>
  511. /// 设置行高
  512. /// </summary>
  513. /// <param name="sheet"></param>
  514. /// <param name="row">行号,从1计</param>
  515. /// <param name="column">列号,从1计</param>
  516. /// <param name="width">行宽</param>
  517. public void SetHeightInPoints(ISheet sheet, int row, int column, string value = null, int width = 180, int height = 18)
  518. {
  519. row -= 1;
  520. IRow xrow = sheet.GetRow(row);
  521. if (xrow == null)
  522. {
  523. xrow = sheet.CreateRow(row);
  524. }
  525. column -= 1;
  526. var cell = xrow.GetCell(column);
  527. if (cell == null)
  528. {
  529. cell = xrow.CreateCell(column);
  530. }
  531. //设置单元格内容换行
  532. //cell.CellStyle.WrapText = true;
  533. #region 设置行高
  534. value = value ?? GetCellValue(cell).ToString();
  535. var heightInPoints = 0;
  536. var strVal = value.Split("\r\n".ToCharArray());
  537. foreach (var val in strVal)
  538. {
  539. var strVal2 = val.Split(new char[] { '\r', '\n' });
  540. foreach (var val2 in strVal2)
  541. {
  542. var length = Encoding.UTF8.GetBytes(val2).Length;
  543. heightInPoints += height * (length / width + 1);
  544. }
  545. }
  546. xrow.HeightInPoints = heightInPoints;
  547. #endregion
  548. if (!string.IsNullOrEmpty(value))
  549. {
  550. cell.SetCellValue(value);
  551. }
  552. }
  553. public void SetValue(ISheet sheet, int row, int column, double value, int heightInPoints = 20)
  554. {
  555. row -= 1;
  556. IRow xrow = sheet.GetRow(row);
  557. if (xrow == null)
  558. {
  559. xrow = sheet.CreateRow(row);
  560. }
  561. //行高
  562. xrow.HeightInPoints = heightInPoints;
  563. column -= 1;
  564. var cell = xrow.GetCell(column);
  565. if (cell == null)
  566. {
  567. cell = xrow.CreateCell(column);
  568. }
  569. cell.SetCellValue(value);
  570. }
  571. public void SetValueAndFormuar(ISheet sheet, int row, int column, string value, string formular = null)
  572. {
  573. row -= 1;
  574. IRow xrow = sheet.GetRow(row);
  575. if (xrow == null)
  576. {
  577. xrow = sheet.CreateRow(row);
  578. }
  579. column -= 1;
  580. var cell = xrow.GetCell(column);
  581. if (cell != null)
  582. {
  583. cell.SetCellValue(value);
  584. if (!string.IsNullOrEmpty(formular))
  585. {
  586. cell.SetCellType(CellType.Formula);
  587. cell.SetCellFormula(formular);
  588. }
  589. }
  590. else
  591. cell = xrow.CreateCell(column);
  592. }
  593. public void SetValueAndCellStyle(XSSFWorkbook book, ISheet sheet, int row, int column, string value, bool isBold = false, bool IsItalic = false, bool isFillBackgroundColor = false,
  594. bool isBorder = false, bool isWrapText = false, int heightInPoints = 20)
  595. {
  596. var cell = SetValueAndStyle(book, sheet, row, column, isBold, IsItalic, isFillBackgroundColor, isBorder, isWrapText, heightInPoints);
  597. //设置单元格内容
  598. cell.SetCellValue(value);
  599. }
  600. public void SetValueAndCellStyle(XSSFWorkbook book, ISheet sheet, int row, int column, double value, bool isBold = false, bool IsItalic = false, bool isFillBackgroundColor = false,
  601. bool isBorder = false, bool isWrapText = false, int heightInPoints = 20)
  602. {
  603. var cell = SetValueAndStyle(book, sheet, row, column, isBold, IsItalic, isFillBackgroundColor, isBorder, isWrapText, heightInPoints);
  604. //设置单元格内容
  605. cell.SetCellValue(value);
  606. }
  607. private ICell SetValueAndStyle(XSSFWorkbook book, ISheet sheet, int row, int column, bool isBold = false, bool IsItalic = false, bool isFillBackgroundColor = false,
  608. bool isBorder = false, bool isWrapText = false, int heightInPoints = 20)
  609. {
  610. //在工作表中:建立行,参数为行号,从1计
  611. row -= 1;
  612. IRow xrow = sheet.GetRow(row);
  613. if (xrow == null)
  614. {
  615. xrow = sheet.CreateRow(row);
  616. }
  617. //行高
  618. xrow.HeightInPoints = heightInPoints;
  619. //在行中:建立单元格,参数为列号,从1计
  620. column -= 1;
  621. var cell = xrow.GetCell(column);
  622. if (cell == null)
  623. {
  624. cell = xrow.CreateCell(column);
  625. var style = book.CreateCellStyle();
  626. //设置单元格的样式:
  627. cell.CellStyle.Alignment = HorizontalAlignment.Left;//左对齐
  628. cell.CellStyle.VerticalAlignment = VerticalAlignment.Center;//垂直居中
  629. var font = book.CreateFont();
  630. //字体
  631. font.FontName = "Calibri";
  632. //字体大小
  633. font.FontHeightInPoints = 12;
  634. //设置字体加粗样式
  635. font.IsBold = isBold;
  636. //斜体
  637. font.IsItalic = IsItalic;
  638. //使用SetFont方法将字体样式添加到单元格样式中
  639. style.SetFont(font);
  640. cell.CellStyle = style;
  641. }
  642. //背景色
  643. if (isFillBackgroundColor)
  644. {
  645. cell.CellStyle.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.Yellow.Index;// 是设置前景色不是背景色
  646. cell.CellStyle.FillPattern = FillPattern.SolidForeground;
  647. }
  648. //加边框
  649. if (isBorder)
  650. {
  651. var style = book.CreateCellStyle();
  652. style.CloneStyleFrom(cell.CellStyle);
  653. style.BorderTop = BorderStyle.Thin;
  654. style.BorderRight = BorderStyle.Thin;
  655. style.BorderLeft = BorderStyle.Thin;
  656. style.BorderBottom = BorderStyle.Thin;
  657. cell.CellStyle = style;
  658. }
  659. //设置单元格内容换行
  660. cell.CellStyle.WrapText = isWrapText;
  661. return cell;
  662. }
  663. public void SetValueAndBackgroundColor(XSSFWorkbook book, ISheet sheet, int row, int column, string value, bool isFillBackgroundColor = true,
  664. int heightInPoints = 20, short color = NPOI.HSSF.Util.HSSFColor.Yellow.Index)
  665. {
  666. //在工作表中:建立行,参数为行号,从1计
  667. row -= 1;
  668. IRow xrow = sheet.GetRow(row);
  669. if (xrow == null)
  670. {
  671. xrow = sheet.CreateRow(row);
  672. }
  673. //行高
  674. xrow.HeightInPoints = heightInPoints;
  675. //在行中:建立单元格,参数为列号,从1计
  676. column -= 1;
  677. var cell = xrow.GetCell(column);
  678. if (cell == null)
  679. {
  680. cell = xrow.CreateCell(column);
  681. }
  682. //设置单元格的样式:背景色
  683. if (isFillBackgroundColor)
  684. {
  685. var style = book.CreateCellStyle();
  686. style.CloneStyleFrom(cell.CellStyle);
  687. style.FillForegroundColor = color;
  688. style.FillPattern = FillPattern.SolidForeground;
  689. cell.CellStyle = style;
  690. }
  691. //设置单元格内容换行
  692. cell.CellStyle.WrapText = true;
  693. //设置单元格内容
  694. cell.SetCellValue(value ?? string.Empty);
  695. }
  696. public void SetValueAndBackgroundColor(XSSFWorkbook book, ISheet sheet, int row, int column, double value, bool isFillBackgroundColor = true,
  697. int heightInPoints = 20, short color = NPOI.HSSF.Util.HSSFColor.Yellow.Index)
  698. {
  699. //在工作表中:建立行,参数为行号,从1计
  700. row -= 1;
  701. IRow xrow = sheet.GetRow(row);
  702. if (xrow == null)
  703. {
  704. xrow = sheet.CreateRow(row);
  705. }
  706. //行高
  707. xrow.HeightInPoints = heightInPoints;
  708. //在行中:建立单元格,参数为列号,从1计
  709. column -= 1;
  710. var cell = xrow.GetCell(column);
  711. if (cell == null)
  712. {
  713. cell = xrow.CreateCell(column);
  714. }
  715. //设置单元格的样式:背景色
  716. if (isFillBackgroundColor)
  717. {
  718. var style = book.CreateCellStyle();
  719. style.CloneStyleFrom(cell.CellStyle);
  720. style.FillForegroundColor = color;
  721. style.FillPattern = FillPattern.SolidForeground;
  722. cell.CellStyle = style;
  723. }
  724. //设置单元格内容换行
  725. cell.CellStyle.WrapText = true;
  726. //设置单元格内容
  727. cell.SetCellValue(value);
  728. }
  729. public void SetValue(XSSFWorkbook book, ISheet sheet, int row, int column, double value, bool isFillBackgroundColor, bool isMergedRegion, int heightInPoints = 20)
  730. {
  731. //在工作表中:建立行,参数为行号,从1计
  732. row -= 1;
  733. IRow xrow = sheet.GetRow(row);
  734. if (xrow == null)
  735. {
  736. xrow = sheet.CreateRow(row);
  737. }
  738. //行高
  739. xrow.HeightInPoints = heightInPoints;
  740. //在行中:建立单元格,参数为列号,从1计
  741. column -= 1;
  742. var cell = xrow.GetCell(column);
  743. if (cell == null)
  744. {
  745. cell = xrow.CreateCell(column);
  746. }
  747. //设置单元格的样式:背景色
  748. if (isFillBackgroundColor)
  749. {
  750. var style = book.CreateCellStyle();
  751. style.CloneStyleFrom(cell.CellStyle);
  752. style.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.Yellow.Index;
  753. style.FillPattern = FillPattern.SolidForeground;
  754. cell.CellStyle = style;
  755. }
  756. //设置单元格内容
  757. cell.SetCellValue(value);
  758. //合并单元格
  759. if (isMergedRegion)
  760. {
  761. sheet.AddMergedRegion(new CellRangeAddress(row - 1, row, column, column));
  762. }
  763. }
  764. /// <summary>
  765. /// 合并单元格
  766. /// </summary>
  767. /// <param name="sheet"></param>
  768. /// <param name="row"></param>
  769. /// <param name="column"></param>
  770. /// <param name="value"></param>
  771. /// <param name="heightInPoints"></param>
  772. public void SetValueIsMergedRegion(ISheet sheet, int row, int column, string value, int heightInPoints, bool isMergedRegion = false)
  773. {
  774. //在工作表中:建立行,参数为行号,从1计
  775. row -= 1;
  776. IRow xrow = sheet.GetRow(row);
  777. if (xrow == null)
  778. {
  779. xrow = sheet.CreateRow(row);
  780. }
  781. //行高
  782. xrow.HeightInPoints = heightInPoints;
  783. //在行中:建立单元格,参数为列号,从1计
  784. column -= 1;
  785. var cell = xrow.GetCell(column);
  786. if (cell == null)
  787. {
  788. cell = xrow.CreateCell(column);
  789. }
  790. //设置单元格内容
  791. cell.SetCellValue(value);
  792. //合并单元格
  793. if (isMergedRegion)
  794. {
  795. sheet.AddMergedRegion(new CellRangeAddress(row - 1, row, column, column));
  796. }
  797. }
  798. public void SetValueIsMergedRegion(ISheet sheet, int row, int column, double value, int heightInPoints, bool isMergedRegion = false)
  799. {
  800. //在工作表中:建立行,参数为行号,从1计
  801. row -= 1;
  802. IRow xrow = sheet.GetRow(row);
  803. if (xrow == null)
  804. {
  805. xrow = sheet.CreateRow(row);
  806. }
  807. //行高
  808. xrow.HeightInPoints = heightInPoints;
  809. //在行中:建立单元格,参数为列号,从1计
  810. column -= 1;
  811. var cell = xrow.GetCell(column);
  812. if (cell == null)
  813. {
  814. cell = xrow.CreateCell(column);
  815. }
  816. //设置单元格内容
  817. cell.SetCellValue(value);
  818. //合并单元格
  819. if (isMergedRegion)
  820. {
  821. sheet.AddMergedRegion(new CellRangeAddress(row - 1, row, column, column));
  822. }
  823. }
  824. /// <summary>
  825. /// 获得行高
  826. /// </summary>
  827. /// <param name="value">值</param>
  828. /// <param name="width">行宽</param>
  829. /// <returns></returns>
  830. public int GetHeightInPoints(string value, int width = 40, int height = 20)
  831. {
  832. value = value ?? string.Empty;
  833. var length = 0;
  834. var heightInPoints = 0;
  835. var strVal = value.Split("\r\n".ToCharArray());
  836. foreach (var val in strVal)
  837. {
  838. var strVal2 = val.Split(new char[] { '\r', '\n' });
  839. foreach (var val2 in strVal2)
  840. {
  841. length = Encoding.UTF8.GetBytes(val2).Length + 3;
  842. heightInPoints += height * (length / width + 1);
  843. }
  844. }
  845. return heightInPoints;
  846. }
  847. /// <summary>
  848. /// 合并单元格
  849. /// </summary>
  850. /// <param name="sheet"></param>
  851. public void AddMergedRegion(ISheet sheet, MergedRegion mergedRegion)
  852. {
  853. mergedRegion.FirstRow--;
  854. mergedRegion.LastRow--;
  855. mergedRegion.FirstCol--;
  856. mergedRegion.LastCol--;
  857. sheet.AddMergedRegion(new CellRangeAddress(mergedRegion.FirstRow, mergedRegion.LastRow, mergedRegion.FirstCol, mergedRegion.LastCol));
  858. }
  859. /// <summary>
  860. /// XSSFRow Copy Command
  861. ///
  862. /// Description: Inserts a existing row into a new row, will automatically push down
  863. /// any existing rows. Copy is done cell by cell and supports, and the
  864. /// command tries to copy all properties available (style, merged cells, values, etc...)
  865. /// </summary>
  866. /// <param name="workbook"></param>
  867. /// <param name="worksheet"></param>
  868. /// <param name="sourceRowNum"></param>
  869. /// <param name="destinationRowNum"></param>
  870. public void CopyRow(XSSFWorkbook workbook, ISheet worksheet, int sourceRowNum, int destinationRowNum)
  871. {
  872. // Get the source / new row
  873. IRow newRow = worksheet.GetRow(destinationRowNum);
  874. IRow sourceRow = worksheet.GetRow(sourceRowNum);
  875. // If the row exist in destination, push down all rows by 1 else create a new row
  876. if (newRow != null)
  877. {
  878. worksheet.ShiftRows(destinationRowNum, worksheet.LastRowNum, 1);
  879. }
  880. else
  881. {
  882. newRow = worksheet.CreateRow(destinationRowNum);
  883. }
  884. // Loop through source columns to add to new row
  885. for (int i = 0; i < sourceRow.LastCellNum; i++)
  886. {
  887. // Grab a copy of the old/new cell
  888. ICell oldCell = sourceRow.GetCell(i);
  889. ICell newCell = newRow.CreateCell(i);
  890. // If the old cell is null jump to next cell
  891. if (oldCell == null)
  892. {
  893. newCell = null;
  894. continue;
  895. }
  896. // Copy style from old cell and apply to new cell
  897. var newCellStyle = workbook.CreateCellStyle();
  898. newCellStyle.CloneStyleFrom(oldCell.CellStyle); ;
  899. newCell.CellStyle = newCellStyle;
  900. // If there is a cell comment, copy
  901. if (newCell.CellComment != null) newCell.CellComment = oldCell.CellComment;
  902. // If there is a cell hyperlink, copy
  903. if (oldCell.Hyperlink != null) newCell.Hyperlink = oldCell.Hyperlink;
  904. // Set the cell data type
  905. newCell.SetCellType(oldCell.CellType);
  906. // Set the cell data value
  907. switch (oldCell.CellType)
  908. {
  909. case CellType.Blank:
  910. newCell.SetCellValue(oldCell.StringCellValue);
  911. break;
  912. case CellType.Boolean:
  913. newCell.SetCellValue(oldCell.BooleanCellValue);
  914. break;
  915. case CellType.Error:
  916. newCell.SetCellErrorValue(oldCell.ErrorCellValue);
  917. break;
  918. case CellType.Formula:
  919. //newCell.SetCellFormula(oldCell.CellFormula);
  920. var formula = $"H{destinationRowNum + 1}*I{destinationRowNum + 1}";
  921. newCell.SetCellFormula(formula);
  922. break;
  923. case CellType.Numeric:
  924. newCell.SetCellValue(oldCell.NumericCellValue);
  925. break;
  926. case CellType.String:
  927. newCell.SetCellValue(oldCell.RichStringCellValue);
  928. break;
  929. case CellType.Unknown:
  930. newCell.SetCellValue(oldCell.StringCellValue);
  931. break;
  932. }
  933. }
  934. // If there are are any merged regions in the source row, copy to new row
  935. for (int i = 0; i < worksheet.NumMergedRegions; i++)
  936. {
  937. CellRangeAddress cellRangeAddress = worksheet.GetMergedRegion(i);
  938. if (cellRangeAddress != null && cellRangeAddress.FirstRow == sourceRow.RowNum)
  939. {
  940. CellRangeAddress newCellRangeAddress = new CellRangeAddress(newRow.RowNum,
  941. (newRow.RowNum +
  942. (cellRangeAddress.FirstRow -
  943. cellRangeAddress.LastRow)),
  944. cellRangeAddress.FirstColumn,
  945. cellRangeAddress.LastColumn);
  946. worksheet.AddMergedRegion(newCellRangeAddress);
  947. }
  948. }
  949. }
  950. public DataTable GenerateData()
  951. {
  952. DataTable data = new DataTable();
  953. for (int i = 0; i < 5; ++i)
  954. {
  955. data.Columns.Add("Columns_" + i.ToString(), typeof(string));
  956. }
  957. for (int i = 0; i < 10; ++i)
  958. {
  959. DataRow row = data.NewRow();
  960. row["Columns_0"] = "item0_" + i.ToString();
  961. row["Columns_1"] = "item1_" + i.ToString();
  962. row["Columns_2"] = "item2_" + i.ToString();
  963. row["Columns_3"] = "item3_" + i.ToString();
  964. row["Columns_4"] = "item4_" + i.ToString();
  965. data.Rows.Add(row);
  966. }
  967. return data;
  968. }
  969. public void PrintData(DataTable data)
  970. {
  971. if (data == null) return;
  972. for (int i = 0; i < data.Rows.Count; ++i)
  973. {
  974. for (int j = 0; j < data.Columns.Count; ++j)
  975. Console.Write("{0} ", data.Rows[i][j]);
  976. Console.Write("\n");
  977. }
  978. }
  979. public new void Dispose()
  980. {
  981. Dispose(true);
  982. GC.SuppressFinalize(this);
  983. }
  984. protected virtual new void Dispose(bool disposing)
  985. {
  986. if (!this._disposed)
  987. {
  988. if (disposing)
  989. {
  990. _fs?.Close();
  991. }
  992. _fs = null;
  993. _disposed = true;
  994. }
  995. }
  996. /// <summary>
  997. /// 加范围边框
  998. /// </summary>
  999. /// <param name="firstRow">起始行</param>
  1000. /// <param name="lastRow">结束行</param>
  1001. /// <param name="firstCell">起始列</param>
  1002. /// <param name="lastCell">结束列</param>
  1003. /// <returns></returns>
  1004. public void AddRengionBorder(XSSFWorkbook book, ISheet sheet, int firstRow, int lastRow, int firstCell, int lastCell)
  1005. {
  1006. for (int i = firstRow; i < lastRow; i++)
  1007. {
  1008. for (int n = firstCell; n < lastCell; n++)
  1009. {
  1010. ICell cell;
  1011. if (sheet.GetRow(i) == null)
  1012. continue;
  1013. cell = sheet.GetRow(i).GetCell(n);
  1014. if (cell == null)
  1015. {
  1016. cell = sheet.GetRow(i).CreateCell(n);
  1017. cell.SetCellValue(" ");
  1018. }
  1019. var cellstyle = book.CreateCellStyle();
  1020. //为首行加上方边框
  1021. if (i == firstRow)
  1022. {
  1023. cellstyle.BorderTop = BorderStyle.Thin;//ss.UserModel.BorderStyle.THIN;
  1024. }
  1025. //为末行加下方边框
  1026. if (i == lastRow - 1)
  1027. {
  1028. cellstyle.BorderBottom = BorderStyle.Thin;//ss.UserModel.BorderStyle.THIN;
  1029. }
  1030. //为首列加左边框
  1031. if (n == firstCell)
  1032. {
  1033. cellstyle.BorderLeft = BorderStyle.Thin; //ss.UserModel.BorderStyle.THIN;
  1034. }
  1035. //为末列加右边框
  1036. if (n == lastCell - 1)
  1037. {
  1038. cellstyle.BorderRight = BorderStyle.Thin; //ss.UserModel.BorderStyle.THIN;
  1039. }
  1040. cell.CellStyle = cellstyle;
  1041. }
  1042. }
  1043. }
  1044. /// <summary>
  1045. /// 获取单元格的值
  1046. /// </summary>
  1047. /// <param name="item"></param>
  1048. /// <returns></returns>
  1049. public static object GetCellValue(ICell item)
  1050. {
  1051. if (item == null)
  1052. {
  1053. return string.Empty;
  1054. }
  1055. switch (item.CellType)
  1056. {
  1057. case CellType.Boolean:
  1058. return item.BooleanCellValue;
  1059. case CellType.Error:
  1060. return ErrorEval.GetText(item.ErrorCellValue);
  1061. case CellType.Formula:
  1062. switch (item.CachedFormulaResultType)
  1063. {
  1064. case CellType.Boolean:
  1065. return item.BooleanCellValue;
  1066. case CellType.Error:
  1067. return ErrorEval.GetText(item.ErrorCellValue);
  1068. case CellType.Numeric:
  1069. if (DateUtil.IsCellDateFormatted(item))
  1070. {
  1071. return item.DateCellValue.ToString("yyyy-MM-dd");
  1072. }
  1073. else
  1074. {
  1075. return item.NumericCellValue;
  1076. }
  1077. case CellType.String:
  1078. string str = item.StringCellValue;
  1079. if (!string.IsNullOrEmpty(str))
  1080. {
  1081. return str.ToString();
  1082. }
  1083. else
  1084. {
  1085. return string.Empty;
  1086. }
  1087. case CellType.Unknown:
  1088. case CellType.Blank:
  1089. default:
  1090. return string.Empty;
  1091. }
  1092. case CellType.Numeric:
  1093. if (DateUtil.IsCellDateFormatted(item))
  1094. {
  1095. return item.DateCellValue.ToString("yyyy-MM-dd");
  1096. }
  1097. else
  1098. {
  1099. return item.NumericCellValue;
  1100. }
  1101. case CellType.String:
  1102. string strValue = item.StringCellValue;
  1103. return strValue.ToString().Trim();
  1104. case CellType.Unknown:
  1105. case CellType.Blank:
  1106. default:
  1107. return string.Empty;
  1108. }
  1109. }
  1110. }
  1111. }