説明なし

NPOIHelper.cs 33KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838
  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 NPOI.HSSF.Util;
  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 ExportToExcelSplitSheet(string Name, DataTable dt, string[] cols = null)
  105. {
  106. //try
  107. //{
  108. //if (dt.Rows.Count > 0)
  109. //{
  110. HSSFWorkbook workbook = new HSSFWorkbook();//导出xls
  111. //IWorkbook workbook = new XSSFWorkbook();//导出xlsx
  112. int SheetNum = 1;
  113. ISheet sheet = workbook.CreateSheet("Sheet"+ SheetNum);
  114. ICellStyle HeadercellStyle = workbook.CreateCellStyle();
  115. HeadercellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
  116. HeadercellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
  117. HeadercellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
  118. HeadercellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
  119. HeadercellStyle.Alignment = HorizontalAlignment.Center;
  120. HeadercellStyle.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.SkyBlue.Index;
  121. HeadercellStyle.FillPattern = FillPattern.SolidForeground;
  122. HeadercellStyle.FillBackgroundColor = NPOI.HSSF.Util.HSSFColor.SkyBlue.Index;
  123. //字体
  124. NPOI.SS.UserModel.IFont headerfont = workbook.CreateFont();
  125. headerfont.Boldweight = (short)FontBoldWeight.Bold;
  126. headerfont.FontHeightInPoints = 12;
  127. HeadercellStyle.SetFont(headerfont);
  128. //用column name 作为列名
  129. int icolIndex = 0;
  130. IRow headerRow = sheet.CreateRow(0);
  131. if (cols == null || (cols != null && cols.Length == 0))
  132. {
  133. foreach (DataColumn dc in dt.Columns)
  134. {
  135. ICell cell = headerRow.CreateCell(icolIndex);
  136. cell.SetCellValue(dc.ColumnName);
  137. cell.CellStyle = HeadercellStyle;
  138. icolIndex++;
  139. }
  140. }
  141. else
  142. {
  143. foreach (string dc in cols)
  144. {
  145. ICell cell = headerRow.CreateCell(icolIndex);
  146. cell.SetCellValue(dc);
  147. cell.CellStyle = HeadercellStyle;
  148. icolIndex++;
  149. }
  150. }
  151. ICellStyle cellStyle = workbook.CreateCellStyle();
  152. //为避免日期格式被Excel自动替换,所以设定 format 为 『@』 表示一率当成text來看
  153. cellStyle.DataFormat = HSSFDataFormat.GetBuiltinFormat("@");
  154. cellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
  155. cellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
  156. cellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
  157. cellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
  158. NPOI.SS.UserModel.IFont cellfont = workbook.CreateFont();
  159. cellfont.Boldweight = (short)FontBoldWeight.Normal;
  160. cellStyle.SetFont(cellfont);
  161. //建立内容行
  162. int iRowIndex = 0;
  163. int iRowIndex2 = 0;
  164. foreach (DataRow dr in dt.Rows)
  165. {
  166. int iCellIndex = 0;
  167. IRow irow = sheet.CreateRow(iRowIndex + 1);
  168. if (iRowIndex < 60000)
  169. {
  170. for (int i = 0; i < dt.Columns.Count; i++)
  171. {
  172. string strsj = string.Empty;
  173. if (dr[i] != null)
  174. {
  175. strsj = dr[i].ToString();
  176. }
  177. ICell cell = irow.CreateCell(iCellIndex);
  178. cell.SetCellValue(strsj);
  179. cell.CellStyle = cellStyle;
  180. iCellIndex++;
  181. }
  182. iRowIndex++;
  183. }
  184. int iCellIndex2 = 0;
  185. SheetNum = SheetNum + 1;
  186. ISheet sheet2=workbook.CreateSheet("Sheet" + SheetNum );
  187. if (iRowIndex >= 60000)
  188. {
  189. if (iRowIndex == 60000)
  190. {
  191. int icolIndex2 = 0;
  192. foreach (string dc in cols)
  193. {
  194. ICell cell = headerRow.CreateCell(icolIndex2);
  195. cell.SetCellValue(dc);
  196. cell.CellStyle = HeadercellStyle;
  197. icolIndex2++;
  198. }
  199. }
  200. IRow irow2 = sheet2.CreateRow (iRowIndex2 + 1);
  201. for (int i = 0; i < dt.Columns.Count; i++)
  202. {
  203. string strsj = string.Empty;
  204. if (dr[i] != null)
  205. {
  206. strsj = dr[i].ToString();
  207. }
  208. ICell cell = irow.CreateCell(iCellIndex2);
  209. cell.SetCellValue(strsj);
  210. cell.CellStyle = cellStyle;
  211. iCellIndex2++;
  212. }
  213. iRowIndex++;
  214. iRowIndex2++;
  215. }
  216. }
  217. using (MemoryStream ms = new MemoryStream())
  218. {
  219. workbook.Write(ms);
  220. HttpContext curContext = HttpContext.Current;
  221. // 设置编码和附件格式
  222. curContext.Response.ContentType = "application/vnd.ms-excel";
  223. curContext.Response.ContentEncoding = Encoding.UTF8 ;//Encoding.UTF8;
  224. curContext.Response.Charset = "";
  225. curContext.Response.AppendHeader("Content-Disposition",
  226. "attachment;filename=" + HttpUtility.UrlEncode(Name + ".xls", Encoding.UTF8));
  227. curContext.Response.BinaryWrite(ms.GetBuffer());
  228. workbook = null;
  229. ms.Close();
  230. ms.Dispose();
  231. curContext.Response.End();
  232. }
  233. return "";
  234. //}
  235. //catch(Exception e)
  236. //{
  237. // string estr = e.Message;
  238. // return "导出失败!";
  239. //}
  240. }
  241. public string ExportToExcel(string Name, DataTable dt, string[] cols = null)
  242. {
  243. try
  244. {
  245. //if (dt.Rows.Count > 0)
  246. //{
  247. HSSFWorkbook workbook = new HSSFWorkbook();//导出xls
  248. //IWorkbook workbook = new XSSFWorkbook();//导出xlsx
  249. ISheet sheet = workbook.CreateSheet("Sheet1");
  250. ICellStyle HeadercellStyle = workbook.CreateCellStyle();
  251. HeadercellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
  252. HeadercellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
  253. HeadercellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
  254. HeadercellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
  255. HeadercellStyle.Alignment = HorizontalAlignment.Center;
  256. HeadercellStyle.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.SkyBlue.Index;
  257. HeadercellStyle.FillPattern = FillPattern.SolidForeground;
  258. HeadercellStyle.FillBackgroundColor = NPOI.HSSF.Util.HSSFColor.SkyBlue.Index;
  259. //字体
  260. NPOI.SS.UserModel.IFont headerfont = workbook.CreateFont();
  261. headerfont.Boldweight = (short)FontBoldWeight.Bold;
  262. headerfont.FontHeightInPoints = 12;
  263. HeadercellStyle.SetFont(headerfont);
  264. //用column name 作为列名
  265. int icolIndex = 0;
  266. IRow headerRow = sheet.CreateRow(0);
  267. if (cols == null || (cols != null && cols.Length == 0))
  268. {
  269. foreach (DataColumn dc in dt.Columns)
  270. {
  271. ICell cell = headerRow.CreateCell(icolIndex);
  272. cell.SetCellValue(dc.ColumnName);
  273. cell.CellStyle = HeadercellStyle;
  274. icolIndex++;
  275. }
  276. }
  277. else
  278. {
  279. foreach (string dc in cols)
  280. {
  281. ICell cell = headerRow.CreateCell(icolIndex);
  282. cell.SetCellValue(dc);
  283. cell.CellStyle = HeadercellStyle;
  284. icolIndex++;
  285. }
  286. }
  287. ICellStyle cellStyle = workbook.CreateCellStyle();
  288. //为避免日期格式被Excel自动替换,所以设定 format 为 『@』 表示一率当成text來看
  289. cellStyle.DataFormat = HSSFDataFormat.GetBuiltinFormat("@");
  290. cellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
  291. cellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
  292. cellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
  293. cellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
  294. NPOI.SS.UserModel.IFont cellfont = workbook.CreateFont();
  295. cellfont.Boldweight = (short)FontBoldWeight.Normal;
  296. cellStyle.SetFont(cellfont);
  297. //建立内容行
  298. int iRowIndex = 0;
  299. foreach (DataRow dr in dt.Rows)
  300. {
  301. int iCellIndex = 0;
  302. IRow irow = sheet.CreateRow(iRowIndex + 1);
  303. for (int i = 0; i < dt.Columns.Count; i++)
  304. {
  305. string strsj = string.Empty;
  306. if (dr[i] != null)
  307. {
  308. strsj = dr[i].ToString();
  309. }
  310. ICell cell = irow.CreateCell(iCellIndex);
  311. cell.SetCellValue(strsj);
  312. cell.CellStyle = cellStyle;
  313. iCellIndex++;
  314. }
  315. iRowIndex++;
  316. }
  317. ////自适应列宽度
  318. //for (int i = 0; i < icolIndex; i++)
  319. //{
  320. // sheet.AutoSizeColumn(i);
  321. //}
  322. using (MemoryStream ms = new MemoryStream())
  323. {
  324. workbook.Write(ms);
  325. HttpContext curContext = HttpContext.Current;
  326. // 设置编码和附件格式
  327. curContext.Response.ContentType = "application/vnd.ms-excel";
  328. curContext.Response.ContentEncoding = Encoding.UTF8;//Encoding.UTF8;
  329. curContext.Response.Charset = "";
  330. curContext.Response.AppendHeader("Content-Disposition",
  331. "attachment;filename=" + HttpUtility.UrlEncode(Name + ".xls", Encoding.UTF8));
  332. curContext.Response.BinaryWrite(ms.GetBuffer());
  333. workbook = null;
  334. ms.Close();
  335. ms.Dispose();
  336. curContext.Response.End();
  337. }
  338. //}
  339. return "";
  340. }
  341. catch
  342. {
  343. return "导出失败!";
  344. }
  345. }
  346. /// <summary>
  347. /// 导入excel转换为datatable
  348. /// </summary>
  349. /// <param name="upfile"></param>
  350. /// <param name="headrow"></param>
  351. /// <returns></returns>
  352. public DataTable ExcelToTable(HttpPostedFile upfile, int headrow)
  353. {
  354. DataTable dt = new DataTable();
  355. IWorkbook workbook = null;
  356. Stream stream = upfile.InputStream;
  357. string suffix = upfile.FileName.Substring(upfile.FileName.LastIndexOf(".") + 1).ToLower();
  358. if (suffix == "xlsx") // 2007版本
  359. {
  360. workbook = new XSSFWorkbook(stream);
  361. }
  362. else if (suffix == "xls") // 2003版本
  363. {
  364. workbook = new HSSFWorkbook(stream);
  365. }
  366. //获取excel的第一个sheet
  367. ISheet sheet = workbook.GetSheetAt(0);
  368. //获取sheet的第一行
  369. IRow headerRow = sheet.GetRow(headrow);
  370. //一行最后一个方格的编号 即总的列数
  371. int cellCount = headerRow.LastCellNum;
  372. //最后一列的标号 即总的行数
  373. int rowCount = sheet.LastRowNum;
  374. //列名
  375. for (int i = 0; i < cellCount; i++)
  376. {
  377. dt.Columns.Add(headerRow.GetCell(i).ToString());
  378. }
  379. for (int i = (sheet.FirstRowNum + headrow); i <= sheet.LastRowNum; i++)
  380. {
  381. DataRow dr = dt.NewRow();
  382. IRow row = sheet.GetRow(i);
  383. for (int j = row.FirstCellNum; j < cellCount; j++)
  384. {
  385. if (row.GetCell(j) != null)
  386. {
  387. dr[j] = row.GetCell(j).ToString();
  388. }
  389. }
  390. dt.Rows.Add(dr);
  391. }
  392. sheet = null;
  393. workbook = null;
  394. return dt;
  395. }
  396. /// <summary>
  397. /// 导入excel转换为datatable
  398. /// </summary>
  399. /// <param name="upfile"></param>
  400. /// <param name="headrow"></param>
  401. /// <returns></returns>
  402. public DataTable ExcelToTable(string fileName, int headrow)
  403. {
  404. DataTable dt = new DataTable();
  405. IWorkbook workbook = null;
  406. Stream stream = new FileStream(fileName, FileMode.OpenOrCreate);
  407. string suffix = fileName.Substring(fileName.LastIndexOf(".") + 1).ToLower();
  408. if (suffix == "xlsx") // 2007版本
  409. {
  410. workbook = new XSSFWorkbook(stream);
  411. }
  412. else if (suffix == "xls") // 2003版本
  413. {
  414. workbook = new HSSFWorkbook(stream);
  415. }
  416. //获取excel的第一个sheet
  417. ISheet sheet = workbook.GetSheetAt(0);
  418. //获取sheet的第一行
  419. IRow headerRow = sheet.GetRow(headrow);
  420. //一行最后一个方格的编号 即总的列数
  421. int cellCount = headerRow.LastCellNum;
  422. //最后一列的标号 即总的行数
  423. int rowCount = sheet.LastRowNum;
  424. //列名
  425. for (int i = 0; i < cellCount; i++)
  426. {
  427. dt.Columns.Add(headerRow.GetCell(i).ToString());
  428. }
  429. for (int i = (sheet.FirstRowNum + headrow + 1); i <= sheet.LastRowNum; i++)
  430. {
  431. DataRow dr = dt.NewRow();
  432. IRow row = sheet.GetRow(i);
  433. for (int j = row.FirstCellNum; j < cellCount; j++)
  434. {
  435. if (row.GetCell(j) != null)
  436. {
  437. dr[j] = row.GetCell(j).ToString();
  438. }
  439. }
  440. dt.Rows.Add(dr);
  441. }
  442. sheet = null;
  443. workbook = null;
  444. return dt;
  445. }
  446. //2017-11-11数据第一行为标题
  447. #region
  448. /// <summary>
  449. /// 弹出下载框导出excel(数据第一行为标题)
  450. /// </summary>
  451. /// <param name="Name"></param>
  452. /// <param name="dt"></param>
  453. /// <returns></returns>
  454. public string ExportToExcel2(string Name, DataTable dt, string[] cols = null)
  455. {
  456. try
  457. {
  458. //if (dt.Rows.Count > 0)
  459. //{
  460. HSSFWorkbook workbook = new HSSFWorkbook();
  461. ISheet sheet = workbook.CreateSheet("Sheet1");
  462. ICellStyle HeadercellStyle = workbook.CreateCellStyle();
  463. HeadercellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
  464. HeadercellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
  465. HeadercellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
  466. HeadercellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
  467. HeadercellStyle.Alignment = HorizontalAlignment.Center;
  468. HeadercellStyle.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.SkyBlue.Index;
  469. HeadercellStyle.FillPattern = FillPattern.SolidForeground;
  470. HeadercellStyle.FillBackgroundColor = NPOI.HSSF.Util.HSSFColor.SkyBlue.Index;
  471. //字体
  472. NPOI.SS.UserModel.IFont headerfont = workbook.CreateFont();
  473. headerfont.Boldweight = (short)FontBoldWeight.Bold;
  474. headerfont.FontHeightInPoints = 12;
  475. HeadercellStyle.SetFont(headerfont);
  476. //第一行为标题
  477. IRow headRow = sheet.CreateRow(0);
  478. ICell cellh = headRow.CreateCell(0);
  479. cellh.CellStyle = HeadercellStyle;
  480. cellh.SetCellValue(Name );
  481. sheet.AddMergedRegion(new CellRangeAddress(0, 0, 0, dt.Columns .Count-1));
  482. //用column name 作为列名
  483. int icolIndex = 0;
  484. IRow headerRow = sheet.CreateRow(1);
  485. if (cols == null || (cols != null && cols.Length == 0))
  486. {
  487. //foreach (DataColumn dc in dt.Columns)
  488. //{
  489. // ICell cell = headerRow.CreateCell(icolIndex);
  490. // cell.SetCellValue(dc.ColumnName);
  491. // cell.CellStyle = HeadercellStyle;
  492. // icolIndex++;
  493. //}
  494. for (int i = 0; i < dt.Columns.Count; i++)
  495. {
  496. ICell cell = headerRow.CreateCell(icolIndex);
  497. cell.SetCellValue(dt.Columns[i].ColumnName);//cell.SetCellValue(dt.Rows [0][i].ToString());
  498. cell.CellStyle = HeadercellStyle;
  499. icolIndex++;
  500. }
  501. }
  502. else
  503. {
  504. foreach (string dc in cols)
  505. {
  506. ICell cell = headerRow.CreateCell(icolIndex);
  507. cell.SetCellValue(dc);
  508. cell.CellStyle = HeadercellStyle;
  509. icolIndex++;
  510. }
  511. }
  512. ICellStyle cellStyle = workbook.CreateCellStyle();
  513. //为避免日期格式被Excel自动替换,所以设定 format 为 『@』 表示一率当成text來看
  514. cellStyle.DataFormat = HSSFDataFormat.GetBuiltinFormat("@");
  515. cellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
  516. cellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
  517. cellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
  518. cellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
  519. NPOI.SS.UserModel.IFont cellfont = workbook.CreateFont();
  520. cellfont.Boldweight = (short)FontBoldWeight.Normal;
  521. cellStyle.SetFont(cellfont);
  522. //建立内容行
  523. int iRowIndex = 2;
  524. foreach (DataRow dr in dt.Rows)
  525. {
  526. if (iRowIndex >= 2)
  527. {
  528. int iCellIndex = 0;
  529. IRow irow = sheet.CreateRow(iRowIndex );
  530. for (int i = 0; i < dt.Columns.Count; i++)
  531. {
  532. string strsj = string.Empty;
  533. if (dr[i] != null)
  534. {
  535. strsj = dr[i].ToString();
  536. }
  537. ICell cell = irow.CreateCell(iCellIndex);
  538. cell.SetCellValue(strsj);
  539. cell.CellStyle = cellStyle;
  540. iCellIndex++;
  541. }
  542. }
  543. iRowIndex++;
  544. }
  545. //自适应列宽度
  546. for (int i = 0; i < icolIndex; i++)
  547. {
  548. sheet.AutoSizeColumn(i);
  549. // 解决自动设置列宽中文失效的问题
  550. sheet.SetColumnWidth(i, sheet.GetColumnWidth(i) * 17 / 10);
  551. }
  552. using (MemoryStream ms = new MemoryStream())
  553. {
  554. workbook.Write(ms);
  555. HttpContext curContext = HttpContext.Current;
  556. // 设置编码和附件格式
  557. curContext.Response.ContentType = "application/vnd.ms-excel";
  558. curContext.Response.ContentEncoding = Encoding.UTF8;
  559. curContext.Response.Charset = "";
  560. curContext.Response.AppendHeader("Content-Disposition",
  561. "attachment;filename=" + HttpUtility.UrlEncode(Name + ".xls", Encoding.UTF8));
  562. curContext.Response.BinaryWrite(ms.GetBuffer());
  563. workbook = null;
  564. ms.Close();
  565. ms.Dispose();
  566. curContext.Response.End();
  567. }
  568. //}
  569. return "";
  570. }
  571. catch
  572. {
  573. return "导出失败!";
  574. }
  575. }
  576. #endregion
  577. public string ExportToExcel2003(string Name, DataTable dt, string[] cols = null)
  578. {
  579. try
  580. {
  581. HSSFWorkbook workbook = new HSSFWorkbook();
  582. ICellStyle HeadercellStyle = workbook.CreateCellStyle();
  583. HeadercellStyle.BorderBottom = BorderStyle.Thin;
  584. HeadercellStyle.BorderLeft = BorderStyle.Thin;
  585. HeadercellStyle.BorderRight = BorderStyle.Thin;
  586. HeadercellStyle.BorderTop = BorderStyle.Thin;
  587. HeadercellStyle.Alignment = HorizontalAlignment.Center;
  588. HeadercellStyle.FillForegroundColor = HSSFColor.SkyBlue.Index;
  589. HeadercellStyle.FillPattern = FillPattern.SolidForeground;
  590. HeadercellStyle.FillBackgroundColor = HSSFColor.SkyBlue.Index;
  591. //字体
  592. IFont headerfont = workbook.CreateFont();
  593. headerfont.Boldweight = (short)FontBoldWeight.Bold;
  594. headerfont.FontHeightInPoints = 12;
  595. HeadercellStyle.SetFont(headerfont);
  596. //用column name 作为列名
  597. int icolIndex = 0;
  598. //建立内容行
  599. int iRowIndex = 0;
  600. int sheetCount = 0;
  601. int sheetRowCount = 60000;
  602. ISheet sheet = null;
  603. IRow headerRow = null;
  604. if (dt.Rows.Count == 0)
  605. {
  606. sheet = workbook.CreateSheet(Name);
  607. headerRow = sheet.CreateRow(0);
  608. #region 表头
  609. if (cols == null || (cols != null && cols.Length == 0))
  610. {
  611. foreach (DataColumn dc in dt.Columns)
  612. {
  613. ICell cell = headerRow.CreateCell(icolIndex);
  614. cell.SetCellValue(dc.ColumnName);
  615. cell.CellStyle = HeadercellStyle;
  616. icolIndex++;
  617. }
  618. }
  619. else
  620. {
  621. foreach (string dc in cols)
  622. {
  623. ICell cell = headerRow.CreateCell(icolIndex);
  624. cell.SetCellValue(dc);
  625. cell.CellStyle = HeadercellStyle;
  626. icolIndex++;
  627. }
  628. }
  629. #endregion
  630. }
  631. else
  632. {
  633. ICellStyle cellStyle = workbook.CreateCellStyle();
  634. //为避免日期格式被Excel自动替换,所以设定 format 为 『@』 表示一率当成text來看
  635. cellStyle.DataFormat = HSSFDataFormat.GetBuiltinFormat("@");
  636. cellStyle.BorderBottom = BorderStyle.Thin;
  637. cellStyle.BorderLeft = BorderStyle.Thin;
  638. cellStyle.BorderRight = BorderStyle.Thin;
  639. cellStyle.BorderTop = BorderStyle.Thin;
  640. IFont cellfont = workbook.CreateFont();
  641. cellfont.Boldweight = (short)FontBoldWeight.Normal;
  642. cellStyle.SetFont(cellfont);
  643. for (int i = 0; i < dt.Rows.Count; i++)
  644. {
  645. if (i % sheetRowCount == 0)
  646. {
  647. if (i > 0)
  648. {
  649. //自适应列宽度
  650. for (int j = 0; j < icolIndex; j++)
  651. {
  652. sheet.AutoSizeColumn(j);
  653. }
  654. }
  655. sheetCount++;
  656. iRowIndex = 0;
  657. icolIndex = 0;
  658. sheet = workbook.CreateSheet(Name + sheetCount.ToString());
  659. headerRow = sheet.CreateRow(0);
  660. #region 表头
  661. if (cols == null || (cols != null && cols.Length == 0))
  662. {
  663. foreach (DataColumn dc in dt.Columns)
  664. {
  665. ICell cell = headerRow.CreateCell(icolIndex);
  666. cell.SetCellValue(dc.ColumnName);
  667. cell.CellStyle = HeadercellStyle;
  668. icolIndex++;
  669. }
  670. }
  671. else
  672. {
  673. foreach (string dc in cols)
  674. {
  675. ICell cell = headerRow.CreateCell(icolIndex);
  676. cell.SetCellValue(dc);
  677. cell.CellStyle = HeadercellStyle;
  678. icolIndex++;
  679. }
  680. }
  681. #endregion
  682. }
  683. IRow irow = sheet.CreateRow(iRowIndex + 1);
  684. foreach (DataColumn dc in dt.Columns)
  685. {
  686. string strsj = dt.Rows[i][dc]?.ToString() ?? "";
  687. ICell cell = irow.CreateCell(dc.Ordinal);
  688. cell.SetCellValue(strsj);
  689. cell.CellStyle = cellStyle;
  690. }
  691. iRowIndex++;
  692. }
  693. }
  694. using (MemoryStream ms = new MemoryStream())
  695. {
  696. workbook.Write(ms);
  697. HttpContext curContext = HttpContext.Current;
  698. // 设置编码和附件格式
  699. curContext.Response.ContentType = "application/vnd.ms-excel";
  700. curContext.Response.ContentEncoding = Encoding.UTF8;
  701. curContext.Response.Charset = "";
  702. curContext.Response.AppendHeader("Access-Control-Expose-Headers", "Content-Disposition");
  703. curContext.Response.AppendHeader("Content-Disposition",
  704. "attachment;filename=" + HttpUtility.UrlEncode(Name + "_导出文件_" + DateTime.Now.Ticks + ".xls", Encoding.UTF8));
  705. curContext.Response.BinaryWrite(ms.GetBuffer());
  706. workbook = null;
  707. ms.Close();
  708. ms.Dispose();
  709. curContext.Response.End();
  710. }
  711. return "";
  712. }
  713. catch (Exception ex)
  714. {
  715. // LogHelper.Error("导出2003失败!", ex);
  716. return "导出失败!";
  717. }
  718. }
  719. }
  720. }