ExcelHelper.cs 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Web;
  6. using System.ComponentModel;
  7. using System.Reflection;
  8. using System.Data;
  9. using NPOI.HPSF;
  10. using NPOI.SS.Util;
  11. using NPOI.HSSF.Util;
  12. using NPOI.HSSF.UserModel;
  13. using NPOI.SS.UserModel;
  14. using System.IO;
  15. using NPOI.XSSF.UserModel;
  16. namespace Winsoft.GOV.ImportDataForm
  17. {
  18. public class ExcelHelper
  19. {
  20. public delegate T GetRowEvent<T>(IRow row);
  21. public delegate void WriteRowEvent<T>(IRow row, T obj);
  22. public delegate void WriteHeardEvent(IRow row);
  23. public static void WriteExcel<T>(IList<T> list, string filePath, WriteHeardEvent wh, WriteRowEvent<T> wr)
  24. {
  25. if (!string.IsNullOrEmpty(filePath) && null != list && list.Count > 0)
  26. {
  27. IWorkbook book;
  28. if (Path.GetExtension(filePath) == ".xls")
  29. {
  30. book = new HSSFWorkbook();
  31. }
  32. else
  33. {
  34. book = new XSSFWorkbook();
  35. }
  36. ISheet sheet = book.CreateSheet(Path.GetFileNameWithoutExtension(filePath));
  37. wh(sheet.CreateRow(0));
  38. int i = 1;
  39. foreach(T obj in list)
  40. {
  41. wr(sheet.CreateRow(i), obj);
  42. i++;
  43. }
  44. // 写入到客户端
  45. using (MemoryStream ms = new MemoryStream())
  46. {
  47. book.Write(ms);
  48. using (FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write))
  49. {
  50. byte[] data = ms.ToArray();
  51. fs.Write(data, 0, data.Length);
  52. fs.Flush();
  53. }
  54. book = null;
  55. }
  56. }
  57. }
  58. public static IList<T> ExcelToList<T>(string excelPath, GetRowEvent<T> f)
  59. {
  60. return ExcelToList(excelPath, true, f);
  61. }
  62. public static IList<T> ExcelToList<T>(string excelPath, bool firstRowAsHeader, GetRowEvent<T> f)
  63. {
  64. int sheetCount;
  65. return ExcelToList(excelPath, firstRowAsHeader, out sheetCount, f);
  66. }
  67. public static IList<T> ExcelToList<T>(string excelPath, bool firstRowAsHeader, out int sheetCount, GetRowEvent<T> f)
  68. {
  69. IList<T> list = new List<T>();
  70. using (FileStream fileStream = new FileStream(excelPath, FileMode.Open, FileAccess.Read))
  71. {
  72. IWorkbook workbook;
  73. IFormulaEvaluator evaluator;
  74. if (Path.GetExtension(excelPath) == ".xls")
  75. {
  76. workbook = new HSSFWorkbook(fileStream);
  77. evaluator = new HSSFFormulaEvaluator(workbook);
  78. }
  79. else
  80. {
  81. workbook = new XSSFWorkbook(fileStream);
  82. evaluator = new XSSFFormulaEvaluator(workbook);
  83. }
  84. sheetCount = workbook.NumberOfSheets;
  85. for (int i = 0; i < sheetCount; ++i)
  86. {
  87. ISheet sheet = workbook.GetSheetAt(i);
  88. ExcelToList(firstRowAsHeader, sheet, evaluator, ref list, f);
  89. }
  90. return list;
  91. }
  92. }
  93. private static void ExcelToList<T>(bool firstRowAsHeader, ISheet sheet, IFormulaEvaluator evaluator, ref IList<T> list, GetRowEvent<T> f)
  94. {
  95. if (sheet.LastRowNum == 0)
  96. return;
  97. int i = sheet.FirstRowNum;
  98. if (firstRowAsHeader)
  99. i++;
  100. for (; i <= sheet.LastRowNum; i++)
  101. {
  102. IRow row = sheet.GetRow(i);
  103. if (row == null)
  104. return;
  105. T obj = f(row);
  106. if (obj == null)
  107. continue;
  108. list.Add(obj);
  109. }
  110. }
  111. /// <summary>
  112. /// Excel读取到DataSet
  113. /// </summary>
  114. /// <param name="excelPath"></param>
  115. /// <returns></returns>
  116. public static DataSet ExcelToDataSet(string excelPath)
  117. {
  118. return ExcelToDataSet(excelPath, true);
  119. }
  120. /// <summary>
  121. /// Excel读取到DataSet
  122. /// </summary>
  123. /// <param name="excelPath"></param>
  124. /// <param name="firstRowAsHeader"></param>
  125. /// <returns></returns>
  126. public static DataSet ExcelToDataSet(string excelPath, bool firstRowAsHeader)
  127. {
  128. int sheetCount;
  129. return ExcelToDataSet(excelPath, firstRowAsHeader, out sheetCount);
  130. }
  131. /// <summary>
  132. /// Excel读取到DataSet
  133. /// </summary>
  134. /// <param name="excelPath"></param>
  135. /// <param name="firstRowAsHeader"></param>
  136. /// <param name="sheetCount"></param>
  137. /// <returns></returns>
  138. public static DataSet ExcelToDataSet(string excelPath, bool firstRowAsHeader, out int sheetCount)
  139. {
  140. using (DataSet ds = new DataSet())
  141. {
  142. using (FileStream fileStream = new FileStream(excelPath, FileMode.Open, FileAccess.Read))
  143. {
  144. IWorkbook workbook;
  145. IFormulaEvaluator evaluator;
  146. if (Path.GetExtension(excelPath) == ".xls")
  147. {
  148. workbook = new HSSFWorkbook(fileStream);
  149. evaluator = new HSSFFormulaEvaluator(workbook);
  150. }
  151. else
  152. {
  153. workbook = new XSSFWorkbook(fileStream);
  154. evaluator = new XSSFFormulaEvaluator(workbook);
  155. }
  156. sheetCount = workbook.NumberOfSheets;
  157. for (int i = 0; i < sheetCount; ++i)
  158. {
  159. ISheet sheet = workbook.GetSheetAt(i);
  160. DataTable dt = ExcelToDataTable(sheet, evaluator, firstRowAsHeader);
  161. ds.Tables.Add(dt);
  162. }
  163. return ds;
  164. }
  165. }
  166. }
  167. /// <summary>
  168. /// Excel读取到DataTable
  169. /// </summary>
  170. /// <param name="excelPath"></param>
  171. /// <param name="sheetName"></param>
  172. /// <returns></returns>
  173. public static DataTable ExcelToDataTable(string excelPath, string sheetName)
  174. {
  175. return ExcelToDataTable(excelPath, sheetName, true);
  176. }
  177. /// <summary>
  178. /// Excel读取到DataTable
  179. /// </summary>
  180. /// <param name="excelPath"></param>
  181. /// <param name="sheetName"></param>
  182. /// <param name="firstRowAsHeader"></param>
  183. /// <returns></returns>
  184. public static DataTable ExcelToDataTable(string excelPath, string sheetName, bool firstRowAsHeader)
  185. {
  186. using (FileStream fileStream = new FileStream(excelPath, FileMode.Open, FileAccess.Read))
  187. {
  188. IWorkbook workbook;
  189. IFormulaEvaluator evaluator;
  190. if (Path.GetExtension(excelPath) == ".xls")
  191. {
  192. workbook = new HSSFWorkbook(fileStream);
  193. evaluator = new HSSFFormulaEvaluator(workbook);
  194. }
  195. else
  196. {
  197. workbook = new XSSFWorkbook(fileStream);
  198. evaluator = new XSSFFormulaEvaluator(workbook);
  199. }
  200. ISheet sheet = workbook.GetSheet(sheetName) as ISheet;
  201. return ExcelToDataTable(sheet, evaluator, firstRowAsHeader);
  202. }
  203. }
  204. private static DataTable ExcelToDataTable(ISheet sheet, IFormulaEvaluator evaluator, bool firstRowAsHeader)
  205. {
  206. if (firstRowAsHeader)
  207. {
  208. return ExcelToDataTableFirstRowAsHeader(sheet, evaluator);
  209. }
  210. else
  211. {
  212. return ExcelToDataTable(sheet, evaluator);
  213. }
  214. }
  215. private static DataTable ExcelToDataTableFirstRowAsHeader(ISheet sheet, IFormulaEvaluator evaluator)
  216. {
  217. using (DataTable dt = new DataTable())
  218. {
  219. IRow firstRow = sheet.GetRow(0);
  220. int cellCount = GetCellCount(sheet);
  221. for (int i = 0; i < cellCount; i++)
  222. {
  223. if (firstRow.GetCell(i) != null)
  224. {
  225. dt.Columns.Add(firstRow.GetCell(i).StringCellValue ?? string.Format("F{0}", i + 1), typeof(string));
  226. }
  227. else
  228. {
  229. dt.Columns.Add(string.Format("F{0}", i + 1), typeof(string));
  230. }
  231. }
  232. for (int i = 1; i <= sheet.LastRowNum; i++)
  233. {
  234. IRow row = sheet.GetRow(i);
  235. DataRow dr = dt.NewRow();
  236. FillDataRowByHSSFRow(row, evaluator, ref dr);
  237. dt.Rows.Add(dr);
  238. }
  239. dt.TableName = sheet.SheetName;
  240. return dt;
  241. }
  242. }
  243. private static DataTable ExcelToDataTable(ISheet sheet, IFormulaEvaluator evaluator)
  244. {
  245. using (DataTable dt = new DataTable())
  246. {
  247. if (sheet.LastRowNum != 0)
  248. {
  249. int cellCount = GetCellCount(sheet);
  250. for (int i = 0; i < cellCount; i++)
  251. {
  252. dt.Columns.Add(string.Format("F{0}", i), typeof(string));
  253. }
  254. for (int i = 0; i < sheet.FirstRowNum; ++i)
  255. {
  256. DataRow dr = dt.NewRow();
  257. dt.Rows.Add(dr);
  258. }
  259. for (int i = sheet.FirstRowNum; i <= sheet.LastRowNum; i++)
  260. {
  261. IRow row = sheet.GetRow(i) as IRow;
  262. DataRow dr = dt.NewRow();
  263. FillDataRowByHSSFRow(row, evaluator, ref dr);
  264. dt.Rows.Add(dr);
  265. }
  266. }
  267. dt.TableName = sheet.SheetName;
  268. return dt;
  269. }
  270. }
  271. private static void FillDataRowByHSSFRow(IRow row, IFormulaEvaluator evaluator, ref DataRow dr)
  272. {
  273. if (row != null)
  274. {
  275. for (int j = 0; j < dr.Table.Columns.Count; j++)
  276. {
  277. ICell cell = row.GetCell(j) as ICell;
  278. if (cell != null)
  279. {
  280. switch (cell.CellType)
  281. {
  282. case CellType.Blank:
  283. dr[j] = DBNull.Value;
  284. break;
  285. case CellType.Boolean:
  286. dr[j] = cell.BooleanCellValue;
  287. break;
  288. case CellType.Numeric:
  289. if (DateUtil.IsCellDateFormatted(cell))
  290. {
  291. dr[j] = cell.DateCellValue;
  292. }
  293. else
  294. {
  295. dr[j] = cell.NumericCellValue;
  296. }
  297. break;
  298. case CellType.String:
  299. dr[j] = cell.StringCellValue;
  300. break;
  301. case CellType.Error:
  302. dr[j] = cell.ErrorCellValue;
  303. break;
  304. case CellType.Formula:
  305. cell = evaluator.EvaluateInCell(cell) as ICell;
  306. dr[j] = cell.ToString();
  307. break;
  308. default:
  309. throw new NotSupportedException(string.Format("Catched unhandle CellType[{0}]", cell.CellType));
  310. }
  311. }
  312. }
  313. }
  314. }
  315. private static int GetCellCount(ISheet sheet)
  316. {
  317. int firstRowNum = sheet.FirstRowNum;
  318. int cellCount = 0;
  319. for (int i = sheet.FirstRowNum; i <= sheet.LastRowNum; ++i)
  320. {
  321. IRow row = sheet.GetRow(i) as IRow;
  322. if (row != null && row.LastCellNum > cellCount)
  323. {
  324. cellCount = row.LastCellNum;
  325. }
  326. }
  327. return cellCount;
  328. }
  329. }
  330. public class ExcelHelper<T> where T : new()
  331. {
  332. #region Entity To Excel
  333. /// <summary>
  334. /// 返回 Excel导出配置对象
  335. /// </summary>
  336. /// <returns></returns>
  337. public static ExcelExportSetting<T> CreateExportInstance()
  338. {
  339. return new ExcelExportSetting<T>();
  340. }
  341. #endregion
  342. }
  343. public class ExcelExportSetting<T>
  344. {
  345. string fileName = "导出Excel";
  346. /// <summary>
  347. /// Excel标题
  348. /// </summary>
  349. public string FileName
  350. {
  351. get { return fileName; }
  352. set { fileName = value; }
  353. }
  354. string title = String.Empty;
  355. /// <summary>
  356. /// Excel标题
  357. /// </summary>
  358. public string Title
  359. {
  360. get { return title; }
  361. set { title = value; }
  362. }
  363. string description = String.Empty;
  364. /// <summary>
  365. /// Excel描述
  366. /// </summary>
  367. public string Description
  368. {
  369. get { return description; }
  370. set { description = value; }
  371. }
  372. private IEnumerable<T> source;
  373. /// <summary>
  374. /// 数据源
  375. /// </summary>
  376. public IEnumerable<T> Source
  377. {
  378. get { return source; }
  379. set { source = value; }
  380. }
  381. IEnumerable<ExcelColum<T>> colum;
  382. /// <summary>
  383. /// 列配置
  384. /// </summary>
  385. public IEnumerable<ExcelColum<T>> Colum
  386. {
  387. get { return colum; }
  388. set { colum = value; }
  389. }
  390. IEnumerable<ExcelColumGroup> columGroup;
  391. /// <summary>
  392. /// 列头分组
  393. /// </summary>
  394. public IEnumerable<ExcelColumGroup> ColumGroup
  395. {
  396. get { return columGroup; }
  397. set { columGroup = value; }
  398. }
  399. }
  400. /// <summary>
  401. /// Excel数据列
  402. /// </summary>
  403. /// <typeparam name="K"></typeparam>
  404. public class ExcelColum<K>
  405. {
  406. /// <summary>
  407. /// 列名称
  408. /// </summary>
  409. public string Name = String.Empty;
  410. short width = 0;
  411. /// <summary>
  412. /// 列宽度
  413. /// </summary>
  414. public short Width
  415. {
  416. get { return this.width; }
  417. set { this.width = value; }
  418. }
  419. private ExcelColumType realColumType;
  420. /// <summary>
  421. /// 实际Excel类型
  422. /// </summary>
  423. internal ExcelColumType RealColumType
  424. {
  425. get { return realColumType; }
  426. set { realColumType = value; }
  427. }
  428. ExcelColumType columType;
  429. /// <summary>
  430. /// 列数据类型
  431. /// </summary>
  432. public ExcelColumType ColumType
  433. {
  434. get { return columType; }
  435. set { columType = value; }
  436. }
  437. /// <summary>
  438. /// 是否对该列求和
  439. /// </summary>
  440. public bool DoColumSum
  441. {
  442. get;
  443. set;
  444. }
  445. Func<K, object> result;
  446. /// <summary>
  447. /// 计算列单元格结果
  448. /// </summary>
  449. public Func<K, object> Result
  450. {
  451. get { return result; }
  452. set { result = value; }
  453. }
  454. string fieldName;
  455. /// <summary>
  456. /// 自定特定字段 , 服务于 ResultByFieldName
  457. /// </summary>
  458. public string FieldName
  459. {
  460. get { return fieldName; }
  461. set { fieldName = value; }
  462. }
  463. Func<K, string, object> resultByFieldName;
  464. /// <summary>
  465. /// 指定特定字段运行委托,基于FieldName;如果 Result为null 则执行
  466. /// K 对象
  467. /// string 字段名
  468. /// object 返回值
  469. /// </summary>
  470. public Func<K, string, object> ResultByFieldName
  471. {
  472. get { return resultByFieldName; }
  473. set { resultByFieldName = value; }
  474. }
  475. }
  476. public class ExcelColumGroup
  477. {
  478. int cols;
  479. /// <summary>
  480. /// 合并单元格列数
  481. /// </summary>
  482. public int Cols
  483. {
  484. get { return cols; }
  485. set { cols = value; }
  486. }
  487. string name;
  488. /// <summary>
  489. /// 分组名称
  490. /// </summary>
  491. public string Name
  492. {
  493. get { return name; }
  494. set { name = value; }
  495. }
  496. int startIndex;
  497. /// <summary>
  498. /// 其实位置索引
  499. /// </summary>
  500. public int StartIndex
  501. {
  502. get { return startIndex; }
  503. set { startIndex = value; }
  504. }
  505. }
  506. /// <summary>
  507. /// Excel支持的数据类型
  508. /// </summary>
  509. public enum ExcelColumType
  510. {
  511. Double,
  512. String,
  513. DateTime,
  514. Bool
  515. }
  516. public static class ExcelExportExtension
  517. {
  518. #region excel import
  519. /// <summary>
  520. /// Excel读取到DataSet
  521. /// </summary>
  522. /// <param name="excelPath"></param>
  523. /// <returns></returns>
  524. public static DataSet ExcelToDataSet(string excelPath)
  525. {
  526. return ExcelToDataSet(excelPath, true);
  527. }
  528. /// <summary>
  529. /// Excel读取到DataSet
  530. /// </summary>
  531. /// <param name="excelPath"></param>
  532. /// <param name="firstRowAsHeader"></param>
  533. /// <returns></returns>
  534. public static DataSet ExcelToDataSet(string excelPath, bool firstRowAsHeader)
  535. {
  536. int sheetCount;
  537. return ExcelToDataSet(excelPath, firstRowAsHeader, out sheetCount);
  538. }
  539. /// <summary>
  540. /// Excel读取到DataSet
  541. /// </summary>
  542. /// <param name="excelPath"></param>
  543. /// <param name="firstRowAsHeader"></param>
  544. /// <param name="sheetCount"></param>
  545. /// <returns></returns>
  546. public static DataSet ExcelToDataSet(string excelPath, bool firstRowAsHeader, out int sheetCount)
  547. {
  548. using (DataSet ds = new DataSet())
  549. {
  550. using (FileStream fileStream = new FileStream(excelPath, FileMode.Open, FileAccess.Read))
  551. {
  552. IWorkbook workbook;
  553. IFormulaEvaluator evaluator;
  554. if (Path.GetExtension(excelPath) == ".xls")
  555. {
  556. workbook = new HSSFWorkbook(fileStream);
  557. evaluator = new HSSFFormulaEvaluator(workbook);
  558. }
  559. else
  560. {
  561. workbook = new XSSFWorkbook(fileStream);
  562. evaluator = new XSSFFormulaEvaluator(workbook);
  563. }
  564. sheetCount = workbook.NumberOfSheets;
  565. for (int i = 0; i < sheetCount; ++i)
  566. {
  567. ISheet sheet = workbook.GetSheetAt(i) as ISheet;
  568. DataTable dt = ExcelToDataTable(sheet, evaluator, firstRowAsHeader);
  569. ds.Tables.Add(dt);
  570. }
  571. return ds;
  572. }
  573. }
  574. }
  575. /// <summary>
  576. /// Excel读取到DataTable
  577. /// </summary>
  578. /// <param name="excelPath"></param>
  579. /// <param name="sheetName"></param>
  580. /// <returns></returns>
  581. public static DataTable ExcelToDataTable(string excelPath, string sheetName)
  582. {
  583. return ExcelToDataTable(excelPath, sheetName, true);
  584. }
  585. /// <summary>
  586. /// Excel读取到DataTable
  587. /// </summary>
  588. /// <param name="excelPath"></param>
  589. /// <param name="sheetName"></param>
  590. /// <param name="firstRowAsHeader"></param>
  591. /// <returns></returns>
  592. public static DataTable ExcelToDataTable(string excelPath, string sheetName, bool firstRowAsHeader)
  593. {
  594. using (FileStream fileStream = new FileStream(excelPath, FileMode.Open, FileAccess.Read))
  595. {
  596. IWorkbook workbook;
  597. IFormulaEvaluator evaluator;
  598. if (Path.GetExtension(excelPath) == ".xls")
  599. {
  600. workbook = new HSSFWorkbook(fileStream);
  601. evaluator = new HSSFFormulaEvaluator(workbook);
  602. }
  603. else
  604. {
  605. workbook = new XSSFWorkbook(fileStream);
  606. evaluator = new XSSFFormulaEvaluator(workbook);
  607. }
  608. ISheet sheet = workbook.GetSheet(sheetName) as ISheet;
  609. return ExcelToDataTable(sheet, evaluator, firstRowAsHeader);
  610. }
  611. }
  612. private static DataTable ExcelToDataTable(ISheet sheet, IFormulaEvaluator evaluator, bool firstRowAsHeader)
  613. {
  614. if (firstRowAsHeader)
  615. {
  616. return ExcelToDataTableFirstRowAsHeader(sheet, evaluator);
  617. }
  618. else
  619. {
  620. return ExcelToDataTable(sheet, evaluator);
  621. }
  622. }
  623. private static DataTable ExcelToDataTableFirstRowAsHeader(ISheet sheet, IFormulaEvaluator evaluator)
  624. {
  625. using (DataTable dt = new DataTable())
  626. {
  627. IRow firstRow = sheet.GetRow(0);
  628. int cellCount = GetCellCount(sheet);
  629. for (int i = 0; i < cellCount; i++)
  630. {
  631. if (firstRow.GetCell(i) != null)
  632. {
  633. dt.Columns.Add(firstRow.GetCell(i).StringCellValue ?? string.Format("F{0}", i + 1), typeof(string));
  634. }
  635. else
  636. {
  637. dt.Columns.Add(string.Format("F{0}", i + 1), typeof(string));
  638. }
  639. }
  640. for (int i = 1; i <= sheet.LastRowNum; i++)
  641. {
  642. IRow row = sheet.GetRow(i);
  643. DataRow dr = dt.NewRow();
  644. FillDataRowByHSSFRow(row, evaluator, ref dr);
  645. dt.Rows.Add(dr);
  646. }
  647. dt.TableName = sheet.SheetName;
  648. return dt;
  649. }
  650. }
  651. private static DataTable ExcelToDataTable(ISheet sheet, IFormulaEvaluator evaluator)
  652. {
  653. using (DataTable dt = new DataTable())
  654. {
  655. if (sheet.LastRowNum != 0)
  656. {
  657. int cellCount = GetCellCount(sheet);
  658. for (int i = 0; i < cellCount; i++)
  659. {
  660. dt.Columns.Add(string.Format("F{0}", i), typeof(string));
  661. }
  662. for (int i = 0; i < sheet.FirstRowNum; ++i)
  663. {
  664. DataRow dr = dt.NewRow();
  665. dt.Rows.Add(dr);
  666. }
  667. for (int i = sheet.FirstRowNum; i <= sheet.LastRowNum; i++)
  668. {
  669. IRow row = sheet.GetRow(i);
  670. DataRow dr = dt.NewRow();
  671. FillDataRowByHSSFRow(row, evaluator, ref dr);
  672. dt.Rows.Add(dr);
  673. }
  674. }
  675. dt.TableName = sheet.SheetName;
  676. return dt;
  677. }
  678. }
  679. private static void FillDataRowByHSSFRow(IRow row, IFormulaEvaluator evaluator, ref DataRow dr)
  680. {
  681. if (row != null)
  682. {
  683. for (int j = 0; j < dr.Table.Columns.Count; j++)
  684. {
  685. HSSFCell cell = row.GetCell(j) as HSSFCell;
  686. if (cell != null)
  687. {
  688. switch (cell.CellType)
  689. {
  690. case CellType.Blank:
  691. dr[j] = DBNull.Value;
  692. break;
  693. case CellType.Boolean:
  694. dr[j] = cell.BooleanCellValue;
  695. break;
  696. case CellType.Numeric:
  697. if (DateUtil.IsCellDateFormatted(cell))
  698. {
  699. dr[j] = cell.DateCellValue;
  700. }
  701. else
  702. {
  703. dr[j] = cell.NumericCellValue;
  704. }
  705. break;
  706. case CellType.String:
  707. dr[j] = cell.StringCellValue;
  708. break;
  709. case CellType.Error:
  710. dr[j] = cell.ErrorCellValue;
  711. break;
  712. case CellType.Formula:
  713. cell = evaluator.EvaluateInCell(cell) as HSSFCell;
  714. dr[j] = cell.ToString();
  715. break;
  716. default:
  717. throw new NotSupportedException(string.Format("Catched unhandle CellType[{0}]", cell.CellType));
  718. }
  719. }
  720. }
  721. }
  722. }
  723. private static int GetCellCount(ISheet sheet)
  724. {
  725. int firstRowNum = sheet.FirstRowNum;
  726. int cellCount = 0;
  727. for (int i = sheet.FirstRowNum; i <= sheet.LastRowNum; ++i)
  728. {
  729. IRow row = sheet.GetRow(i);
  730. if (row != null && row.LastCellNum > cellCount)
  731. {
  732. cellCount = row.LastCellNum;
  733. }
  734. }
  735. return cellCount;
  736. }
  737. #endregion
  738. /// <summary>
  739. /// 导出Excel,发送数据流到客户端
  740. /// </summary>
  741. /// <typeparam name="T"></typeparam>
  742. /// <param name="setting"></param>
  743. public static void Export<T>(this ExcelExportSetting<T> setting)
  744. {
  745. //string filename = setting.FileName + DateTime.Now.ToString("yyyy-MM-dd/HH:mm") + ".xls";
  746. //string filename = HttpUtility.UrlEncode(setting.FileName + DateTime.Now.ToString("-yyyy-MM-dd-HHmmss") + ".xls", System.Text.Encoding.UTF8);//防止文件名乱码
  747. //System.Web.HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
  748. //System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", filename));
  749. //System.Web.HttpContext.Current.Response.Clear();
  750. //var cols = setting.Colum.Count();
  751. //HSSFWorkbook hssworkbook = new HSSFWorkbook();
  752. //var sheet1 = hssworkbook.CreateSheet("Sheet1");
  753. //DocumentSummaryInformation docSummaryInfo = PropertySetFactory.CreateDocumentSummaryInformation();
  754. //docSummaryInfo.Company = String.Empty;
  755. //SummaryInformation summaryInfo = PropertySetFactory.CreateSummaryInformation();
  756. //summaryInfo.Subject = setting.Title;
  757. //hssworkbook.DocumentSummaryInformation = docSummaryInfo;
  758. //hssworkbook.SummaryInformation = summaryInfo;
  759. ////自动调整某列宽度
  760. //for (var i = 0; i < cols; i++)
  761. //{
  762. // sheet1.AutoSizeColumn(i, true);
  763. //}
  764. //var currentRowIndex = 0;
  765. ////设置标题信息
  766. //if (!String.IsNullOrWhiteSpace(setting.Title))
  767. //{
  768. // var row0 = sheet1.CreateRow(currentRowIndex);
  769. // for (var i = 0; i < cols; i++)
  770. // {
  771. // row0.CreateCell(i).Row.Height = 600;
  772. // }
  773. // row0.GetCell(0).SetCellValue(setting.Title);
  774. // currentRowIndex++;
  775. // //标题样式
  776. // sheet1.AddMergedRegion(new CellRangeAddress(0, 0, 0, cols - 1));
  777. // var titlestyle = hssworkbook.CreateCellStyle();
  778. // titlestyle.WrapText = true;
  779. // var titleFont = hssworkbook.CreateFont();
  780. // titleFont.FontHeight = 20 * 20;
  781. // titlestyle.SetFont(titleFont);
  782. // titlestyle.Alignment = HorizontalAlignment.CENTER;
  783. // sheet1.GetRow(0).GetCell(0).CellStyle = titlestyle;
  784. //}
  785. ////设置描述信息
  786. //if (!String.IsNullOrWhiteSpace(setting.Description))
  787. //{
  788. // var row1 = sheet1.CreateRow(currentRowIndex);
  789. // for (var i = 0; i < cols; i++)
  790. // {
  791. // row1.CreateCell(i).Row.Height = 1000;
  792. // }
  793. // row1.GetCell(0).SetCellValue(setting.Description);
  794. // currentRowIndex++;
  795. // //描述样式
  796. // sheet1.AddMergedRegion(new CellRangeAddress(1, 1, 0, cols - 1));
  797. //}
  798. ////设置列分组
  799. //if (setting.ColumGroup != null && setting.ColumGroup.Count() > 0)
  800. //{
  801. // var rowGroup = sheet1.CreateRow(currentRowIndex);
  802. // var columGroup = setting.ColumGroup;
  803. // for (var i = 0; i < cols; i++)
  804. // {
  805. // var cell = rowGroup.CreateCell(i, CellType.STRING);
  806. // cell.SetCellValue(String.Empty);
  807. // cell.Row.Height = 500;
  808. // }
  809. // var groupStyle = hssworkbook.CreateCellStyle();
  810. // var groupFont = hssworkbook.CreateFont();
  811. // groupFont.FontHeight = 15 * 15;
  812. // groupFont.Boldweight = 6000;
  813. // groupStyle.SetFont(groupFont);
  814. // groupStyle.Alignment = HorizontalAlignment.CENTER;
  815. // for (var j = columGroup.Count() - 1; j >= 0; j--)
  816. // {
  817. // var cell = rowGroup.GetCell(columGroup.ElementAt(j).StartIndex);
  818. // cell.SetCellValue(columGroup.ElementAt(j).Name);
  819. // cell.CellStyle = groupStyle;
  820. // sheet1.AddMergedRegion(new CellRangeAddress(2, 2, columGroup.ElementAt(j).StartIndex, columGroup.ElementAt(j).StartIndex + columGroup.ElementAt(j).Cols - 1));
  821. // }
  822. // currentRowIndex++;
  823. //}
  824. ////列头行索引
  825. //var columHeaderRowIndex = currentRowIndex;
  826. ////列头样式
  827. //var headerfont = hssworkbook.CreateFont();
  828. //headerfont.FontHeightInPoints = 12;
  829. //headerfont.Boldweight = (short)NPOI.SS.UserModel.FontBoldWeight.BOLD;
  830. //var headerstyle = hssworkbook.CreateCellStyle();
  831. //headerstyle.SetFont(headerfont);
  832. ////设置列头信息
  833. //var row2 = sheet1.CreateRow(columHeaderRowIndex);
  834. //for (var i = 0; i < cols; i++)
  835. //{
  836. // var cell = row2.CreateCell(i);
  837. // cell.Row.Height = 500;
  838. // cell.SetCellValue(setting.Colum.ElementAt(i).Name);
  839. // cell.CellStyle = headerstyle;
  840. //}
  841. ////输出数据
  842. //for (var i = 0; i < setting.Source.Count(); i++)
  843. //{
  844. // var model = setting.Source.ElementAt(i);
  845. // var rowTemp = sheet1.CreateRow(i + columHeaderRowIndex + 1);
  846. // Type modelType = model.GetType();
  847. // PropertyInfo[] properties = modelType.GetProperties();
  848. // var proDic = new Dictionary<string, PropertyInfo>();
  849. // foreach (var item in properties)
  850. // {
  851. // proDic.Add(item.Name, item);
  852. // }
  853. // for (var j = 0; j < setting.Colum.Count(); j++)
  854. // {
  855. // rowTemp.CreateCell(j).SetCellValueT(setting.Colum.ElementAt(j).ColumType, setting.Colum.ElementAt(j).Result == null ? setting.Colum.ElementAt(j).ResultByFieldName(model, setting.Colum.ElementAt(j).FieldName) : setting.Colum.ElementAt(j).Result(model));
  856. // }
  857. //}
  858. //HSSFFormulaEvaluator e = new HSSFFormulaEvaluator(hssworkbook);
  859. ////对设定并可行的列求和
  860. //var containSum = false;
  861. //foreach (var item in setting.Colum)
  862. //{
  863. // if (item.DoColumSum)
  864. // {
  865. // containSum = true;
  866. // break;
  867. // }
  868. //}
  869. //if (containSum)
  870. //{
  871. // var style = hssworkbook.CreateCellStyle();
  872. // var font = hssworkbook.CreateFont();
  873. // font.FontHeight = 15 * 15;
  874. // font.Boldweight = 6000;
  875. // font.Color = HSSFColor.BLUE.index;
  876. // style.SetFont(font);
  877. // //求和 SUM(A2:A12)
  878. // var letter = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  879. // var totalRow = sheet1.CreateRow(columHeaderRowIndex + 1 + setting.Source.Count());
  880. // var rowName = "A";
  881. // for (var x = 0; x < setting.Colum.Count(); x++)
  882. // {
  883. // rowName = x == 0 ? "A" : (x > 26 ? letter.ElementAt(x / 26).ToString() + letter.ElementAt(x % 26).ToString() : letter.ElementAt(x % 26).ToString());
  884. // if (setting.Colum.ElementAt(x).DoColumSum)
  885. // {
  886. // var tempCell = totalRow.CreateCell(x);
  887. // tempCell.CellFormula = "SUM(" + rowName + (columHeaderRowIndex + 2) + ":" + rowName + (columHeaderRowIndex + 1 + setting.Source.Count()) + ")";
  888. // tempCell.CellStyle = style;
  889. // tempCell = e.EvaluateInCell(tempCell);
  890. // }
  891. // else
  892. // {
  893. // var temp = totalRow.CreateCell(x);
  894. // temp.CellStyle = style;
  895. // if (x == 0) temp.SetCellValue("合计");
  896. // }
  897. // }
  898. //}
  899. ////表格样式
  900. //for (var i = 0; i < cols; i++)
  901. //{
  902. // if (setting.Colum.ElementAt(i).Width <= 0) continue;
  903. // sheet1.SetColumnWidth(i, setting.Colum.ElementAt(i).Width);
  904. //}
  905. ////写入响应流
  906. //MemoryStream filestream = new MemoryStream();
  907. //hssworkbook.Write(filestream);
  908. //System.Web.HttpContext.Current.Response.BinaryWrite(filestream.GetBuffer());
  909. //System.Web.HttpContext.Current.Response.End();
  910. }
  911. /// <summary>
  912. ///构建路径
  913. /// </summary>
  914. /// <param name="filePath"></param>
  915. /// <returns></returns>
  916. private static string BiuldPath(string filePath)
  917. {
  918. //return HttpContext.Current.Server.MapPath("~/Upload/" + filePath);
  919. return String.Empty;
  920. }
  921. /// <summary>
  922. /// 给单元格赋值,并设置数据类型
  923. /// </summary>
  924. /// <param name="cell"></param>
  925. /// <param name="type"></param>
  926. /// <param name="value"></param>
  927. private static void SetCellValueT(this NPOI.SS.UserModel.ICell cell, ExcelColumType type, object value)
  928. {
  929. if (value == null)
  930. return;
  931. if (type == ExcelColumType.Bool)
  932. cell.SetCellValue((bool)value);
  933. else if (type == ExcelColumType.DateTime)
  934. cell.SetCellValue((DateTime)value);
  935. else if (type == ExcelColumType.Double)
  936. {
  937. double number = 0;
  938. if (double.TryParse(value.ToString(), out number))
  939. cell.SetCellValue(number);
  940. else
  941. cell.SetCellValue(value.ToString());
  942. }
  943. else
  944. cell.SetCellValue(value.ToString());
  945. }
  946. }
  947. }