Excel.cs 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949
  1. using System;
  2. using System.IO;
  3. using System.Windows.Forms;
  4. using System.Data;
  5. using NPOI.HSSF.UserModel;
  6. using NPOI.SS.UserModel;
  7. using NPOI.XSSF.UserModel;
  8. using NPOI.SS.Util;
  9. using NPOI.HSSF.Util;
  10. namespace BaseLibRWFile
  11. {
  12. public class Excel
  13. {
  14. ICell cell = null;
  15. /// <summary>
  16. /// 把DataGridView控件里面的数据读出,放在DataTable里面
  17. /// </summary>
  18. /// <param name="dgv">DataGridView控件</param>
  19. /// <returns></returns>
  20. public DataTable GetDgvToTable(DataGridView dgv)
  21. {
  22. DataTable dt = new DataTable();
  23. for (int i = 0; i < dgv.Columns.Count; i++)
  24. {
  25. DataColumn dc = new DataColumn(dgv.Columns[i].Name.ToString());
  26. dt.Columns.Add(dc);
  27. }
  28. for (int i = 0; i < dgv.Rows.Count - 1; i++)
  29. {
  30. DataRow dr = dt.NewRow();
  31. for (int countsub = 0; countsub < dgv.Columns.Count; countsub++)
  32. {
  33. dr[countsub] = Convert.ToString(dgv.Rows[i].Cells[countsub].Value);
  34. }
  35. dt.Rows.Add(dr);
  36. }
  37. return dt;
  38. }
  39. /// <summary>
  40. /// 把Excel的数据读出,放在DataTable里面
  41. /// </summary>
  42. /// <param name="filePath">Excel文件完整路径</param>
  43. /// <param name="sheetname">sheet名称,可不填,默认第一个sheet</param>
  44. /// <returns></returns>
  45. public DataTable ExcelToDataTable(string filePath, string sheetname = "")
  46. {
  47. if (!File.Exists(filePath))
  48. {
  49. return null;
  50. }
  51. DataTable dt = new DataTable();
  52. using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
  53. {
  54. IWorkbook wk;
  55. if (filePath.Contains(".xlsx"))
  56. {
  57. wk = new XSSFWorkbook(fs);
  58. }
  59. else
  60. {
  61. wk = new HSSFWorkbook(fs);
  62. }
  63. if (wk != null)
  64. {
  65. ISheet sheet;
  66. if (string.IsNullOrEmpty(sheetname))
  67. {
  68. sheet = wk.GetSheetAt(0);
  69. }
  70. else
  71. {
  72. sheet = wk.GetSheet(sheetname);
  73. }
  74. System.Collections.IEnumerator rows = sheet.GetRowEnumerator();
  75. IRow headerRow = null;
  76. int cellCount = 0;
  77. for (int i = 0; i <= sheet.LastRowNum; i++)
  78. {
  79. headerRow = sheet.GetRow(i);
  80. if (headerRow!=null)
  81. {
  82. if (headerRow.LastCellNum > cellCount)
  83. {
  84. cellCount = headerRow.LastCellNum;
  85. }
  86. }
  87. }
  88. //得到Excel工作表的总列数
  89. for (int j = 0; j < cellCount; j++)
  90. {
  91. ICell cell = headerRow.GetCell(j);
  92. if (cell == null)
  93. {
  94. dt.Columns.Add("");
  95. }
  96. else
  97. {
  98. dt.Columns.Add();
  99. }
  100. }
  101. for (int i = 0; i <= sheet.LastRowNum; i++)
  102. {
  103. IRow row = sheet.GetRow(i);
  104. DataRow dataRow = dt.NewRow();
  105. if (row != null)
  106. {
  107. for (int j = row.FirstCellNum; j < cellCount; j++)
  108. {
  109. ICell cell = row.GetCell(j);
  110. if (cell == null)
  111. {
  112. dataRow[j] = "";
  113. }
  114. else
  115. {
  116. switch (cell.CellType)
  117. {
  118. case CellType.Blank:
  119. dataRow[j] = "";
  120. break;
  121. case CellType.Boolean:
  122. dataRow[j] = cell.BooleanCellValue;
  123. break;
  124. case CellType.Numeric:
  125. dataRow[j] = cell.ToString();
  126. break;
  127. case CellType.String:
  128. dataRow[j] = cell.StringCellValue;
  129. break;
  130. case CellType.Error:
  131. dataRow[j] = cell.ErrorCellValue;
  132. break;
  133. case CellType.Formula:
  134. try
  135. {
  136. dataRow[j] = cell.NumericCellValue;
  137. }
  138. catch
  139. {
  140. dataRow[j] = cell.StringCellValue;
  141. }
  142. break;
  143. default:
  144. dataRow[j] = cell.CellFormula;
  145. break;
  146. }
  147. }
  148. }
  149. dt.Rows.Add(dataRow);
  150. }
  151. }
  152. }
  153. }
  154. return dt;
  155. }
  156. /// <summary>
  157. /// 把Excel的数据读出,放在DataSet里面
  158. /// </summary>
  159. /// <param name="filePath">Excel文件完整路径</param>
  160. /// <returns></returns>
  161. public DataSet ExcelToDataSet(string filePath)
  162. {
  163. DataSet ds = new DataSet();
  164. try
  165. {
  166. using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
  167. {
  168. IWorkbook wk = null;
  169. if (filePath.Contains(".xlsx"))
  170. {
  171. wk = new XSSFWorkbook(fs);
  172. }
  173. else
  174. {
  175. wk = new HSSFWorkbook(fs);
  176. }
  177. if (wk != null)
  178. {
  179. ISheet sheet = null;
  180. for (int i = 0; i < wk.NumberOfSheets; i++)
  181. {
  182. string sheetname = wk.GetSheetName(i);
  183. sheet = wk.GetSheet(sheetname);
  184. if (sheet != null)
  185. {
  186. DataTable dt = ExcelToDataTable(filePath, sheetname);
  187. if (dt != null)
  188. {
  189. dt.TableName = sheetname.Trim();
  190. ds.Tables.Add(dt);
  191. }
  192. }
  193. }
  194. }
  195. }
  196. return ds;
  197. }
  198. catch (Exception ex)
  199. {
  200. MessageBox.Show($"读取数据到DataSet出错\r\n{ex.Message}", "Error");
  201. return null;
  202. }
  203. }
  204. /// <summary>
  205. /// 向Excel文件插入一行以逗号分隔的字符串
  206. /// </summary>
  207. /// <param name="filePath">Excel文件完整路径</param>
  208. /// <param name="sheetname">工作表名称</param>
  209. /// <param name="RowNo">插入位置(第几行)</param>
  210. /// <param name="strValue">插入内容</param>
  211. /// <returns></returns>
  212. public bool InsertRow(string filePath, int RowNo, string strValue, string sheetname=null)
  213. {
  214. try
  215. {
  216. IWorkbook wk = null;
  217. using (FileStream fs = File.Open(filePath, FileMode.Open,
  218. FileAccess.Read, FileShare.ReadWrite))
  219. {
  220. if (filePath.Contains(".xlsx"))
  221. {
  222. wk = new XSSFWorkbook(fs);
  223. }
  224. else
  225. {
  226. wk = new HSSFWorkbook(fs);
  227. }
  228. fs.Close();
  229. }
  230. ISheet sheet =sheetname==null?wk.GetSheetAt(0):wk.GetSheet(sheetname);
  231. sheet.ShiftRows(RowNo, sheet.LastRowNum + 1, 1);
  232. string[] s = strValue.Split(',');
  233. IRow row1 = sheet.CreateRow(RowNo);
  234. ICell cell = null;
  235. for (int i = 0; i < s.Length; i++)
  236. {
  237. cell = row1.CreateCell(i);
  238. cell.SetCellValue(s[i]);
  239. }
  240. using (FileStream fileStream = File.Create(filePath))
  241. {
  242. wk.Write(fileStream);
  243. fileStream.Close();
  244. }
  245. return true;
  246. }
  247. catch (Exception ex)
  248. {
  249. MessageBox.Show($"Excel插入行出错\r\nExcel insert row error\r\n{ex.Message}", "Warning");
  250. return false;
  251. }
  252. }
  253. /// <summary>
  254. /// 向Excel文件写入一行以逗号分隔的字符串
  255. /// </summary>
  256. /// <param name="filePath">Excel文件完整路径</param>
  257. /// <param name="sheetname">工作表名称</param>
  258. /// <param name="RowNo">写入位置(第几行)</param>
  259. /// <param name="strValue">插入内容</param>
  260. /// <returns></returns>
  261. public bool WriteRow(string filePath, int RowNo, string strValue, string sheetname = null)
  262. {
  263. try
  264. {
  265. IWorkbook wk = null;
  266. using (FileStream fs = File.Open(filePath, FileMode.Open,
  267. FileAccess.Read, FileShare.ReadWrite))
  268. {
  269. if (filePath.Contains(".xlsx"))
  270. {
  271. wk = new XSSFWorkbook(fs);
  272. }
  273. else
  274. {
  275. wk = new HSSFWorkbook(fs);
  276. }
  277. fs.Close();
  278. }
  279. ISheet sheet = sheetname == null ? wk.GetSheetAt(0) : wk.GetSheet(sheetname);
  280. IRow row1 = sheet.GetRow(RowNo);
  281. if (row1==null)
  282. {
  283. row1 = sheet.CreateRow(RowNo);
  284. }
  285. string[] s = strValue.Split(',');
  286. ICell cell = null;
  287. for (int i = 0; i < s.Length; i++)
  288. {
  289. cell = row1.CreateCell(i);
  290. cell.SetCellValue(s[i]);
  291. }
  292. using (FileStream fileStream = File.Create(filePath))
  293. {
  294. wk.Write(fileStream);
  295. fileStream.Close();
  296. }
  297. return true;
  298. }
  299. catch (Exception ex)
  300. {
  301. MessageBox.Show($"Excel写入行出错\r\nExcel insert row error\r\n{ex.Message}", "Warning");
  302. return false;
  303. }
  304. }
  305. /// <summary>
  306. /// 向Excel文件写入一列以逗号分隔的字符串
  307. /// </summary>
  308. /// <param name="filePath">Excel文件完整路径</param>
  309. /// <param name="sheetname">工作表名称</param>
  310. /// <param name="column">写入位置(列)</param>
  311. /// <param name="startRow">写入位置(起始行)</param>
  312. /// <param name="strValue">写入内容</param>
  313. /// <returns></returns>
  314. public bool WriteColumn(string filePath, int column,int startRow,string strValue, string sheetname = null)
  315. {
  316. try
  317. {
  318. IWorkbook wk = null;
  319. using (FileStream fs = File.Open(filePath, FileMode.Open,
  320. FileAccess.Read, FileShare.ReadWrite))
  321. {
  322. if (filePath.Contains(".xlsx"))
  323. {
  324. wk = new XSSFWorkbook(fs);
  325. }
  326. else
  327. {
  328. wk = new HSSFWorkbook(fs);
  329. }
  330. fs.Close();
  331. }
  332. ISheet sheet = sheetname == null ? wk.GetSheetAt(0) : wk.GetSheet(sheetname);
  333. IRow row = null;
  334. ICell cell = null;
  335. string[] str = strValue.Split(',');
  336. for (int i = 0; i < str.Length; i++)
  337. {
  338. row = sheet.GetRow(startRow+i);
  339. if (row == null)
  340. {
  341. row = sheet.CreateRow(startRow+i);
  342. }
  343. cell = row.CreateCell(column);
  344. cell.SetCellValue(str[i]);
  345. }
  346. using (FileStream fileStream = File.Create(filePath))
  347. {
  348. wk.Write(fileStream);
  349. fileStream.Close();
  350. }
  351. return true;
  352. }
  353. catch (Exception ex)
  354. {
  355. MessageBox.Show($"Excel写入列出错\r\nExcel write column error\r\n{ex.Message}", "Warning");
  356. return false;
  357. }
  358. }
  359. /// <summary>
  360. /// 向Excel文件写入一列double数组
  361. /// </summary>
  362. /// <param name="filePath">Excel文件完整路径</param>
  363. /// <param name="sheetname">工作表名称</param>
  364. /// <param name="column">写入位置(列)</param>
  365. /// <param name="startRow">写入位置(起始行)</param>
  366. /// <param name="dValue">写入内容</param>
  367. /// <returns></returns>
  368. public bool WriteColumn(string filePath, int column, int startRow, double[] dValue, string sheetname = null)
  369. {
  370. try
  371. {
  372. IWorkbook wk = null;
  373. using (FileStream fs = File.Open(filePath, FileMode.Open,
  374. FileAccess.Read, FileShare.ReadWrite))
  375. {
  376. if (filePath.Contains(".xlsx"))
  377. {
  378. wk = new XSSFWorkbook(fs);
  379. }
  380. else
  381. {
  382. wk = new HSSFWorkbook(fs);
  383. }
  384. fs.Close();
  385. }
  386. ISheet sheet = sheetname == null ? wk.GetSheetAt(0) : wk.GetSheet(sheetname);
  387. IRow row = null;
  388. ICell cell = null;
  389. for (int i = 0; i < dValue.Length; i++)
  390. {
  391. row = sheet.GetRow(startRow + i);
  392. if (row == null)
  393. {
  394. row = sheet.CreateRow(startRow + i);
  395. }
  396. cell = row.CreateCell(column);
  397. cell.SetCellValue(dValue[i]);
  398. }
  399. using (FileStream fileStream = File.Create(filePath))
  400. {
  401. wk.Write(fileStream);
  402. fileStream.Close();
  403. }
  404. return true;
  405. }
  406. catch (Exception ex)
  407. {
  408. MessageBox.Show($"Excel写入列出错\r\nExcel write column error\r\n{ex.Message}", "Warning");
  409. return false;
  410. }
  411. }
  412. /// <summary>
  413. /// 向Excel文件指定单元格写入数据
  414. /// </summary>
  415. /// <param name="filePath">Excel文件完整路径</param>
  416. /// <param name="sheetname">工作表名称</param>
  417. /// <param name="row">行号</param>
  418. /// <param name="column">列号</param>
  419. /// <param name="strValue">插入内容</param>
  420. /// <returns></returns>
  421. public bool SetCellValue(string filePath, string sheetname, int row, int column, string value)
  422. {
  423. try
  424. {
  425. IWorkbook wk = null;
  426. using (FileStream fs = File.Open(filePath, FileMode.Open,
  427. FileAccess.Read, FileShare.ReadWrite))
  428. {
  429. if (filePath.Contains(".xlsx"))
  430. {
  431. wk = new XSSFWorkbook(fs);
  432. }
  433. else
  434. {
  435. wk = new HSSFWorkbook(fs);
  436. }
  437. fs.Close();
  438. }
  439. ISheet sheet = wk.GetSheet(sheetname);
  440. IRow row1 = sheet.CreateRow(row);
  441. ICell cell = row1.CreateCell(column);
  442. //cell = sheet.GetRow(row).GetCell(column);
  443. //sheet.ForceFormulaRecalculation = true; //强制计算
  444. //sheet.ProtectSheet("123");//密码保护
  445. if (value.Contains(","))
  446. {
  447. string[] s = value.Split(',');
  448. for (int i = 0; i < s.Length; i++)
  449. {
  450. cell = row1.CreateCell(i);
  451. cell.SetCellValue(s[i]);
  452. }
  453. }
  454. else
  455. {
  456. cell.SetCellValue(value);
  457. }
  458. using (FileStream fileStream = File.Create(filePath))
  459. {
  460. wk.Write(fileStream);
  461. fileStream.Close();
  462. }
  463. return true;
  464. }
  465. catch (Exception ex)
  466. {
  467. MessageBox.Show($"Excel向指定单元格写入数据失败\r\nFails to write data to specified cell\r\n{ex.Message}", "Warning");
  468. return false;
  469. }
  470. }
  471. public bool SetExcelCellValue(string filePath, String sheetname, int row, int column, String value)
  472. {
  473. bool returnb;
  474. try
  475. {
  476. IWorkbook wk = null;
  477. using (FileStream fs = File.Open(filePath, FileMode.Open,
  478. FileAccess.Read, FileShare.ReadWrite))
  479. {
  480. if (filePath.Contains(".xlsx"))
  481. {
  482. wk = new XSSFWorkbook(fs);
  483. }
  484. else
  485. {
  486. //把xls文件读入workbook变量里,之后就可以关闭了
  487. wk = new HSSFWorkbook(fs);
  488. }
  489. fs.Close();
  490. }
  491. //把xls文件读入workbook变量里,之后就可以关闭了
  492. ISheet sheet = wk.GetSheet(sheetname);
  493. GetCellValue(cell);
  494. cell = sheet.GetRow(row).GetCell(column);
  495. cell.SetCellValue(value);
  496. using (FileStream fileStream = File.Create(filePath))
  497. {
  498. wk.Write(fileStream);
  499. fileStream.Close();
  500. }
  501. returnb = true;
  502. }
  503. catch (Exception ex)
  504. {
  505. MessageBox.Show(ex.Message);
  506. returnb = false;
  507. // throw;
  508. }
  509. return returnb;
  510. }
  511. //获取cell的数据,并设置为对应的数据类型
  512. public object GetCellValue(ICell cell)
  513. {
  514. object value = null;
  515. try
  516. {
  517. if (cell.CellType != CellType.Blank)
  518. {
  519. switch (cell.CellType)
  520. {
  521. case CellType.Numeric:
  522. // Date comes here
  523. if (DateUtil.IsCellDateFormatted(cell))
  524. {
  525. value = cell.DateCellValue;
  526. }
  527. else
  528. {
  529. // Numeric type
  530. value = cell.NumericCellValue;
  531. }
  532. break;
  533. case CellType.Boolean:
  534. // Boolean type
  535. value = cell.BooleanCellValue;
  536. break;
  537. case CellType.Formula:
  538. value = cell.CellFormula;
  539. break;
  540. default:
  541. // String type
  542. value = cell.StringCellValue;
  543. break;
  544. }
  545. }
  546. }
  547. catch (Exception)
  548. {
  549. value = "";
  550. }
  551. return value;
  552. }
  553. /// <summary>
  554. /// 设置sheet密码
  555. /// </summary>
  556. /// <param name="filePath">Excel文件完整路径</param>
  557. /// <param name="password">要设置的密码</param>
  558. /// <param name="sheetname">工作表名称(可为空)</param>
  559. /// <returns></returns>
  560. public void SetSheetPassword(string filePath, string password, string sheetname=null)
  561. {
  562. IWorkbook wk = null;
  563. using (FileStream fs = File.Open(filePath, FileMode.Open,
  564. FileAccess.Read, FileShare.ReadWrite))
  565. {
  566. if (filePath.Contains(".xlsx"))
  567. {
  568. wk = new XSSFWorkbook(fs);
  569. }
  570. else
  571. {
  572. wk = new HSSFWorkbook(fs);
  573. }
  574. fs.Close();
  575. }
  576. ISheet sheet = null;
  577. if (string.IsNullOrEmpty(sheetname))
  578. {
  579. sheet = wk.GetSheetAt(0);
  580. }
  581. else
  582. {
  583. sheet = wk.GetSheet(sheetname);
  584. }
  585. //sheet.SetColumnWidth(0, 15 * 256);//设置列宽
  586. sheet.ProtectSheet(password);
  587. using (FileStream fileStream = File.Create(filePath))
  588. {
  589. wk.Write(fileStream);
  590. fileStream.Close();
  591. }
  592. }
  593. /// <summary>
  594. /// 读Excel文件指定单元格数据
  595. /// </summary>
  596. /// <param name="filePath">Excel文件完整路径</param>
  597. /// <param name="sheetname">工作表名称</param>
  598. /// <param name="row">行号</param>
  599. /// <param name="column">列号</param>
  600. /// <returns></returns>
  601. public string GetCellValue(string filePath, string sheetname, int row, int column)
  602. {
  603. try
  604. {
  605. IWorkbook wk = null;
  606. using (FileStream fs = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
  607. {
  608. if (filePath.Contains(".xlsx"))
  609. {
  610. wk = new XSSFWorkbook(fs);
  611. }
  612. else
  613. {
  614. wk = new HSSFWorkbook(fs);
  615. }
  616. fs.Close();
  617. }
  618. ISheet sheet = wk.GetSheet(sheetname);
  619. ICell cell = sheet.GetRow(row).GetCell(column);
  620. return cell.ToString();
  621. }
  622. catch (Exception ex)
  623. {
  624. MessageBox.Show($"读Excel文件指定单元格数据失败\r\nReading specified cell data failed\r\n{ex.Message}", "Warning");
  625. return null;
  626. }
  627. }
  628. /// <summary>
  629. /// 创建Excel文件
  630. /// </summary>
  631. /// <param name="filePath">Excel文件完整路径</param>
  632. /// <param name="SheetName">工作表名称</param>
  633. /// <returns></returns>
  634. public bool CreatExcel(string filePath, string[] SheetName = null)
  635. {
  636. try
  637. {
  638. IWorkbook wk = null;
  639. if (filePath.Contains(".xlsx"))
  640. {
  641. wk = new XSSFWorkbook();
  642. }
  643. else
  644. {
  645. wk = new HSSFWorkbook();
  646. }
  647. SheetName = SheetName ?? (new string[] { "sheet1" });
  648. for (int i = 0; i < SheetName.Length; i++)
  649. {
  650. wk.CreateSheet(SheetName[i]);
  651. }
  652. FileStream fs = new FileStream(filePath, FileMode.Create);
  653. wk.Write(fs);
  654. fs.Close();
  655. return true;
  656. }
  657. catch (Exception ex)
  658. {
  659. MessageBox.Show($"创建Excel失败\r\nExcel creation failed\r\n{ex.Message}", "Error");
  660. return false;
  661. }
  662. }
  663. /// <summary>
  664. /// 把DataTable数据写入Excel文件
  665. /// </summary>
  666. /// <param name="filePath">Excel文件完整路径</param>
  667. /// <param name="dt">DataTable数据</param>
  668. /// <returns></returns>
  669. public bool DataTableToExcel(string filePath, DataTable dt)
  670. {
  671. try
  672. {
  673. IWorkbook wk = null;
  674. if (File.Exists(filePath))
  675. {
  676. File.Delete(filePath);
  677. }
  678. if (!File.Exists(filePath)) //判断文件是否存在,不存在时则创建并添加表头
  679. {
  680. if (filePath.Contains(".xlsx"))
  681. {
  682. wk = new XSSFWorkbook();
  683. }
  684. else
  685. {
  686. wk = new HSSFWorkbook();
  687. }
  688. using (FileStream fs1 = new FileStream(filePath, FileMode.OpenOrCreate))//读取流
  689. {
  690. //创建sheet
  691. ISheet sheet = wk.CreateSheet("Sheet1");
  692. for (int i = 0; i < dt.Rows.Count; i++)
  693. {
  694. IRow row = sheet.CreateRow(i);
  695. for (int j = 0; j < dt.Columns.Count; j++)
  696. {
  697. ICell cell = row.CreateCell(j);
  698. cell.SetCellValue(dt.Rows[i][j].ToString());
  699. }
  700. }
  701. wk.Write(fs1);
  702. fs1.Close();
  703. }
  704. }
  705. else
  706. { //如果文件已存在则首先打开,并且获取到最大的行数
  707. using (FileStream fs = new FileStream(filePath, FileMode.Open))//读取流
  708. {
  709. if (filePath.Contains(".xlsx"))
  710. {
  711. wk = new XSSFWorkbook(fs);
  712. }
  713. else
  714. {
  715. wk = new HSSFWorkbook(fs);
  716. }
  717. ISheet sheet1 = wk.GetSheetAt(0);
  718. //int num = sheet1.LastRowNum + 1;//获取最大行数
  719. FileStream fout = new FileStream(filePath, FileMode.Open, FileAccess.Write, FileShare.ReadWrite);//写入流
  720. for (int i = 0; i < dt.Rows.Count; i++)
  721. {
  722. //创建行数时+num
  723. IRow row = sheet1.CreateRow(i);
  724. for (int j = 0; j < dt.Columns.Count; j++)
  725. {
  726. ICell cell = row.CreateCell(j);
  727. cell.SetCellValue(dt.Rows[i][j].ToString());
  728. }
  729. }
  730. wk.Write(fout);
  731. fs.Close();
  732. fout.Close();
  733. }
  734. }
  735. return true;
  736. }
  737. catch
  738. {
  739. //MessageBox.Show($"创建Excel失败\r\nExcel creation failed\r\n{ex.Message}", "Error");
  740. return false;
  741. }
  742. }
  743. /// <summary>
  744. /// 读Excel文件指定Sheet数据,返回二维数组字符串
  745. /// </summary>
  746. /// <param name="filePath">Excel文件完整路径</param>
  747. /// <param name="SheetName">工作表名称</param>
  748. /// <param name="iRow">行号</param>
  749. /// <param name="iColumn">列号</param>
  750. /// <returns></returns>
  751. public string[,] ReadSheetData(string filePath, string SheetName = "", int iRow = -1, int iColumn = -1)
  752. {
  753. try
  754. {
  755. if (!File.Exists(filePath))
  756. {
  757. MessageBox.Show($"{filePath} 文件不存在!\r\nThe specified excel file could not be found or is corrupted!");
  758. return null;
  759. }
  760. IWorkbook wk = null;
  761. using (FileStream fs = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
  762. {
  763. if (filePath.Contains(".xlsx"))
  764. {
  765. wk = new XSSFWorkbook(fs);
  766. }
  767. else
  768. {
  769. wk = new HSSFWorkbook(fs);
  770. }
  771. fs.Close();
  772. }
  773. ISheet sheet = string.IsNullOrEmpty(SheetName) ? wk.GetSheetAt(0) : wk.GetSheet(SheetName);
  774. iRow = iRow > 0 ? iRow : sheet.LastRowNum -sheet.FirstRowNum+ 1;
  775. iColumn = iColumn > 0 ? iColumn : sheet.GetRow(sheet.FirstRowNum).LastCellNum + 1;
  776. string[,] ret = new string[iRow, iColumn];
  777. for (int i = sheet.FirstRowNum; i < iRow; i++)
  778. {
  779. for (int j = 0; j < iColumn; j++)
  780. {
  781. try
  782. {
  783. ret[i- sheet.FirstRowNum, j] = sheet.GetRow(i).GetCell(j).ToString();
  784. }
  785. catch
  786. {
  787. ret[i- sheet.FirstRowNum, j] = "";
  788. }
  789. }
  790. }
  791. return ret;
  792. }
  793. catch (Exception ex)
  794. {
  795. MessageBox.Show($"读取Sheet数据失败\r\nFailed to read sheet data\r\n{ex.Message}", "Error");
  796. return null;
  797. }
  798. }
  799. /// <summary>
  800. /// 合并单元格
  801. /// </summary>
  802. /// <param name="filePath">Excel文件完整路径</param>
  803. /// <param name="sheetname">工作表名称</param>
  804. /// <param name="startRow">开始行</param>
  805. /// <param name="endRow">结束行</param>
  806. /// <param name="startColumn">开始列</param>
  807. /// <param name="endColumn">结束列</param>
  808. /// <param name="value">合并后写入的数据</param>
  809. /// <param name="fontsize">字体大小</param>
  810. /// <returns></returns>
  811. public bool MergeCells(string filePath, int[] startRow, int[] endRow, int[] startColumn, int[] endColumn,
  812. string[] value=null,double[] fontsize=null, string sheetname = null)
  813. {
  814. try
  815. {
  816. IWorkbook wk = null;
  817. using (FileStream fs = File.Open(filePath, FileMode.Open,FileAccess.Read, FileShare.ReadWrite))
  818. {
  819. if (filePath.Contains(".xlsx"))
  820. {
  821. wk = new XSSFWorkbook(fs);
  822. }
  823. else
  824. {
  825. wk = new HSSFWorkbook(fs);
  826. }
  827. fs.Close();
  828. }
  829. ISheet sheet = string.IsNullOrEmpty(sheetname) ? wk.GetSheetAt(0) : wk.GetSheet(sheetname);
  830. for (int i = 0; i < startRow.Length; i++)
  831. {
  832. CellRangeAddress region = new CellRangeAddress(startRow[i], endRow[i], startColumn[i], endColumn[i]);
  833. sheet.AddMergedRegion(region);
  834. ICellStyle style = wk.CreateCellStyle();
  835. style.VerticalAlignment = VerticalAlignment.Center;
  836. style.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
  837. if (fontsize != null)
  838. {
  839. IFont font = wk.CreateFont();
  840. font.FontHeight = fontsize[i];
  841. style.SetFont(font);
  842. }
  843. //style.FillBackgroundColor = HSSFColor.Red.Index;
  844. IRow row = sheet.GetRow(startRow[i]);
  845. ICell cell = null;
  846. if (row == null)
  847. {
  848. row = sheet.CreateRow(startRow[i]);
  849. }
  850. if (row.GetCell(startColumn[i]) == null)
  851. {
  852. cell = row.CreateCell(startColumn[i]);
  853. }
  854. if (value != null)
  855. {
  856. cell.SetCellValue(value[i]);
  857. }
  858. cell.CellStyle = style;
  859. }
  860. using (FileStream fileStream = File.Create(filePath))
  861. {
  862. wk.Write(fileStream);
  863. fileStream.Close();
  864. }
  865. return true;
  866. }
  867. catch (Exception ex)
  868. {
  869. MessageBox.Show($"合并单元格失败\r\nFailed to merge cells\r\n{ex.Message}", "Error");
  870. return false;
  871. }
  872. }
  873. /// <summary>
  874. /// 合并单元格
  875. /// </summary>
  876. /// <param name="filePath">Excel文件完整路径</param>
  877. /// <param name="sheetname">工作表名称</param>
  878. /// <param name="startRow">开始行</param>
  879. /// <param name="endRow">结束行</param>
  880. /// <param name="startColumn">开始列</param>
  881. /// <param name="endColumn">结束列</param>
  882. /// <param name="value">合并后写入的数据</param>
  883. /// <param name="fontsize">字体大小</param>
  884. /// <returns></returns>
  885. public bool MergeCells(string filePath, int startRow, int endRow, int startColumn, int endColumn,
  886. string value = null, double fontsize = -1, string sheetname = null)
  887. {
  888. try
  889. {
  890. IWorkbook wk = null;
  891. using (FileStream fs = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
  892. {
  893. if (filePath.Contains(".xlsx"))
  894. {
  895. wk = new XSSFWorkbook(fs);
  896. }
  897. else
  898. {
  899. wk = new HSSFWorkbook(fs);
  900. }
  901. fs.Close();
  902. }
  903. ISheet sheet = string.IsNullOrEmpty(sheetname) ? wk.GetSheetAt(0) : wk.GetSheet(sheetname);
  904. ICell cell = sheet.CreateRow(startRow).CreateCell(startColumn);
  905. if (value != null)
  906. {
  907. cell.SetCellValue(value);
  908. }
  909. CellRangeAddress region = new CellRangeAddress(startRow, endRow, startColumn, endColumn);
  910. sheet.AddMergedRegion(region);
  911. ICellStyle style = wk.CreateCellStyle();
  912. style.VerticalAlignment = VerticalAlignment.Center;
  913. style.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
  914. if (fontsize >0)
  915. {
  916. IFont font = wk.CreateFont();
  917. font.FontHeight = fontsize;
  918. style.SetFont(font);
  919. }
  920. //style.FillBackgroundColor = HSSFColor.Red.Index;
  921. cell.CellStyle = style;
  922. using (FileStream fileStream = File.Create(filePath))
  923. {
  924. wk.Write(fileStream);
  925. fileStream.Close();
  926. }
  927. return true;
  928. }
  929. catch (Exception ex)
  930. {
  931. MessageBox.Show($"合并单元格失败\r\nFailed to merge cells\r\n{ex.Message}", "Error");
  932. return false;
  933. }
  934. }
  935. }
  936. }