鄂尔多斯-招源科技

NPOIHelper.cs 30KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768
  1. 
  2. using System;
  3. using System.Data;
  4. using System.IO;
  5. using System.Text;
  6. using System.Web;
  7. using NPOI.HSSF.UserModel;
  8. using NPOI.SS.UserModel;
  9. using NPOI.SS.Util;
  10. using NPOI.XSSF.UserModel;
  11. using System.Collections.Generic;
  12. namespace CallCenter.Utility
  13. {
  14. public class NPOIHelper
  15. {
  16. private string _title;
  17. private string _sheetName;
  18. private string _filePath;
  19. /// <summary>
  20. /// 导出到Excel
  21. /// </summary>
  22. /// <param name="table"></param>
  23. /// <returns></returns>
  24. public bool ToExcel(DataTable table, string[] columns = null)
  25. {
  26. FileStream fs = new FileStream(this._filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
  27. IWorkbook workBook = new HSSFWorkbook();
  28. if (string.IsNullOrWhiteSpace(this._sheetName))
  29. {
  30. this._sheetName = "sheet1";
  31. }
  32. ISheet sheet = workBook.CreateSheet(this._sheetName);
  33. //处理表格标题
  34. IRow row = sheet.CreateRow(0);
  35. row.CreateCell(0).SetCellValue(this._title);
  36. sheet.AddMergedRegion(new CellRangeAddress(0, 0, 0, table.Columns.Count - 1));
  37. row.Height = 500;
  38. ICellStyle cellStyle = workBook.CreateCellStyle();
  39. IFont font = workBook.CreateFont();
  40. font.FontName = "微软雅黑";
  41. font.FontHeightInPoints = 17;
  42. cellStyle.SetFont(font);
  43. cellStyle.VerticalAlignment = VerticalAlignment.Center;
  44. cellStyle.Alignment = HorizontalAlignment.Center;
  45. row.Cells[0].CellStyle = cellStyle;
  46. //处理表格列头
  47. row = sheet.CreateRow(1);
  48. if (columns == null)
  49. {
  50. for (int i = 0; i < table.Columns.Count; i++)
  51. {
  52. row.CreateCell(i).SetCellValue(table.Columns[i].ColumnName);
  53. row.Height = 350;
  54. //sheet.AutoSizeColumn(i);
  55. }
  56. }
  57. else
  58. {
  59. for (int i = 0; i < columns.Length; i++)
  60. {
  61. row.CreateCell(i).SetCellValue(columns[i]);
  62. row.Height = 350;
  63. //sheet.AutoSizeColumn(i);
  64. }
  65. }
  66. //处理数据内容
  67. for (int i = 0; i < table.Rows.Count; i++)
  68. {
  69. row = sheet.CreateRow(2 + i);
  70. row.Height = 250;
  71. for (int j = 0; j < table.Columns.Count; j++)
  72. {
  73. row.CreateCell(j).SetCellValue(table.Rows[i][j].ToString());
  74. sheet.SetColumnWidth(j, 256 * 15);
  75. }
  76. }
  77. //写入数据流
  78. workBook.Write(fs);
  79. fs.Flush();
  80. fs.Close();
  81. return true;
  82. }
  83. /// <summary>
  84. /// 导出到Excel
  85. /// </summary>
  86. /// <param name="table"></param>
  87. /// <param name="title"></param>
  88. /// <param name="sheetName">空字符串或null的话默认sheet1</param>
  89. /// <param name="columns">自定义表格列头,默认null</param>
  90. /// <returns></returns>
  91. public bool ToExcel(DataTable table, string title, string sheetName, string filePath, string[] columns = null)
  92. {
  93. this._title = title;
  94. this._sheetName = sheetName;
  95. this._filePath = filePath;
  96. return ToExcel(table, columns);
  97. }
  98. /// <summary>
  99. /// 弹出下载框导出excel
  100. /// </summary>
  101. /// <param name="Name"></param>
  102. /// <param name="dt"></param>
  103. /// <returns></returns>
  104. public string ExportToExcel_old(string Name, DataTable dt, string[] cols = null)
  105. {
  106. try
  107. {
  108. HSSFWorkbook workbook = new HSSFWorkbook();
  109. ISheet sheet = workbook.CreateSheet("Sheet1");
  110. ICellStyle HeadercellStyle = workbook.CreateCellStyle();
  111. HeadercellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
  112. HeadercellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
  113. HeadercellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
  114. HeadercellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
  115. HeadercellStyle.Alignment = HorizontalAlignment.Center;
  116. HeadercellStyle.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.SkyBlue.Index;
  117. HeadercellStyle.FillPattern = FillPattern.SolidForeground;
  118. HeadercellStyle.FillBackgroundColor = NPOI.HSSF.Util.HSSFColor.SkyBlue.Index;
  119. //字体
  120. NPOI.SS.UserModel.IFont headerfont = workbook.CreateFont();
  121. headerfont.Boldweight = (short)FontBoldWeight.Bold;
  122. headerfont.FontHeightInPoints = 12;
  123. HeadercellStyle.SetFont(headerfont);
  124. //用column name 作为列名
  125. int icolIndex = 0;
  126. IRow headerRow = sheet.CreateRow(0);
  127. if (cols == null || (cols != null && cols.Length == 0))
  128. {
  129. foreach (DataColumn dc in dt.Columns)
  130. {
  131. ICell cell = headerRow.CreateCell(icolIndex);
  132. cell.SetCellValue(dc.ColumnName);
  133. cell.CellStyle = HeadercellStyle;
  134. icolIndex++;
  135. }
  136. }
  137. else
  138. {
  139. foreach (string dc in cols)
  140. {
  141. ICell cell = headerRow.CreateCell(icolIndex);
  142. cell.SetCellValue(dc);
  143. cell.CellStyle = HeadercellStyle;
  144. icolIndex++;
  145. }
  146. }
  147. ICellStyle cellStyle = workbook.CreateCellStyle();
  148. //为避免日期格式被Excel自动替换,所以设定 format 为 『@』 表示一率当成text來看
  149. cellStyle.DataFormat = HSSFDataFormat.GetBuiltinFormat("@");
  150. cellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
  151. cellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
  152. cellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
  153. cellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
  154. NPOI.SS.UserModel.IFont cellfont = workbook.CreateFont();
  155. cellfont.Boldweight = (short)FontBoldWeight.Normal;
  156. cellStyle.SetFont(cellfont);
  157. if (dt.Rows.Count > 0)
  158. {
  159. //建立内容行
  160. int iRowIndex = 0;
  161. foreach (DataRow dr in dt.Rows)
  162. {
  163. int iCellIndex = 0;
  164. IRow irow = sheet.CreateRow(iRowIndex + 1);
  165. for (int i = 0; i < dt.Columns.Count; i++)
  166. {
  167. string strsj = string.Empty;
  168. if (dr[i] != null)
  169. {
  170. strsj = dr[i].ToString();
  171. }
  172. ICell cell = irow.CreateCell(iCellIndex);
  173. cell.SetCellValue(strsj);
  174. cell.CellStyle = cellStyle;
  175. iCellIndex++;
  176. }
  177. iRowIndex++;
  178. }
  179. ////自适应列宽度
  180. //for (int i = 0; i < icolIndex; i++)
  181. //{
  182. // sheet.AutoSizeColumn(i);
  183. //}
  184. }
  185. using (MemoryStream ms = new MemoryStream())
  186. {
  187. workbook.Write(ms);
  188. HttpContext curContext = HttpContext.Current;
  189. // 设置编码和附件格式
  190. curContext.Response.ContentType = "application/vnd.ms-excel";
  191. curContext.Response.ContentEncoding = Encoding.UTF8;
  192. curContext.Response.Charset = "";
  193. curContext.Response.AppendHeader("Content-Disposition",
  194. "attachment;filename=" + HttpUtility.UrlEncode(Name + ".xls", Encoding.UTF8));
  195. curContext.Response.BinaryWrite(ms.GetBuffer());
  196. workbook = null;
  197. ms.Close();
  198. ms.Dispose();
  199. curContext.Response.End();
  200. }
  201. return "";
  202. }
  203. catch
  204. {
  205. return "导出失败!";
  206. }
  207. }
  208. /// <summary>
  209. /// 弹出下载框导出excel => 创建多个Sheet:例如sheet1,sheet2...
  210. /// </summary>
  211. /// <param name="Name"></param>
  212. /// <param name="dt"></param>
  213. /// <returns></returns>
  214. public string ExportToExcel(string Name, DataTable dt, string[] cols = null)
  215. {
  216. try
  217. {
  218. HSSFWorkbook workbook = new HSSFWorkbook();
  219. //ISheet sheet = workbook.CreateSheet("Sheet1");
  220. //数据总数
  221. int count = dt.Rows.Count;
  222. //注意:1、Excel2003及以前版本65536行,256列; 2、Excel2007、2010版本1048576行,16384列
  223. int sheetpage = 50000; //这里设置5w条
  224. //向上取整
  225. int sheetindexcount = int.Parse(Math.Ceiling(Convert.ToDecimal((double)count / sheetpage)).ToString());
  226. if (sheetindexcount == 0)
  227. sheetindexcount = 1;
  228. for (int n = 1; n <= sheetindexcount; n++)
  229. {
  230. ISheet sheet = workbook.CreateSheet("Sheet" + n);
  231. ICellStyle HeadercellStyle = workbook.CreateCellStyle();
  232. HeadercellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
  233. HeadercellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
  234. HeadercellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
  235. HeadercellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
  236. HeadercellStyle.Alignment = HorizontalAlignment.Center;
  237. HeadercellStyle.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.SkyBlue.Index;
  238. HeadercellStyle.FillPattern = FillPattern.SolidForeground;
  239. HeadercellStyle.FillBackgroundColor = NPOI.HSSF.Util.HSSFColor.SkyBlue.Index;
  240. //字体
  241. NPOI.SS.UserModel.IFont headerfont = workbook.CreateFont();
  242. headerfont.Boldweight = (short)FontBoldWeight.Bold;
  243. headerfont.FontHeightInPoints = 12;
  244. HeadercellStyle.SetFont(headerfont);
  245. //用column name 作为列名
  246. int icolIndex = 0;
  247. IRow headerRow = sheet.CreateRow(0);
  248. if (cols == null || (cols != null && cols.Length == 0))
  249. {
  250. foreach (DataColumn dc in dt.Columns)
  251. {
  252. ICell cell = headerRow.CreateCell(icolIndex);
  253. cell.SetCellValue(dc.ColumnName);
  254. cell.CellStyle = HeadercellStyle;
  255. icolIndex++;
  256. }
  257. }
  258. else
  259. {
  260. foreach (string dc in cols)
  261. {
  262. ICell cell = headerRow.CreateCell(icolIndex);
  263. cell.SetCellValue(dc);
  264. cell.CellStyle = HeadercellStyle;
  265. icolIndex++;
  266. }
  267. }
  268. ICellStyle cellStyle = workbook.CreateCellStyle();
  269. //为避免日期格式被Excel自动替换,所以设定 format 为 『@』 表示一率当成text來看
  270. cellStyle.DataFormat = HSSFDataFormat.GetBuiltinFormat("@");
  271. cellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
  272. cellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
  273. cellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
  274. cellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
  275. NPOI.SS.UserModel.IFont cellfont = workbook.CreateFont();
  276. cellfont.Boldweight = (short)FontBoldWeight.Normal;
  277. cellStyle.SetFont(cellfont);
  278. if (dt.Rows.Count > 0)
  279. {
  280. //建立内容行
  281. int iRowIndex = 0;
  282. #region 修改不用
  283. //foreach (DataRow dr in dt.Rows)
  284. //{
  285. // int iCellIndex = 0;
  286. // IRow irow = sheet.CreateRow(iRowIndex + 1);
  287. // for (int i = 0; i < dt.Columns.Count; i++)
  288. // {
  289. // string strsj = string.Empty;
  290. // if (dr[i] != null)
  291. // {
  292. // strsj = dr[i].ToString();
  293. // }
  294. // ICell cell = irow.CreateCell(iCellIndex);
  295. // cell.SetCellValue(strsj);
  296. // cell.CellStyle = cellStyle;
  297. // iCellIndex++;
  298. // }
  299. // iRowIndex++;
  300. //}
  301. #endregion
  302. int startcount = (n - 1) * sheetpage;
  303. int endcount = n * sheetpage;
  304. if (sheetindexcount == n)
  305. endcount = count;
  306. //for (int x = 0; x < dt.Rows.Count; x++)
  307. for (int x = startcount; x < endcount; x++)
  308. {
  309. int iCellIndex = 0;
  310. IRow irow = sheet.CreateRow(iRowIndex + 1);
  311. for (int i = 0; i < dt.Columns.Count; i++)
  312. {
  313. string strsj = string.Empty;
  314. if (dt.Rows[x][i] != null)
  315. {
  316. strsj = dt.Rows[x][i].ToString();
  317. }
  318. ICell cell = irow.CreateCell(iCellIndex);
  319. cell.SetCellValue(strsj);
  320. cell.CellStyle = cellStyle;
  321. iCellIndex++;
  322. }
  323. iRowIndex++;
  324. }
  325. ////自适应列宽度
  326. //for (int i = 0; i < icolIndex; i++)
  327. //{
  328. // sheet.AutoSizeColumn(i);
  329. //}
  330. }
  331. }
  332. using (MemoryStream ms = new MemoryStream())
  333. {
  334. workbook.Write(ms);
  335. HttpContext curContext = HttpContext.Current;
  336. // 设置编码和附件格式
  337. curContext.Response.ContentType = "application/vnd.ms-excel";
  338. curContext.Response.ContentEncoding = Encoding.UTF8;
  339. curContext.Response.Charset = "";
  340. curContext.Response.AppendHeader("Content-Disposition",
  341. "attachment;filename=" + HttpUtility.UrlEncode(Name + ".xls", Encoding.UTF8));
  342. curContext.Response.BinaryWrite(ms.GetBuffer());
  343. workbook = null;
  344. ms.Close();
  345. ms.Dispose();
  346. curContext.Response.End();
  347. }
  348. return "";
  349. }
  350. catch (Exception ex)
  351. {
  352. return "导出失败!" + ex.Message;
  353. }
  354. }
  355. /// <summary>
  356. /// 弹出下载框导出excel => 创建多个Sheet:例如sheet1,sheet2...【数据源为 List<List<string>> 】
  357. /// </summary>
  358. /// <param name="Name"></param>
  359. /// <param name="list"></param>
  360. /// <returns></returns>
  361. public string ExportToExcel(string Name, List<List<string>> list, string[] cols = null)
  362. {
  363. try
  364. {
  365. HSSFWorkbook workbook = new HSSFWorkbook();
  366. //ISheet sheet = workbook.CreateSheet("Sheet1");
  367. //数据总数
  368. int count = list.Count;
  369. //注意:1、Excel2003及以前版本65536行,256列; 2、Excel2007、2010版本1048576行,16384列
  370. int sheetpage = 50000; //这里设置5w条
  371. //向上取整
  372. int sheetindexcount = int.Parse(Math.Ceiling(Convert.ToDecimal((double)count / sheetpage)).ToString());
  373. if (sheetindexcount == 0)
  374. sheetindexcount = 1;
  375. for (int n = 1; n <= sheetindexcount; n++)
  376. {
  377. ISheet sheet = workbook.CreateSheet("Sheet" + n);
  378. ICellStyle HeadercellStyle = workbook.CreateCellStyle();
  379. HeadercellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
  380. HeadercellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
  381. HeadercellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
  382. HeadercellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
  383. HeadercellStyle.Alignment = HorizontalAlignment.Center;
  384. HeadercellStyle.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.SkyBlue.Index;
  385. HeadercellStyle.FillPattern = FillPattern.SolidForeground;
  386. HeadercellStyle.FillBackgroundColor = NPOI.HSSF.Util.HSSFColor.SkyBlue.Index;
  387. //字体
  388. NPOI.SS.UserModel.IFont headerfont = workbook.CreateFont();
  389. headerfont.Boldweight = (short)FontBoldWeight.Bold;
  390. headerfont.FontHeightInPoints = 12;
  391. HeadercellStyle.SetFont(headerfont);
  392. //用column name 作为列名
  393. int icolIndex = 0;
  394. IRow headerRow = sheet.CreateRow(0);
  395. foreach (string dc in cols)
  396. {
  397. ICell cell = headerRow.CreateCell(icolIndex);
  398. cell.SetCellValue(dc);
  399. cell.CellStyle = HeadercellStyle;
  400. icolIndex++;
  401. }
  402. ICellStyle cellStyle = workbook.CreateCellStyle();
  403. //为避免日期格式被Excel自动替换,所以设定 format 为 『@』 表示一率当成text來看
  404. cellStyle.DataFormat = HSSFDataFormat.GetBuiltinFormat("@");
  405. cellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
  406. cellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
  407. cellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
  408. cellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
  409. NPOI.SS.UserModel.IFont cellfont = workbook.CreateFont();
  410. cellfont.Boldweight = (short)FontBoldWeight.Normal;
  411. cellStyle.SetFont(cellfont);
  412. if (list.Count > 0)
  413. {
  414. //建立内容行
  415. int iRowIndex = 0;
  416. #region 修改不用
  417. //foreach (DataRow dr in dt.Rows)
  418. //{
  419. // int iCellIndex = 0;
  420. // IRow irow = sheet.CreateRow(iRowIndex + 1);
  421. // for (int i = 0; i < dt.Columns.Count; i++)
  422. // {
  423. // string strsj = string.Empty;
  424. // if (dr[i] != null)
  425. // {
  426. // strsj = dr[i].ToString();
  427. // }
  428. // ICell cell = irow.CreateCell(iCellIndex);
  429. // cell.SetCellValue(strsj);
  430. // cell.CellStyle = cellStyle;
  431. // iCellIndex++;
  432. // }
  433. // iRowIndex++;
  434. //}
  435. #endregion
  436. int startcount = (n - 1) * sheetpage;
  437. int endcount = n * sheetpage;
  438. if (sheetindexcount == n)
  439. endcount = count;
  440. //for (int x = 0; x < dt.Rows.Count; x++)
  441. for (int x = startcount; x < endcount; x++)
  442. {
  443. int iCellIndex = 0;
  444. IRow irow = sheet.CreateRow(iRowIndex + 1);
  445. for (int i = 0; i < list[iRowIndex].Count; i++)
  446. {
  447. string strsj = string.Empty;
  448. strsj = list[iRowIndex][i];
  449. ICell cell = irow.CreateCell(iCellIndex);
  450. cell.SetCellValue(strsj);
  451. cell.CellStyle = cellStyle;
  452. iCellIndex++;
  453. }
  454. iRowIndex++;
  455. }
  456. ////自适应列宽度
  457. //for (int i = 0; i < icolIndex; i++)
  458. //{
  459. // sheet.AutoSizeColumn(i);
  460. //}
  461. }
  462. }
  463. using (MemoryStream ms = new MemoryStream())
  464. {
  465. workbook.Write(ms);
  466. HttpContext curContext = HttpContext.Current;
  467. // 设置编码和附件格式
  468. curContext.Response.ContentType = "application/vnd.ms-excel";
  469. curContext.Response.ContentEncoding = Encoding.UTF8;
  470. curContext.Response.Charset = "";
  471. curContext.Response.AppendHeader("Content-Disposition",
  472. "attachment;filename=" + HttpUtility.UrlEncode(Name + ".xls", Encoding.UTF8));
  473. curContext.Response.BinaryWrite(ms.GetBuffer());
  474. workbook = null;
  475. ms.Close();
  476. ms.Dispose();
  477. curContext.Response.End();
  478. }
  479. return "";
  480. }
  481. catch (Exception ex)
  482. {
  483. return "导出失败!" + ex.Message;
  484. }
  485. }
  486. /// <summary>
  487. /// 创建Sheet
  488. /// </summary>
  489. /// <param name="workBook"></param>
  490. /// <param name="sheetName"></param>
  491. /// <returns></returns>
  492. public ISheet CreateSheet(HSSFWorkbook workBook, string sheetName)
  493. {
  494. ISheet sheet = workBook.CreateSheet(sheetName);
  495. IRow RowHead = sheet.CreateRow(0);
  496. for (int iColumnIndex = 0; iColumnIndex < 10; iColumnIndex++)
  497. {
  498. RowHead.CreateCell(iColumnIndex).SetCellValue(Guid.NewGuid().ToString());
  499. }
  500. for (int iRowIndex = 0; iRowIndex < 20; iRowIndex++)
  501. {
  502. IRow RowBody = sheet.CreateRow(iRowIndex + 1);
  503. for (int iColumnIndex = 0; iColumnIndex < 10; iColumnIndex++)
  504. {
  505. RowBody.CreateCell(iColumnIndex).SetCellValue(DateTime.Now.Millisecond);
  506. //sheet.AutoSizeColumn(iColumnIndex);
  507. }
  508. }
  509. return sheet;
  510. }
  511. /// <summary>
  512. /// 导入excel转换为datatable
  513. /// </summary>
  514. /// <param name="upfile"></param>
  515. /// <param name="headrow"></param>
  516. /// <returns></returns>
  517. public DataTable ExcelToTable(HttpPostedFile upfile, int headrow)
  518. {
  519. DataTable dt = new DataTable();
  520. IWorkbook workbook = null;
  521. Stream stream = upfile.InputStream;
  522. string suffix = upfile.FileName.Substring(upfile.FileName.LastIndexOf(".") + 1).ToLower();
  523. if (suffix == "xlsx") // 2007版本
  524. {
  525. workbook = new XSSFWorkbook(stream);
  526. }
  527. else if (suffix == "xls") // 2003版本
  528. {
  529. workbook = new HSSFWorkbook(stream);
  530. }
  531. //获取excel的第一个sheet
  532. ISheet sheet = workbook.GetSheetAt(0);
  533. //获取sheet的第一行
  534. IRow headerRow = sheet.GetRow(headrow);
  535. //一行最后一个方格的编号 即总的列数
  536. int cellCount = headerRow.LastCellNum;
  537. //最后一列的标号 即总的行数
  538. int rowCount = sheet.LastRowNum;
  539. //列名
  540. for (int i = 0; i < cellCount; i++)
  541. {
  542. dt.Columns.Add(headerRow.GetCell(i).ToString());
  543. }
  544. for (int i = (sheet.FirstRowNum + headrow); i <= sheet.LastRowNum; i++)
  545. {
  546. DataRow dr = dt.NewRow();
  547. IRow row = sheet.GetRow(i);
  548. for (int j = row.FirstCellNum; j < cellCount; j++)
  549. {
  550. if (row.GetCell(j) != null)
  551. {
  552. dr[j] = row.GetCell(j).ToString();
  553. }
  554. }
  555. dt.Rows.Add(dr);
  556. }
  557. sheet = null;
  558. workbook = null;
  559. return dt;
  560. }
  561. /// <summary>
  562. /// 上传excel文件,并且读取excel文件转换为datatable, HttpPostedFileBase
  563. /// </summary>
  564. /// <param name="upfile"></param>
  565. /// <param name="headrow"></param>
  566. /// <returns></returns>
  567. public DataTable ExcelToTable(HttpPostedFileBase upfile, int headrow, out string filePath)
  568. {
  569. var ext = upfile.FileName.Substring(upfile.FileName.LastIndexOf(".") + 1).ToLower();
  570. var foldPath = $"{HttpContext.Current.Request.ApplicationPath}\\ExcelData\\{ DateTime.Now.ToString("yyyyMM")}";
  571. var server = HttpContext.Current.Server;
  572. if (!Directory.Exists(server.MapPath(foldPath)))
  573. {
  574. Directory.CreateDirectory(server.MapPath(foldPath));
  575. }
  576. filePath = server.MapPath($"{foldPath}\\") + Guid.NewGuid().ToString("N") + "." + ext;
  577. upfile.SaveAs(filePath);
  578. DataTable dt = new DataTable();
  579. IWorkbook workbook = null;
  580. Stream stream = upfile.InputStream;
  581. string suffix = ext;
  582. if (suffix == "xlsx") // 2007版本
  583. {
  584. workbook = new XSSFWorkbook(stream);
  585. }
  586. else if (suffix == "xls") // 2003版本
  587. {
  588. workbook = new HSSFWorkbook(stream);
  589. }
  590. //获取excel的第一个sheet
  591. ISheet sheet = workbook.GetSheetAt(0);
  592. //获取sheet的第一行
  593. IRow headerRow = sheet.GetRow(headrow);
  594. //一行最后一个方格的编号 即总的列数
  595. int cellCount = headerRow.LastCellNum;
  596. //最后一列的标号 即总的行数
  597. int rowCount = sheet.LastRowNum;
  598. //列名
  599. for (int i = 0; i < cellCount; i++)
  600. {
  601. dt.Columns.Add(headerRow.GetCell(i).ToString());
  602. }
  603. for (int i = (sheet.FirstRowNum + headrow + 1); i <= sheet.LastRowNum; i++)
  604. {
  605. DataRow dr = dt.NewRow();
  606. IRow row = sheet.GetRow(i);
  607. for (int j = row.FirstCellNum; j < cellCount; j++)
  608. {
  609. if (row.GetCell(j) != null)
  610. {
  611. dr[j] = row.GetCell(j).ToString();
  612. }
  613. }
  614. dt.Rows.Add(dr);
  615. }
  616. sheet = null;
  617. workbook = null;
  618. return dt;
  619. }
  620. /// <summary>
  621. /// 导入excel转换为datatable
  622. /// </summary>
  623. /// <param name="upfile"></param>
  624. /// <param name="headrow"></param>
  625. /// <returns></returns>
  626. public DataTable ExcelToTable(string fileName, int headrow)
  627. {
  628. DataTable dt = new DataTable();
  629. IWorkbook workbook = null;
  630. Stream stream = new FileStream(fileName, FileMode.OpenOrCreate);
  631. string suffix = fileName.Substring(fileName.LastIndexOf(".") + 1).ToLower();
  632. if (suffix == "xlsx") // 2007版本
  633. {
  634. workbook = new XSSFWorkbook(stream);
  635. }
  636. else if (suffix == "xls") // 2003版本
  637. {
  638. workbook = new HSSFWorkbook(stream);
  639. }
  640. //获取excel的第一个sheet
  641. ISheet sheet = workbook.GetSheetAt(0);
  642. //获取sheet的第一行
  643. IRow headerRow = sheet.GetRow(headrow);
  644. //一行最后一个方格的编号 即总的列数
  645. int cellCount = headerRow.LastCellNum;
  646. //最后一列的标号 即总的行数
  647. int rowCount = sheet.LastRowNum;
  648. //列名
  649. for (int i = 0; i < cellCount; i++)
  650. {
  651. dt.Columns.Add(headerRow.GetCell(i).ToString());
  652. }
  653. for (int i = (sheet.FirstRowNum + headrow + 1); i <= sheet.LastRowNum; i++)
  654. {
  655. DataRow dr = dt.NewRow();
  656. IRow row = sheet.GetRow(i);
  657. for (int j = row.FirstCellNum; j < cellCount; j++)
  658. {
  659. if (row.GetCell(j) != null)
  660. {
  661. dr[j] = row.GetCell(j).ToString();
  662. }
  663. }
  664. dt.Rows.Add(dr);
  665. }
  666. sheet = null;
  667. workbook = null;
  668. return dt;
  669. }
  670. }
  671. }