人民医院API

NPOIHelper.cs 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. 
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Data;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Web;
  9. using NPOI.HSSF.UserModel;
  10. using NPOI.OpenXmlFormats.Wordprocessing;
  11. using NPOI.SS.UserModel;
  12. using NPOI.SS.Util;
  13. using NPOI.XSSF.UserModel;
  14. namespace RMYY_CallCenter_Api.Utility
  15. {
  16. public class NPOIHelper
  17. {
  18. /// <summary>
  19. /// 弹出下载框导出excel
  20. /// </summary>
  21. /// <param name="Name"></param>
  22. /// <param name="dt"></param>
  23. /// <returns></returns>
  24. public string ExportToExcel2(string Name, DataTable dt, string[] cols = null)
  25. {
  26. try
  27. {
  28. //if (dt.Rows.Count > 0)
  29. //{
  30. HSSFWorkbook workbook = new HSSFWorkbook();
  31. ISheet sheet = workbook.CreateSheet(Name);
  32. ICellStyle HeadercellStyle = workbook.CreateCellStyle();
  33. HeadercellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
  34. HeadercellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
  35. HeadercellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
  36. HeadercellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
  37. HeadercellStyle.Alignment = HorizontalAlignment.Center;
  38. HeadercellStyle.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.SkyBlue.Index;
  39. HeadercellStyle.FillPattern = FillPattern.SolidForeground;
  40. HeadercellStyle.FillBackgroundColor = NPOI.HSSF.Util.HSSFColor.SkyBlue.Index;
  41. //字体
  42. NPOI.SS.UserModel.IFont headerfont = workbook.CreateFont();
  43. headerfont.Boldweight = (short)FontBoldWeight.Bold;
  44. headerfont.FontHeightInPoints = 12;
  45. HeadercellStyle.SetFont(headerfont);
  46. //用column name 作为列名
  47. int icolIndex = 0;
  48. IRow headerRow = sheet.CreateRow(0);
  49. if (cols == null || (cols != null && cols.Length == 0))
  50. {
  51. foreach (DataColumn dc in dt.Columns)
  52. {
  53. ICell cell = headerRow.CreateCell(icolIndex);
  54. cell.SetCellValue(dc.ColumnName);
  55. cell.CellStyle = HeadercellStyle;
  56. icolIndex++;
  57. }
  58. }
  59. else
  60. {
  61. foreach (string dc in cols)
  62. {
  63. ICell cell = headerRow.CreateCell(icolIndex);
  64. cell.SetCellValue(dc);
  65. cell.CellStyle = HeadercellStyle;
  66. icolIndex++;
  67. }
  68. }
  69. ICellStyle cellStyle = workbook.CreateCellStyle();
  70. //为避免日期格式被Excel自动替换,所以设定 format 为 『@』 表示一率当成text來看
  71. cellStyle.DataFormat = HSSFDataFormat.GetBuiltinFormat("@");
  72. cellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
  73. cellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
  74. cellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
  75. cellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
  76. NPOI.SS.UserModel.IFont cellfont = workbook.CreateFont();
  77. cellfont.Boldweight = (short)FontBoldWeight.Normal;
  78. cellStyle.SetFont(cellfont);
  79. //建立内容行
  80. int iRowIndex = 0;
  81. foreach (DataRow dr in dt.Rows)
  82. {
  83. int iCellIndex = 0;
  84. IRow irow = sheet.CreateRow(iRowIndex + 1);
  85. for (int i = 0; i < dt.Columns.Count; i++)
  86. {
  87. string strsj = string.Empty;
  88. if (dr[i] != null)
  89. {
  90. strsj = dr[i].ToString();
  91. }
  92. ICell cell = irow.CreateCell(iCellIndex);
  93. cell.SetCellValue(strsj);
  94. cell.CellStyle = cellStyle;
  95. iCellIndex++;
  96. }
  97. iRowIndex++;
  98. }
  99. //自适应列宽度
  100. for (int i = 0; i < icolIndex; i++)
  101. {
  102. sheet.AutoSizeColumn(i);
  103. }
  104. using (MemoryStream ms = new MemoryStream())
  105. {
  106. workbook.Write(ms);
  107. HttpContext curContext = HttpContext.Current;
  108. // 设置编码和附件格式
  109. curContext.Response.ContentType = "application/vnd.ms-excel";
  110. curContext.Response.ContentEncoding = Encoding.UTF8;
  111. curContext.Response.Charset = "";
  112. curContext.Response.AppendHeader("Access-Control-Expose-Headers", "Content-Disposition");
  113. curContext.Response.AppendHeader("Content-Disposition",
  114. "attachment;filename=" + HttpUtility.UrlEncode(Name + "_导出文件_" + DateTime.Now.Ticks + ".xls", Encoding.UTF8));
  115. curContext.Response.BinaryWrite(ms.GetBuffer());
  116. workbook = null;
  117. ms.Close();
  118. ms.Dispose();
  119. curContext.Response.End();
  120. }
  121. //}
  122. return "";
  123. }
  124. catch
  125. {
  126. return "导出失败!";
  127. }
  128. }
  129. /// <summary>
  130. /// 弹出下载框导出excel
  131. /// </summary>
  132. /// <param name="Name"></param>
  133. /// <param name="dt"></param>
  134. /// <returns></returns>
  135. public string ExportToExcel(string Name, DataTable dt, string[] cols = null, int issort = 0)
  136. {
  137. try
  138. {
  139. //if (dt.Rows.Count > 0)
  140. //{
  141. HSSFWorkbook workbook = new HSSFWorkbook();
  142. ISheet sheet = workbook.CreateSheet(Name);
  143. ICellStyle HeadercellStyle = workbook.CreateCellStyle();
  144. HeadercellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
  145. HeadercellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
  146. HeadercellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
  147. HeadercellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
  148. HeadercellStyle.Alignment = HorizontalAlignment.Center;
  149. HeadercellStyle.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.SkyBlue.Index;
  150. HeadercellStyle.FillPattern = FillPattern.SolidForeground;
  151. HeadercellStyle.FillBackgroundColor = NPOI.HSSF.Util.HSSFColor.SkyBlue.Index;
  152. //字体
  153. NPOI.SS.UserModel.IFont headerfont = workbook.CreateFont();
  154. headerfont.Boldweight = (short)FontBoldWeight.Bold;
  155. headerfont.FontHeightInPoints = 12;
  156. HeadercellStyle.SetFont(headerfont);
  157. //用column name 作为列名
  158. int icolIndex = 0;
  159. IRow headerRow = sheet.CreateRow(0);
  160. if (issort == 1)
  161. {
  162. ICell cell = headerRow.CreateCell(icolIndex);
  163. cell.SetCellValue("序号");
  164. cell.CellStyle = HeadercellStyle;
  165. icolIndex++;
  166. }
  167. if (cols == null || (cols != null && cols.Length == 0))
  168. {
  169. foreach (DataColumn dc in dt.Columns)
  170. {
  171. ICell cell = headerRow.CreateCell(icolIndex);
  172. cell.SetCellValue(dc.ColumnName);
  173. cell.CellStyle = HeadercellStyle;
  174. icolIndex++;
  175. }
  176. }
  177. else
  178. {
  179. foreach (string dc in cols)
  180. {
  181. ICell cell = headerRow.CreateCell(icolIndex);
  182. cell.SetCellValue(dc);
  183. cell.CellStyle = HeadercellStyle;
  184. icolIndex++;
  185. }
  186. }
  187. ICellStyle cellStyle = workbook.CreateCellStyle();
  188. //为避免日期格式被Excel自动替换,所以设定 format 为 『@』 表示一率当成text來看
  189. cellStyle.DataFormat = HSSFDataFormat.GetBuiltinFormat("@");
  190. cellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
  191. cellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
  192. cellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
  193. cellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
  194. NPOI.SS.UserModel.IFont cellfont = workbook.CreateFont();
  195. cellfont.Boldweight = (short)FontBoldWeight.Normal;
  196. cellStyle.SetFont(cellfont);
  197. //建立内容行
  198. int iRowIndex = 0;
  199. foreach (DataRow dr in dt.Rows)
  200. {
  201. int iCellIndex = 0;
  202. IRow irow = sheet.CreateRow(iRowIndex + 1);
  203. if (issort == 1)
  204. {
  205. ICell cell = irow.CreateCell(iCellIndex);
  206. cell.SetCellValue(iRowIndex + 1);
  207. cell.CellStyle = cellStyle;
  208. iCellIndex++;
  209. }
  210. for (int i = 0; i < dt.Columns.Count; i++)
  211. {
  212. string strsj = string.Empty;
  213. if (dr[i] != null)
  214. {
  215. strsj = dr[i].ToString();
  216. }
  217. ICell cell = irow.CreateCell(iCellIndex);
  218. cell.SetCellValue(strsj);
  219. cell.CellStyle = cellStyle;
  220. iCellIndex++;
  221. }
  222. iRowIndex++;
  223. }
  224. //自适应列宽度
  225. for (int i = 0; i < icolIndex; i++)
  226. {
  227. sheet.AutoSizeColumn(i);
  228. }
  229. using (MemoryStream ms = new MemoryStream())
  230. {
  231. workbook.Write(ms);
  232. HttpContext curContext = HttpContext.Current;
  233. // 设置编码和附件格式
  234. curContext.Response.ContentType = "application/vnd.ms-excel"; //指定返回的是一个不能被客户端读取的流,必须被下载
  235. curContext.Response.ContentEncoding = Encoding.UTF8;
  236. curContext.Response.Charset = "";
  237. curContext.Response.AppendHeader("Access-Control-Expose-Headers", "Content-Disposition");
  238. curContext.Response.AppendHeader("Content-Disposition",
  239. "attachment;filename=" + HttpUtility.UrlEncode(Name + "_导出文件_" + DateTime.Now.Ticks + ".xls", Encoding.UTF8));
  240. curContext.Response.BinaryWrite(ms.GetBuffer());
  241. workbook = null;
  242. ms.Close();
  243. ms.Dispose();
  244. curContext.Response.End();
  245. }
  246. //}
  247. return "";
  248. }
  249. catch
  250. {
  251. return "导出失败!";
  252. }
  253. }
  254. /// <summary>
  255. /// 导入excel转换为datatable
  256. /// </summary>
  257. /// <param name="upfile"></param>
  258. /// <param name="headrow"></param>
  259. /// <returns></returns>
  260. public DataTable ExcelToTable(HttpPostedFileBase upfile, int headrow)
  261. {
  262. DataTable dt = new DataTable();
  263. IWorkbook workbook = null;
  264. Stream stream = upfile.InputStream;
  265. string suffix = upfile.FileName.Substring(upfile.FileName.LastIndexOf(".") + 1).ToLower();
  266. if (suffix == "xlsx") // 2007版本
  267. {
  268. workbook = new XSSFWorkbook(stream);
  269. }
  270. else if (suffix == "xls") // 2003版本
  271. {
  272. workbook = new HSSFWorkbook(stream);
  273. }
  274. //获取excel的第一个sheet
  275. ISheet sheet = workbook.GetSheetAt(0);
  276. //获取sheet的第一行
  277. IRow headerRow = sheet.GetRow(headrow);
  278. //一行最后一个方格的编号 即总的列数
  279. int cellCount = headerRow.LastCellNum;
  280. //最后一列的标号 即总的行数
  281. int rowCount = sheet.LastRowNum;
  282. //列名
  283. for (int i = 0; i < cellCount; i++)
  284. {
  285. dt.Columns.Add(headerRow.GetCell(i).ToString());
  286. }
  287. for (int i = (sheet.FirstRowNum + headrow + 1); i <= sheet.LastRowNum; i++)
  288. {
  289. DataRow dr = dt.NewRow();
  290. IRow row = sheet.GetRow(i);
  291. for (int j = row.FirstCellNum; j < cellCount; j++)
  292. {
  293. if (row.GetCell(j) != null)
  294. {
  295. dr[j] = row.GetCell(j).ToString();
  296. }
  297. }
  298. dt.Rows.Add(dr);
  299. }
  300. sheet = null;
  301. workbook = null;
  302. return dt;
  303. }
  304. }
  305. }