新乡民调(来自息县民调) - 主标

NPOIHelper.cs 19KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  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. namespace CallCenter.Utility
  12. {
  13. public class NPOIHelper
  14. {
  15. private string _title;
  16. private string _sheetName;
  17. private string _filePath;
  18. /// <summary>
  19. /// 导出到Excel
  20. /// </summary>
  21. /// <param name="table"></param>
  22. /// <returns></returns>
  23. public bool ToExcel(DataTable table, string[] columns = null)
  24. {
  25. FileStream fs = new FileStream(this._filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
  26. IWorkbook workBook = new HSSFWorkbook();
  27. if (string.IsNullOrWhiteSpace(this._sheetName))
  28. {
  29. this._sheetName = "sheet1";
  30. }
  31. ISheet sheet = workBook.CreateSheet(this._sheetName);
  32. //处理表格标题
  33. IRow row = sheet.CreateRow(0);
  34. row.CreateCell(0).SetCellValue(this._title);
  35. sheet.AddMergedRegion(new CellRangeAddress(0, 0, 0, table.Columns.Count - 1));
  36. row.Height = 500;
  37. ICellStyle cellStyle = workBook.CreateCellStyle();
  38. IFont font = workBook.CreateFont();
  39. font.FontName = "微软雅黑";
  40. font.FontHeightInPoints = 17;
  41. cellStyle.SetFont(font);
  42. cellStyle.VerticalAlignment = VerticalAlignment.Center;
  43. cellStyle.Alignment = HorizontalAlignment.Center;
  44. row.Cells[0].CellStyle = cellStyle;
  45. //处理表格列头
  46. row = sheet.CreateRow(1);
  47. if (columns == null)
  48. {
  49. for (int i = 0; i < table.Columns.Count; i++)
  50. {
  51. row.CreateCell(i).SetCellValue(table.Columns[i].ColumnName);
  52. row.Height = 350;
  53. sheet.AutoSizeColumn(i);
  54. }
  55. }
  56. else
  57. {
  58. for (int i = 0; i < columns.Length; i++)
  59. {
  60. row.CreateCell(i).SetCellValue(columns[i]);
  61. row.Height = 350;
  62. sheet.AutoSizeColumn(i);
  63. }
  64. }
  65. //处理数据内容
  66. for (int i = 0; i < table.Rows.Count; i++)
  67. {
  68. row = sheet.CreateRow(2 + i);
  69. row.Height = 250;
  70. for (int j = 0; j < table.Columns.Count; j++)
  71. {
  72. row.CreateCell(j).SetCellValue(table.Rows[i][j].ToString());
  73. sheet.SetColumnWidth(j, 256 * 15);
  74. }
  75. }
  76. //写入数据流
  77. workBook.Write(fs);
  78. fs.Flush();
  79. fs.Close();
  80. return true;
  81. }
  82. /// <summary>
  83. /// 导出到Excel
  84. /// </summary>
  85. /// <param name="table"></param>
  86. /// <param name="title"></param>
  87. /// <param name="sheetName">空字符串或null的话默认sheet1</param>
  88. /// <param name="columns">自定义表格列头,默认null</param>
  89. /// <returns></returns>
  90. public bool ToExcel(DataTable table, string title, string sheetName, string filePath, string[] columns = null)
  91. {
  92. this._title = title;
  93. this._sheetName = sheetName;
  94. this._filePath = filePath;
  95. return ToExcel(table, columns);
  96. }
  97. /// <summary>
  98. /// 弹出下载框导出excel
  99. /// </summary>
  100. /// <param name="Name"></param>
  101. /// <param name="dt"></param>
  102. /// <returns></returns>
  103. public string ExportToExcel(string Name, DataTable dt, string[] cols = null)
  104. {
  105. try
  106. {
  107. //if (dt.Rows.Count > 0)
  108. //{
  109. HSSFWorkbook workbook = new HSSFWorkbook();//导出xls
  110. //IWorkbook workbook = new XSSFWorkbook();//导出xlsx
  111. ISheet sheet = workbook.CreateSheet("Sheet1");
  112. ICellStyle HeadercellStyle = workbook.CreateCellStyle();
  113. HeadercellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
  114. HeadercellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
  115. HeadercellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
  116. HeadercellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
  117. HeadercellStyle.Alignment = HorizontalAlignment.Center;
  118. HeadercellStyle.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.SkyBlue.Index;
  119. HeadercellStyle.FillPattern = FillPattern.SolidForeground;
  120. HeadercellStyle.FillBackgroundColor = NPOI.HSSF.Util.HSSFColor.SkyBlue.Index;
  121. //字体
  122. NPOI.SS.UserModel.IFont headerfont = workbook.CreateFont();
  123. headerfont.Boldweight = (short)FontBoldWeight.Bold;
  124. headerfont.FontHeightInPoints = 12;
  125. HeadercellStyle.SetFont(headerfont);
  126. //用column name 作为列名
  127. int icolIndex = 0;
  128. IRow headerRow = sheet.CreateRow(0);
  129. if (cols == null || (cols != null && cols.Length == 0))
  130. {
  131. foreach (DataColumn dc in dt.Columns)
  132. {
  133. ICell cell = headerRow.CreateCell(icolIndex);
  134. cell.SetCellValue(dc.ColumnName);
  135. cell.CellStyle = HeadercellStyle;
  136. icolIndex++;
  137. }
  138. }
  139. else
  140. {
  141. foreach (string dc in cols)
  142. {
  143. ICell cell = headerRow.CreateCell(icolIndex);
  144. cell.SetCellValue(dc);
  145. cell.CellStyle = HeadercellStyle;
  146. icolIndex++;
  147. }
  148. }
  149. ICellStyle cellStyle = workbook.CreateCellStyle();
  150. //为避免日期格式被Excel自动替换,所以设定 format 为 『@』 表示一率当成text來看
  151. cellStyle.DataFormat = HSSFDataFormat.GetBuiltinFormat("@");
  152. cellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
  153. cellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
  154. cellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
  155. cellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
  156. NPOI.SS.UserModel.IFont cellfont = workbook.CreateFont();
  157. cellfont.Boldweight = (short)FontBoldWeight.Normal;
  158. cellStyle.SetFont(cellfont);
  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. using (MemoryStream ms = new MemoryStream())
  185. {
  186. workbook.Write(ms);
  187. HttpContext curContext = HttpContext.Current;
  188. // 设置编码和附件格式
  189. curContext.Response.ContentType = "application/vnd.ms-excel";
  190. curContext.Response.ContentEncoding = Encoding.UTF8 ;//Encoding.UTF8;
  191. curContext.Response.Charset = "";
  192. curContext.Response.AppendHeader("Content-Disposition",
  193. "attachment;filename=" + HttpUtility.UrlEncode(Name + ".xls", Encoding.UTF8));
  194. curContext.Response.BinaryWrite(ms.GetBuffer());
  195. workbook = null;
  196. ms.Close();
  197. ms.Dispose();
  198. curContext.Response.End();
  199. }
  200. //}
  201. return "";
  202. }
  203. catch
  204. {
  205. return "导出失败!";
  206. }
  207. }
  208. /// <summary>
  209. /// 导入excel转换为datatable
  210. /// </summary>
  211. /// <param name="upfile"></param>
  212. /// <param name="headrow"></param>
  213. /// <returns></returns>
  214. public DataTable ExcelToTable(HttpPostedFile upfile, int headrow)
  215. {
  216. DataTable dt = new DataTable();
  217. IWorkbook workbook = null;
  218. Stream stream = upfile.InputStream;
  219. string suffix = upfile.FileName.Substring(upfile.FileName.LastIndexOf(".") + 1).ToLower();
  220. if (suffix == "xlsx") // 2007版本
  221. {
  222. workbook = new XSSFWorkbook(stream);
  223. }
  224. else if (suffix == "xls") // 2003版本
  225. {
  226. workbook = new HSSFWorkbook(stream);
  227. }
  228. //获取excel的第一个sheet
  229. ISheet sheet = workbook.GetSheetAt(0);
  230. //获取sheet的第一行
  231. IRow headerRow = sheet.GetRow(headrow);
  232. //一行最后一个方格的编号 即总的列数
  233. int cellCount = headerRow.LastCellNum;
  234. //最后一列的标号 即总的行数
  235. int rowCount = sheet.LastRowNum;
  236. //列名
  237. for (int i = 0; i < cellCount; i++)
  238. {
  239. dt.Columns.Add(headerRow.GetCell(i).ToString());
  240. }
  241. for (int i = (sheet.FirstRowNum + headrow); i <= sheet.LastRowNum; i++)
  242. {
  243. DataRow dr = dt.NewRow();
  244. IRow row = sheet.GetRow(i);
  245. for (int j = row.FirstCellNum; j < cellCount; j++)
  246. {
  247. if (row.GetCell(j) != null)
  248. {
  249. dr[j] = row.GetCell(j).ToString();
  250. }
  251. }
  252. dt.Rows.Add(dr);
  253. }
  254. sheet = null;
  255. workbook = null;
  256. return dt;
  257. }
  258. /// <summary>
  259. /// 导入excel转换为datatable
  260. /// </summary>
  261. /// <param name="upfile"></param>
  262. /// <param name="headrow"></param>
  263. /// <returns></returns>
  264. public DataTable ExcelToTable(string fileName, int headrow)
  265. {
  266. DataTable dt = new DataTable();
  267. IWorkbook workbook = null;
  268. Stream stream = new FileStream(fileName, FileMode.OpenOrCreate);
  269. string suffix = fileName.Substring(fileName.LastIndexOf(".") + 1).ToLower();
  270. if (suffix == "xlsx") // 2007版本
  271. {
  272. workbook = new XSSFWorkbook(stream);
  273. }
  274. else if (suffix == "xls") // 2003版本
  275. {
  276. workbook = new HSSFWorkbook(stream);
  277. }
  278. //获取excel的第一个sheet
  279. ISheet sheet = workbook.GetSheetAt(0);
  280. //获取sheet的第一行
  281. IRow headerRow = sheet.GetRow(headrow);
  282. //一行最后一个方格的编号 即总的列数
  283. int cellCount = headerRow.LastCellNum;
  284. //最后一列的标号 即总的行数
  285. int rowCount = sheet.LastRowNum;
  286. //列名
  287. for (int i = 0; i < cellCount; i++)
  288. {
  289. dt.Columns.Add(headerRow.GetCell(i).ToString());
  290. }
  291. for (int i = (sheet.FirstRowNum + headrow + 1); i <= sheet.LastRowNum; i++)
  292. {
  293. DataRow dr = dt.NewRow();
  294. IRow row = sheet.GetRow(i);
  295. for (int j = row.FirstCellNum; j < cellCount; j++)
  296. {
  297. if (row.GetCell(j) != null)
  298. {
  299. dr[j] = row.GetCell(j).ToString();
  300. }
  301. }
  302. dt.Rows.Add(dr);
  303. }
  304. sheet = null;
  305. workbook = null;
  306. return dt;
  307. }
  308. //2017-11-11数据第一行为标题
  309. #region
  310. /// <summary>
  311. /// 弹出下载框导出excel(数据第一行为标题)
  312. /// </summary>
  313. /// <param name="Name"></param>
  314. /// <param name="dt"></param>
  315. /// <returns></returns>
  316. public string ExportToExcel2(string Name, DataTable dt, string[] cols = null)
  317. {
  318. try
  319. {
  320. //if (dt.Rows.Count > 0)
  321. //{
  322. HSSFWorkbook workbook = new HSSFWorkbook();
  323. ISheet sheet = workbook.CreateSheet("Sheet1");
  324. ICellStyle HeadercellStyle = workbook.CreateCellStyle();
  325. HeadercellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
  326. HeadercellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
  327. HeadercellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
  328. HeadercellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
  329. HeadercellStyle.Alignment = HorizontalAlignment.Center;
  330. HeadercellStyle.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.SkyBlue.Index;
  331. HeadercellStyle.FillPattern = FillPattern.SolidForeground;
  332. HeadercellStyle.FillBackgroundColor = NPOI.HSSF.Util.HSSFColor.SkyBlue.Index;
  333. //字体
  334. NPOI.SS.UserModel.IFont headerfont = workbook.CreateFont();
  335. headerfont.Boldweight = (short)FontBoldWeight.Bold;
  336. headerfont.FontHeightInPoints = 12;
  337. HeadercellStyle.SetFont(headerfont);
  338. //第一行为标题
  339. IRow headRow = sheet.CreateRow(0);
  340. ICell cellh = headRow.CreateCell(0);
  341. cellh.CellStyle = HeadercellStyle;
  342. cellh.SetCellValue(Name );
  343. sheet.AddMergedRegion(new CellRangeAddress(0, 0, 0, dt.Columns .Count-1));
  344. //用column name 作为列名
  345. int icolIndex = 0;
  346. IRow headerRow = sheet.CreateRow(1);
  347. if (cols == null || (cols != null && cols.Length == 0))
  348. {
  349. //foreach (DataColumn dc in dt.Columns)
  350. //{
  351. // ICell cell = headerRow.CreateCell(icolIndex);
  352. // cell.SetCellValue(dc.ColumnName);
  353. // cell.CellStyle = HeadercellStyle;
  354. // icolIndex++;
  355. //}
  356. for (int i = 0; i < dt.Columns.Count; i++)
  357. {
  358. ICell cell = headerRow.CreateCell(icolIndex);
  359. cell.SetCellValue(dt.Columns[i].ColumnName);//cell.SetCellValue(dt.Rows [0][i].ToString());
  360. cell.CellStyle = HeadercellStyle;
  361. icolIndex++;
  362. }
  363. }
  364. else
  365. {
  366. foreach (string dc in cols)
  367. {
  368. ICell cell = headerRow.CreateCell(icolIndex);
  369. cell.SetCellValue(dc);
  370. cell.CellStyle = HeadercellStyle;
  371. icolIndex++;
  372. }
  373. }
  374. ICellStyle cellStyle = workbook.CreateCellStyle();
  375. //为避免日期格式被Excel自动替换,所以设定 format 为 『@』 表示一率当成text來看
  376. cellStyle.DataFormat = HSSFDataFormat.GetBuiltinFormat("@");
  377. cellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
  378. cellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
  379. cellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
  380. cellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
  381. NPOI.SS.UserModel.IFont cellfont = workbook.CreateFont();
  382. cellfont.Boldweight = (short)FontBoldWeight.Normal;
  383. cellStyle.SetFont(cellfont);
  384. //建立内容行
  385. int iRowIndex = 2;
  386. foreach (DataRow dr in dt.Rows)
  387. {
  388. if (iRowIndex >= 2)
  389. {
  390. int iCellIndex = 0;
  391. IRow irow = sheet.CreateRow(iRowIndex );
  392. for (int i = 0; i < dt.Columns.Count; i++)
  393. {
  394. string strsj = string.Empty;
  395. if (dr[i] != null)
  396. {
  397. strsj = dr[i].ToString();
  398. }
  399. ICell cell = irow.CreateCell(iCellIndex);
  400. cell.SetCellValue(strsj);
  401. cell.CellStyle = cellStyle;
  402. iCellIndex++;
  403. }
  404. }
  405. iRowIndex++;
  406. }
  407. //自适应列宽度
  408. for (int i = 0; i < icolIndex; i++)
  409. {
  410. sheet.AutoSizeColumn(i);
  411. // 解决自动设置列宽中文失效的问题
  412. sheet.SetColumnWidth(i, sheet.GetColumnWidth(i) * 17 / 10);
  413. }
  414. using (MemoryStream ms = new MemoryStream())
  415. {
  416. workbook.Write(ms);
  417. HttpContext curContext = HttpContext.Current;
  418. // 设置编码和附件格式
  419. curContext.Response.ContentType = "application/vnd.ms-excel";
  420. curContext.Response.ContentEncoding = Encoding.UTF8;
  421. curContext.Response.Charset = "";
  422. curContext.Response.AppendHeader("Content-Disposition",
  423. "attachment;filename=" + HttpUtility.UrlEncode(Name + ".xls", Encoding.UTF8));
  424. curContext.Response.BinaryWrite(ms.GetBuffer());
  425. workbook = null;
  426. ms.Close();
  427. ms.Dispose();
  428. curContext.Response.End();
  429. }
  430. //}
  431. return "";
  432. }
  433. catch
  434. {
  435. return "导出失败!";
  436. }
  437. }
  438. #endregion
  439. }
  440. }