Нет описания

NPOIHelper.cs 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  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();
  110. ISheet sheet = workbook.CreateSheet("Sheet1");
  111. ICellStyle HeadercellStyle = workbook.CreateCellStyle();
  112. HeadercellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
  113. HeadercellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
  114. HeadercellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
  115. HeadercellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
  116. HeadercellStyle.Alignment = HorizontalAlignment.Center;
  117. HeadercellStyle.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.SkyBlue.Index;
  118. HeadercellStyle.FillPattern = FillPattern.SolidForeground;
  119. HeadercellStyle.FillBackgroundColor = NPOI.HSSF.Util.HSSFColor.SkyBlue.Index;
  120. //字体
  121. NPOI.SS.UserModel.IFont headerfont = workbook.CreateFont();
  122. headerfont.Boldweight = (short)FontBoldWeight.Bold;
  123. headerfont.FontHeightInPoints = 12;
  124. HeadercellStyle.SetFont(headerfont);
  125. //用column name 作为列名
  126. int icolIndex = 0;
  127. IRow headerRow = sheet.CreateRow(0);
  128. if (cols == null || (cols != null && cols.Length == 0))
  129. {
  130. foreach (DataColumn dc in dt.Columns)
  131. {
  132. ICell cell = headerRow.CreateCell(icolIndex);
  133. cell.SetCellValue(dc.ColumnName);
  134. cell.CellStyle = HeadercellStyle;
  135. icolIndex++;
  136. }
  137. }
  138. else
  139. {
  140. foreach (string dc in cols)
  141. {
  142. ICell cell = headerRow.CreateCell(icolIndex);
  143. cell.SetCellValue(dc);
  144. cell.CellStyle = HeadercellStyle;
  145. icolIndex++;
  146. }
  147. }
  148. ICellStyle cellStyle = workbook.CreateCellStyle();
  149. //为避免日期格式被Excel自动替换,所以设定 format 为 『@』 表示一率当成text來看
  150. cellStyle.DataFormat = HSSFDataFormat.GetBuiltinFormat("@");
  151. cellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
  152. cellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
  153. cellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
  154. cellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
  155. NPOI.SS.UserModel.IFont cellfont = workbook.CreateFont();
  156. cellfont.Boldweight = (short)FontBoldWeight.Normal;
  157. cellStyle.SetFont(cellfont);
  158. //建立内容行
  159. int iRowIndex = 0;
  160. foreach (DataRow dr in dt.Rows)
  161. {
  162. int iCellIndex = 0;
  163. IRow irow = sheet.CreateRow(iRowIndex + 1);
  164. for (int i = 0; i < dt.Columns.Count; i++)
  165. {
  166. string strsj = string.Empty;
  167. if (dr[i] != null)
  168. {
  169. strsj = dr[i].ToString();
  170. }
  171. ICell cell = irow.CreateCell(iCellIndex);
  172. cell.SetCellValue(strsj);
  173. cell.CellStyle = cellStyle;
  174. iCellIndex++;
  175. }
  176. iRowIndex++;
  177. }
  178. //自适应列宽度
  179. for (int i = 0; i < icolIndex; i++)
  180. {
  181. sheet.AutoSizeColumn(i);
  182. }
  183. using (MemoryStream ms = new MemoryStream())
  184. {
  185. workbook.Write(ms);
  186. HttpContext curContext = HttpContext.Current;
  187. // 设置编码和附件格式
  188. curContext.Response.ContentType = "application/vnd.ms-excel";
  189. curContext.Response.ContentEncoding = Encoding.UTF8;
  190. curContext.Response.Charset = "";
  191. curContext.Response.AppendHeader("Content-Disposition",
  192. "attachment;filename=" + HttpUtility.UrlEncode(Name + ".xls", Encoding.UTF8));
  193. curContext.Response.BinaryWrite(ms.GetBuffer());
  194. workbook = null;
  195. ms.Close();
  196. ms.Dispose();
  197. curContext.Response.End();
  198. }
  199. //}
  200. return "";
  201. }
  202. catch
  203. {
  204. return "导出失败!";
  205. }
  206. }
  207. /// <summary>
  208. /// 导入excel转换为datatable
  209. /// </summary>
  210. /// <param name="upfile"></param>
  211. /// <param name="headrow"></param>
  212. /// <returns></returns>
  213. public DataTable ExcelToTable(HttpPostedFile upfile, int headrow)
  214. {
  215. DataTable dt = new DataTable();
  216. IWorkbook workbook = null;
  217. Stream stream = upfile.InputStream;
  218. string suffix = upfile.FileName.Substring(upfile.FileName.LastIndexOf(".") + 1).ToLower();
  219. if (suffix == "xlsx") // 2007版本
  220. {
  221. workbook = new XSSFWorkbook(stream);
  222. }
  223. else if (suffix == "xls") // 2003版本
  224. {
  225. workbook = new HSSFWorkbook(stream);
  226. }
  227. //获取excel的第一个sheet
  228. ISheet sheet = workbook.GetSheetAt(0);
  229. //获取sheet的第一行
  230. IRow headerRow = sheet.GetRow(headrow);
  231. //一行最后一个方格的编号 即总的列数
  232. int cellCount = headerRow.LastCellNum;
  233. //最后一列的标号 即总的行数
  234. int rowCount = sheet.LastRowNum;
  235. //列名
  236. for (int i = 0; i < cellCount; i++)
  237. {
  238. dt.Columns.Add(headerRow.GetCell(i).ToString());
  239. }
  240. for (int i = (sheet.FirstRowNum + headrow + 1); i <= sheet.LastRowNum; i++)
  241. {
  242. DataRow dr = dt.NewRow();
  243. IRow row = sheet.GetRow(i);
  244. for (int j = row.FirstCellNum; j < cellCount; j++)
  245. {
  246. if (row.GetCell(j) != null)
  247. {
  248. dr[j] = row.GetCell(j).ToString();
  249. }
  250. }
  251. dt.Rows.Add(dr);
  252. }
  253. sheet = null;
  254. workbook = null;
  255. return dt;
  256. }
  257. /// <summary>
  258. /// 导入excel转换为datatable
  259. /// </summary>
  260. /// <param name="upfile"></param>
  261. /// <param name="headrow"></param>
  262. /// <returns></returns>
  263. public DataTable ExcelToTable(string fileName, int headrow)
  264. {
  265. DataTable dt = new DataTable();
  266. IWorkbook workbook = null;
  267. Stream stream = new FileStream(fileName, FileMode.OpenOrCreate);
  268. string suffix = fileName.Substring(fileName.LastIndexOf(".") + 1).ToLower();
  269. if (suffix == "xlsx") // 2007版本
  270. {
  271. workbook = new XSSFWorkbook(stream);
  272. }
  273. else if (suffix == "xls") // 2003版本
  274. {
  275. workbook = new HSSFWorkbook(stream);
  276. }
  277. //获取excel的第一个sheet
  278. ISheet sheet = workbook.GetSheetAt(0);
  279. //获取sheet的第一行
  280. IRow headerRow = sheet.GetRow(headrow);
  281. //一行最后一个方格的编号 即总的列数
  282. int cellCount = headerRow.LastCellNum;
  283. //最后一列的标号 即总的行数
  284. int rowCount = sheet.LastRowNum;
  285. //列名
  286. for (int i = 0; i < cellCount; i++)
  287. {
  288. dt.Columns.Add(headerRow.GetCell(i).ToString());
  289. }
  290. for (int i = (sheet.FirstRowNum + headrow + 1); i <= sheet.LastRowNum; i++)
  291. {
  292. DataRow dr = dt.NewRow();
  293. IRow row = sheet.GetRow(i);
  294. for (int j = row.FirstCellNum; j < cellCount; j++)
  295. {
  296. if (row.GetCell(j) != null)
  297. {
  298. dr[j] = row.GetCell(j).ToString();
  299. }
  300. }
  301. dt.Rows.Add(dr);
  302. }
  303. sheet = null;
  304. workbook = null;
  305. return dt;
  306. }
  307. }
  308. }