Brak opisu

NPOIHelper.cs 25KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671
  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. using System.Linq;
  13. namespace CallCenter.Utility
  14. {
  15. public class NPOIHelper
  16. {
  17. private string _title;
  18. private string _sheetName;
  19. private string _filePath;
  20. /// <summary>
  21. /// 导出到Excel
  22. /// </summary>
  23. /// <param name="table"></param>
  24. /// <returns></returns>
  25. public bool ToExcel(DataTable table, string[] columns = null)
  26. {
  27. FileStream fs = new FileStream(this._filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
  28. IWorkbook workBook = new HSSFWorkbook();
  29. if (string.IsNullOrWhiteSpace(this._sheetName))
  30. {
  31. this._sheetName = "sheet1";
  32. }
  33. ISheet sheet = workBook.CreateSheet(this._sheetName);
  34. //处理表格标题
  35. IRow row = sheet.CreateRow(0);
  36. row.CreateCell(0).SetCellValue(this._title);
  37. sheet.AddMergedRegion(new CellRangeAddress(0, 0, 0, table.Columns.Count - 1));
  38. row.Height = 500;
  39. ICellStyle cellStyle = workBook.CreateCellStyle();
  40. IFont font = workBook.CreateFont();
  41. font.FontName = "微软雅黑";
  42. font.FontHeightInPoints = 17;
  43. cellStyle.SetFont(font);
  44. cellStyle.VerticalAlignment = VerticalAlignment.Center;
  45. cellStyle.Alignment = HorizontalAlignment.Center;
  46. row.Cells[0].CellStyle = cellStyle;
  47. //处理表格列头
  48. row = sheet.CreateRow(1);
  49. if (columns == null)
  50. {
  51. for (int i = 0; i < table.Columns.Count; i++)
  52. {
  53. row.CreateCell(i).SetCellValue(table.Columns[i].ColumnName);
  54. row.Height = 350;
  55. sheet.AutoSizeColumn(i);
  56. }
  57. }
  58. else
  59. {
  60. for (int i = 0; i < columns.Length; i++)
  61. {
  62. row.CreateCell(i).SetCellValue(columns[i]);
  63. row.Height = 350;
  64. sheet.AutoSizeColumn(i);
  65. }
  66. }
  67. //处理数据内容
  68. for (int i = 0; i < table.Rows.Count; i++)
  69. {
  70. row = sheet.CreateRow(2 + i);
  71. row.Height = 250;
  72. for (int j = 0; j < table.Columns.Count; j++)
  73. {
  74. row.CreateCell(j).SetCellValue(table.Rows[i][j].ToString());
  75. sheet.SetColumnWidth(j, 256 * 15);
  76. }
  77. }
  78. //写入数据流
  79. workBook.Write(fs);
  80. fs.Flush();
  81. fs.Close();
  82. return true;
  83. }
  84. /// <summary>
  85. /// 导出到Excel
  86. /// </summary>
  87. /// <param name="table"></param>
  88. /// <param name="title"></param>
  89. /// <param name="sheetName">空字符串或null的话默认sheet1</param>
  90. /// <param name="columns">自定义表格列头,默认null</param>
  91. /// <returns></returns>
  92. public bool ToExcel(DataTable table, string title, string sheetName, string filePath, string[] columns = null)
  93. {
  94. this._title = title;
  95. this._sheetName = sheetName;
  96. this._filePath = filePath;
  97. return ToExcel(table, columns);
  98. }
  99. /// <summary>
  100. /// 弹出下载框导出excel
  101. /// </summary>
  102. /// <param name="Name"></param>
  103. /// <param name="dt"></param>
  104. /// <returns></returns>
  105. public string ExportToExcel(string Name, DataTable dt, string[] cols = null
  106. ,int [] Format=null)
  107. {
  108. try
  109. {
  110. //if (dt.Rows.Count > 0)
  111. //{
  112. HSSFWorkbook workbook = new HSSFWorkbook();
  113. ISheet sheet = workbook.CreateSheet("Sheet1");
  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. ICellStyle cellStyle1 = workbook.CreateCellStyle();
  162. //为避免日期格式被Excel自动替换,所以设定 format 为 『@』 表示一率当成text來看
  163. cellStyle1.DataFormat = HSSFDataFormat.GetBuiltinFormat("#,##0.00");
  164. cellStyle1.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
  165. cellStyle1.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
  166. cellStyle1.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
  167. cellStyle1.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
  168. cellStyle1.SetFont(cellfont);
  169. //建立内容行
  170. int iRowIndex = 0;
  171. foreach (DataRow dr in dt.Rows)
  172. {
  173. int iCellIndex = 0;
  174. IRow irow = sheet.CreateRow(iRowIndex + 1);
  175. for (int i = 0; i < dt.Columns.Count; i++)
  176. {
  177. string strsj = string.Empty;
  178. if (dr[i] != null)
  179. {
  180. strsj = dr[i].ToString();
  181. }
  182. ICell cell = irow.CreateCell(iCellIndex);
  183. cell.SetCellValue(strsj);
  184. if (Format!=null&&Array.Exists(Format, element => element == i) )
  185. {
  186. cell.CellStyle = cellStyle1;
  187. }
  188. else
  189. {
  190. cell.CellStyle = cellStyle;
  191. }
  192. iCellIndex++;
  193. }
  194. iRowIndex++;
  195. }
  196. //自适应列宽度
  197. for (int i = 0; i < icolIndex; i++)
  198. {
  199. sheet.AutoSizeColumn(i);
  200. }
  201. using (MemoryStream ms = new MemoryStream())
  202. {
  203. workbook.Write(ms);
  204. HttpContext curContext = HttpContext.Current;
  205. // 设置编码和附件格式
  206. curContext.Response.ContentType = "application/vnd.ms-excel";
  207. curContext.Response.ContentEncoding = Encoding.UTF8;
  208. curContext.Response.Charset = "";
  209. curContext.Response.AppendHeader("Content-Disposition",
  210. "attachment;filename=" + HttpUtility.UrlEncode(Name + ".xls", Encoding.UTF8));
  211. curContext.Response.BinaryWrite(ms.GetBuffer());
  212. workbook = null;
  213. ms.Close();
  214. ms.Dispose();
  215. curContext.Response.End();
  216. }
  217. //}
  218. return "";
  219. }
  220. catch
  221. {
  222. return "导出失败!";
  223. }
  224. }
  225. /// <summary>
  226. /// 合并单元格
  227. /// </summary>
  228. /// <param name="sheet">要合并单元格所在的sheet</param>
  229. /// <param name="rowstart">开始行的索引</param>
  230. /// <param name="rowend">结束行的索引</param>
  231. /// <param name="colstart">开始列的索引</param>
  232. /// <param name="colend">结束列的索引</param>
  233. public static void SetCellRangeAddress(ISheet sheet, int rowstart, int rowend, int colstart, int colend)
  234. {
  235. CellRangeAddress cellRangeAddress = new CellRangeAddress(rowstart, rowend, colstart, colend);
  236. sheet.AddMergedRegion(cellRangeAddress);
  237. }
  238. /// <summary>
  239. /// 工单类型弹出下载框导出excel
  240. /// </summary>
  241. /// <param name="Name"></param>
  242. /// <param name="dt"></param>
  243. /// <param name="typeclass">仪器或试剂</param>
  244. /// <returns></returns>
  245. public string ExportToExcelForGDLX(string Name, DataTable dt, string typeclass, List<string> colnames, List<int> erows, List<string> secolnames)
  246. {
  247. try
  248. {
  249. HSSFWorkbook workbook = new HSSFWorkbook();
  250. ISheet sheet = workbook.CreateSheet("Sheet1");
  251. ICellStyle HeadercellStyle = workbook.CreateCellStyle();
  252. HeadercellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
  253. HeadercellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
  254. HeadercellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
  255. HeadercellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
  256. HeadercellStyle.Alignment = HorizontalAlignment.Center;
  257. HeadercellStyle.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.SkyBlue.Index;
  258. HeadercellStyle.FillPattern = FillPattern.SolidForeground;
  259. HeadercellStyle.FillBackgroundColor = NPOI.HSSF.Util.HSSFColor.SkyBlue.Index;
  260. //字体
  261. NPOI.SS.UserModel.IFont headerfont = workbook.CreateFont();
  262. headerfont.Boldweight = (short)FontBoldWeight.Bold;
  263. headerfont.FontHeightInPoints = 12;
  264. HeadercellStyle.SetFont(headerfont);
  265. //用column name 作为列名
  266. int icolIndex = 0;
  267. IRow headerRow = sheet.CreateRow(0);
  268. for (int i = 0; i < colnames.Count; i++)
  269. {
  270. ICell cell = headerRow.CreateCell(i);
  271. cell.SetCellValue(colnames[i]);
  272. cell.CellStyle = HeadercellStyle;
  273. //SetCellRangeAddress(sheet, 0, 0, erows[i * 2], erows[i * 2 + 1]);
  274. }
  275. for (int k = 0; k < erows.Count / 2; k++)
  276. {
  277. SetCellRangeAddress(sheet, 0, 0, erows[k * 2], erows[k * 2 + 1]);
  278. }
  279. //添加第二行标题
  280. IRow SecRow = sheet.CreateRow(1);
  281. for (int i = 0; i < secolnames.Count; i++)
  282. {
  283. ICell cell = SecRow.CreateCell(i);
  284. cell.SetCellValue(secolnames[i].ToString());
  285. }
  286. ICellStyle cellStyle = workbook.CreateCellStyle();
  287. //为避免日期格式被Excel自动替换,所以设定 format 为 『@』 表示一率当成text來看
  288. cellStyle.DataFormat = HSSFDataFormat.GetBuiltinFormat("@");
  289. cellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
  290. cellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
  291. cellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
  292. cellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
  293. NPOI.SS.UserModel.IFont cellfont = workbook.CreateFont();
  294. cellfont.Boldweight = (short)FontBoldWeight.Normal;
  295. cellStyle.SetFont(cellfont);
  296. //建立内容行
  297. int iRowIndex = 0;
  298. foreach (DataRow dr in dt.Rows)
  299. {
  300. int iCellIndex = 0;
  301. IRow irow = sheet.CreateRow(iRowIndex + 2);
  302. for (int i = 0; i < dt.Columns.Count; i++)
  303. {
  304. string strsj = string.Empty;
  305. if (dr[i] != null)
  306. {
  307. strsj = dr[i].ToString();
  308. }
  309. ICell cell = irow.CreateCell(iCellIndex);
  310. cell.SetCellValue(strsj);
  311. cell.CellStyle = cellStyle;
  312. iCellIndex++;
  313. }
  314. iRowIndex++;
  315. }
  316. //自适应列宽度
  317. for (int i = 0; i < icolIndex; i++)
  318. {
  319. sheet.AutoSizeColumn(i);
  320. }
  321. using (MemoryStream ms = new MemoryStream())
  322. {
  323. workbook.Write(ms);
  324. HttpContext curContext = HttpContext.Current;
  325. // 设置编码和附件格式
  326. curContext.Response.ContentType = "application/vnd.ms-excel";
  327. curContext.Response.ContentEncoding = Encoding.UTF8;
  328. curContext.Response.Charset = "";
  329. curContext.Response.AppendHeader("Content-Disposition",
  330. "attachment;filename=" + HttpUtility.UrlEncode(Name + ".xls", Encoding.UTF8));
  331. curContext.Response.BinaryWrite(ms.GetBuffer());
  332. workbook = null;
  333. ms.Close();
  334. ms.Dispose();
  335. curContext.Response.End();
  336. }
  337. return "";
  338. }
  339. catch (Exception e)
  340. {
  341. return "导出失败!" + e.Message;
  342. }
  343. }
  344. /// <summary>
  345. /// 导入excel转换为datatable
  346. /// </summary>
  347. /// <param name="upfile"></param>
  348. /// <param name="headrow"></param>
  349. /// <returns></returns>
  350. public DataTable ExcelToTable(HttpPostedFile upfile, int headrow)
  351. {
  352. DataTable dt = new DataTable();
  353. IWorkbook workbook = null;
  354. Stream stream = upfile.InputStream;
  355. string suffix = upfile.FileName.Substring(upfile.FileName.LastIndexOf(".") + 1).ToLower();
  356. if (suffix == "xlsx") // 2007版本
  357. {
  358. workbook = new XSSFWorkbook(stream);
  359. }
  360. else if (suffix == "xls") // 2003版本
  361. {
  362. workbook = new HSSFWorkbook(stream);
  363. }
  364. //获取excel的第一个sheet
  365. ISheet sheet = workbook.GetSheetAt(0);
  366. //获取sheet的第一行
  367. IRow headerRow = sheet.GetRow(headrow);
  368. //一行最后一个方格的编号 即总的列数
  369. int cellCount = headerRow.LastCellNum;
  370. //最后一列的标号 即总的行数
  371. int rowCount = sheet.LastRowNum;
  372. //列名
  373. for (int i = 0; i < cellCount; i++)
  374. {
  375. dt.Columns.Add(headerRow.GetCell(i).ToString());
  376. }
  377. for (int i = (sheet.FirstRowNum + headrow + 1); i <= sheet.LastRowNum; i++)
  378. {
  379. DataRow dr = dt.NewRow();
  380. IRow row = sheet.GetRow(i);
  381. if (row != null)
  382. {
  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. }
  393. sheet = null;
  394. workbook = null;
  395. return dt;
  396. }
  397. /// <summary>
  398. /// 导入excel转换为datatable
  399. /// </summary>
  400. /// <param name="upfile"></param>
  401. /// <param name="headrow"></param>
  402. /// <returns></returns>
  403. public DataTable ExcelToTable(string fileName, int headrow)
  404. {
  405. DataTable dt = new DataTable();
  406. IWorkbook workbook = null;
  407. Stream stream = new FileStream(fileName, FileMode.OpenOrCreate);
  408. string suffix = fileName.Substring(fileName.LastIndexOf(".") + 1).ToLower();
  409. if (suffix == "xlsx") // 2007版本
  410. {
  411. workbook = new XSSFWorkbook(stream);
  412. }
  413. else if (suffix == "xls") // 2003版本
  414. {
  415. workbook = new HSSFWorkbook(stream);
  416. }
  417. //获取excel的第一个sheet
  418. ISheet sheet = workbook.GetSheetAt(0);
  419. //获取sheet的第一行
  420. IRow headerRow = sheet.GetRow(headrow);
  421. //一行最后一个方格的编号 即总的列数
  422. int cellCount = headerRow.LastCellNum;
  423. //最后一列的标号 即总的行数
  424. int rowCount = sheet.LastRowNum;
  425. //列名
  426. for (int i = 0; i < cellCount; i++)
  427. {
  428. dt.Columns.Add(headerRow.GetCell(i).ToString());
  429. }
  430. for (int i = (sheet.FirstRowNum + headrow + 1); i <= sheet.LastRowNum; i++)
  431. {
  432. DataRow dr = dt.NewRow();
  433. IRow row = sheet.GetRow(i);
  434. for (int j = row.FirstCellNum; j < cellCount; j++)
  435. {
  436. if (row.GetCell(j) != null)
  437. {
  438. dr[j] = row.GetCell(j).ToString();
  439. }
  440. }
  441. dt.Rows.Add(dr);
  442. }
  443. sheet = null;
  444. workbook = null;
  445. return dt;
  446. }
  447. #region 弹出下载框导出excel(数据第一行为标题)
  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. //用column name 作为列名
  477. int icolIndex = 0;
  478. IRow headerRow = sheet.CreateRow(0);
  479. if (cols == null || (cols != null && cols.Length == 0))
  480. {
  481. //foreach (DataColumn dc in dt.Columns)
  482. //{
  483. // ICell cell = headerRow.CreateCell(icolIndex);
  484. // cell.SetCellValue(dc.ColumnName);
  485. // cell.CellStyle = HeadercellStyle;
  486. // icolIndex++;
  487. //}
  488. for (int i = 0; i < dt.Columns.Count; i++)
  489. {
  490. ICell cell = headerRow.CreateCell(icolIndex);
  491. cell.SetCellValue(dt.Rows[0][i].ToString());
  492. cell.CellStyle = HeadercellStyle;
  493. icolIndex++;
  494. }
  495. }
  496. else
  497. {
  498. foreach (string dc in cols)
  499. {
  500. ICell cell = headerRow.CreateCell(icolIndex);
  501. cell.SetCellValue(dc);
  502. cell.CellStyle = HeadercellStyle;
  503. icolIndex++;
  504. }
  505. }
  506. ICellStyle cellStyle = workbook.CreateCellStyle();
  507. //为避免日期格式被Excel自动替换,所以设定 format 为 『@』 表示一率当成text來看
  508. cellStyle.DataFormat = HSSFDataFormat.GetBuiltinFormat("@");
  509. cellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
  510. cellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
  511. cellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
  512. cellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
  513. NPOI.SS.UserModel.IFont cellfont = workbook.CreateFont();
  514. cellfont.Boldweight = (short)FontBoldWeight.Normal;
  515. cellStyle.SetFont(cellfont);
  516. //建立内容行
  517. int iRowIndex = 0;
  518. foreach (DataRow dr in dt.Rows)
  519. {
  520. if (iRowIndex > 0)
  521. {
  522. int iCellIndex = 0;
  523. IRow irow = sheet.CreateRow(iRowIndex);
  524. for (int i = 0; i < dt.Columns.Count; i++)
  525. {
  526. string strsj = string.Empty;
  527. if (dr[i] != null)
  528. {
  529. strsj = dr[i].ToString();
  530. }
  531. ICell cell = irow.CreateCell(iCellIndex);
  532. cell.SetCellValue(strsj);
  533. cell.CellStyle = cellStyle;
  534. iCellIndex++;
  535. }
  536. }
  537. iRowIndex++;
  538. }
  539. //自适应列宽度
  540. for (int i = 0; i < icolIndex; i++)
  541. {
  542. sheet.AutoSizeColumn(i);
  543. }
  544. using (MemoryStream ms = new MemoryStream())
  545. {
  546. workbook.Write(ms);
  547. HttpContext curContext = HttpContext.Current;
  548. // 设置编码和附件格式
  549. curContext.Response.ContentType = "application/vnd.ms-excel";
  550. curContext.Response.ContentEncoding = Encoding.UTF8;
  551. curContext.Response.Charset = "";
  552. curContext.Response.AppendHeader("Content-Disposition",
  553. "attachment;filename=" + HttpUtility.UrlEncode(Name + ".xls", Encoding.UTF8));
  554. curContext.Response.BinaryWrite(ms.GetBuffer());
  555. workbook = null;
  556. ms.Close();
  557. ms.Dispose();
  558. curContext.Response.End();
  559. }
  560. //}
  561. return "";
  562. }
  563. catch
  564. {
  565. return "导出失败!";
  566. }
  567. }
  568. #endregion
  569. }
  570. }