ExcelHelper.T.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  1. using NPOI.HPSF;
  2. using NPOI.HSSF.UserModel;
  3. using NPOI.SS.UserModel;
  4. using System.Data;
  5. using System.IO;
  6. using System.Text;
  7. using System.Web;
  8. using System.Drawing;
  9. using NPOI.HSSF.Util;
  10. using System;
  11. using System.Collections;
  12. using System.Collections.Generic;
  13. using System.Reflection;
  14. namespace LeaRun.Util.Offices
  15. {
  16. /// <summary>
  17. ///版 本 V1.0
  18. ///Copyright (c) 2010-2015 上海力软信息技术有限公司                          
  19. ///创建人:刘晓雷
  20. ///日 期:2015/11/25
  21. ///描 述:NPOI Excel泛型操作类
  22. public class ExcelHelper<T>
  23. {
  24. #region Excel导出方法 ExcelDownload
  25. /// <summary>
  26. /// Excel导出下载
  27. /// </summary>
  28. /// <param name="lists">List<T>数据源</param>
  29. /// <param name="excelConfig">导出设置包含文件名、标题、列设置</param>
  30. public static void ExcelDownload(List<T> lists, ExcelConfig excelConfig)
  31. {
  32. HttpContext curContext = HttpContext.Current;
  33. // 设置编码和附件格式
  34. curContext.Response.ContentType = "application/ms-excel";
  35. curContext.Response.ContentEncoding = Encoding.UTF8;
  36. curContext.Response.Charset = "";
  37. curContext.Response.AppendHeader("Content-Disposition",
  38. "attachment;filename=" + HttpUtility.UrlEncode(excelConfig.FileName, Encoding.UTF8));
  39. //调用导出具体方法Export()
  40. curContext.Response.BinaryWrite(ExportMemoryStream(lists, excelConfig).GetBuffer());
  41. curContext.Response.End();
  42. }
  43. #endregion
  44. #region DataTable导出到Excel文件excelConfig中FileName设置为全路径
  45. /// <summary>
  46. /// List<T>导出到Excel文件 ExcelImport
  47. /// </summary>
  48. /// <param name="lists">List<T>数据源</param>
  49. /// <param name="excelConfig">导出设置包含文件名、标题、列设置</param>
  50. public static void ExcelImport(List<T> lists, ExcelConfig excelConfig)
  51. {
  52. using (MemoryStream ms = ExportMemoryStream(lists, excelConfig))
  53. {
  54. using (FileStream fs = new FileStream(excelConfig.FileName, FileMode.Create, FileAccess.Write))
  55. {
  56. byte[] data = ms.ToArray();
  57. fs.Write(data, 0, data.Length);
  58. fs.Flush();
  59. }
  60. }
  61. }
  62. #endregion
  63. #region DataTable导出到Excel的MemoryStream
  64. /// <summary>
  65. /// DataTable导出到Excel的MemoryStream Export()
  66. /// </summary>
  67. /// <param name="dtSource">DataTable数据源</param>
  68. /// <param name="excelConfig">导出设置包含文件名、标题、列设置</param>
  69. public static MemoryStream ExportMemoryStream(List<T> lists, ExcelConfig excelConfig)
  70. {
  71. HSSFWorkbook workbook = new HSSFWorkbook();
  72. ISheet sheet = workbook.CreateSheet();
  73. Type type = typeof(T);
  74. PropertyInfo[] properties = type.GetProperties();
  75. #region 右击文件 属性信息
  76. {
  77. DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();
  78. dsi.Company = "NPOI";
  79. workbook.DocumentSummaryInformation = dsi;
  80. SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
  81. si.Author = "刘晓雷"; //填加xls文件作者信息
  82. si.ApplicationName = "力软信息"; //填加xls文件创建程序信息
  83. si.LastAuthor = "刘晓雷"; //填加xls文件最后保存者信息
  84. si.Comments = "刘晓雷"; //填加xls文件作者信息
  85. si.Title = "标题信息"; //填加xls文件标题信息
  86. si.Subject = "主题信息";//填加文件主题信息
  87. si.CreateDateTime = System.DateTime.Now;
  88. workbook.SummaryInformation = si;
  89. }
  90. #endregion
  91. #region 设置标题样式
  92. ICellStyle headStyle = workbook.CreateCellStyle();
  93. int[] arrColWidth = new int[properties.Length];
  94. string[] arrColName = new string[properties.Length];//列名
  95. ICellStyle[] arryColumStyle = new ICellStyle[properties.Length];//样式表
  96. headStyle.Alignment = HorizontalAlignment.Center; // ------------------
  97. if (excelConfig.Background != new Color())
  98. {
  99. if (excelConfig.Background != new Color())
  100. {
  101. headStyle.FillPattern = FillPattern.SolidForeground;
  102. headStyle.FillForegroundColor = GetXLColour(workbook, excelConfig.Background);
  103. }
  104. }
  105. IFont font = workbook.CreateFont();
  106. font.FontHeightInPoints = excelConfig.TitlePoint;
  107. if (excelConfig.ForeColor != new Color())
  108. {
  109. font.Color = GetXLColour(workbook, excelConfig.ForeColor);
  110. }
  111. font.Boldweight = 700;
  112. headStyle.SetFont(font);
  113. #endregion
  114. #region 列头及样式
  115. ICellStyle cHeadStyle = workbook.CreateCellStyle();
  116. cHeadStyle.Alignment = HorizontalAlignment.Center; // ------------------
  117. IFont cfont = workbook.CreateFont();
  118. cfont.FontHeightInPoints = excelConfig.HeadPoint;
  119. cHeadStyle.SetFont(cfont);
  120. #endregion
  121. #region 设置内容单元格样式
  122. int i = 0;
  123. foreach (PropertyInfo column in properties)
  124. {
  125. ICellStyle columnStyle = workbook.CreateCellStyle();
  126. columnStyle.Alignment = HorizontalAlignment.Center;
  127. arrColWidth[i] = Encoding.GetEncoding(936).GetBytes(column.Name).Length;
  128. arrColName[i] = column.Name;
  129. if (excelConfig.ColumnEntity != null)
  130. {
  131. ColumnEntity columnentity = excelConfig.ColumnEntity.Find(t => t.Column == column.Name);
  132. if (columnentity != null)
  133. {
  134. arrColName[i] = columnentity.ExcelColumn;
  135. if (columnentity.Width != 0)
  136. {
  137. arrColWidth[i] = columnentity.Width;
  138. }
  139. if (columnentity.Background != new Color())
  140. {
  141. if (columnentity.Background != new Color())
  142. {
  143. columnStyle.FillPattern = FillPattern.SolidForeground;
  144. columnStyle.FillForegroundColor = GetXLColour(workbook, columnentity.Background);
  145. }
  146. }
  147. if (columnentity.Font != null || columnentity.Point != 0 || columnentity.ForeColor != new Color())
  148. {
  149. IFont columnFont = workbook.CreateFont();
  150. columnFont.FontHeightInPoints = 10;
  151. if (columnentity.Font != null)
  152. {
  153. columnFont.FontName = columnentity.Font;
  154. }
  155. if (columnentity.Point != 0)
  156. {
  157. columnFont.FontHeightInPoints = columnentity.Point;
  158. }
  159. if (columnentity.ForeColor != new Color())
  160. {
  161. columnFont.Color = GetXLColour(workbook, columnentity.ForeColor);
  162. }
  163. columnStyle.SetFont(font);
  164. }
  165. }
  166. }
  167. arryColumStyle[i] = columnStyle;
  168. i++;
  169. }
  170. #endregion
  171. #region 填充数据
  172. #endregion
  173. ICellStyle dateStyle = workbook.CreateCellStyle();
  174. IDataFormat format = workbook.CreateDataFormat();
  175. dateStyle.DataFormat = format.GetFormat("yyyy-mm-dd");
  176. int rowIndex = 0;
  177. foreach (T item in lists)
  178. {
  179. #region 新建表,填充表头,填充列头,样式
  180. if (rowIndex == 65535 || rowIndex == 0)
  181. {
  182. if (rowIndex != 0)
  183. {
  184. sheet = workbook.CreateSheet();
  185. }
  186. #region 表头及样式
  187. {
  188. if (excelConfig.Title != null)
  189. {
  190. IRow headerRow = sheet.CreateRow(0);
  191. if (excelConfig.TitleHeight != 0)
  192. {
  193. headerRow.Height = (short)(excelConfig.TitleHeight * 20);
  194. }
  195. headerRow.HeightInPoints = 25;
  196. headerRow.CreateCell(0).SetCellValue(excelConfig.Title);
  197. headerRow.GetCell(0).CellStyle = headStyle;
  198. sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(0, 0, 0, lists.Count - 1)); // ------------------
  199. }
  200. }
  201. #endregion
  202. #region 列头及样式
  203. {
  204. IRow headerRow = sheet.CreateRow(1);
  205. #region 如果设置了列标题就按列标题定义列头,没定义直接按字段名输出
  206. int headIndex = 0;
  207. foreach (PropertyInfo column in properties)
  208. {
  209. headerRow.CreateCell(headIndex).SetCellValue(arrColName[headIndex]);
  210. headerRow.GetCell(headIndex).CellStyle = cHeadStyle;
  211. //设置列宽
  212. sheet.SetColumnWidth(headIndex, (arrColWidth[headIndex] + 1) * 256);
  213. headIndex++;
  214. }
  215. #endregion
  216. }
  217. #endregion
  218. rowIndex = 2;
  219. }
  220. #endregion
  221. #region 填充内容
  222. IRow dataRow = sheet.CreateRow(rowIndex);
  223. int ordinal = 0;
  224. foreach (PropertyInfo column in properties)
  225. {
  226. ICell newCell = dataRow.CreateCell(ordinal);
  227. newCell.CellStyle = arryColumStyle[ordinal];
  228. string drValue = column.GetValue(item, null) == null ? "" : column.GetValue(item, null).ToString();
  229. SetCell(newCell, dateStyle, column.PropertyType, drValue);
  230. ordinal++;
  231. }
  232. #endregion
  233. rowIndex++;
  234. }
  235. using (MemoryStream ms = new MemoryStream())
  236. {
  237. workbook.Write(ms);
  238. ms.Flush();
  239. ms.Position = 0;
  240. return ms;
  241. }
  242. }
  243. #endregion
  244. #region 设置表格内容
  245. private static void SetCell(ICell newCell, ICellStyle dateStyle, Type dataType, string drValue)
  246. {
  247. switch (dataType.ToString())
  248. {
  249. case "System.String"://字符串类型
  250. newCell.SetCellValue(drValue);
  251. break;
  252. case "System.DateTime"://日期类型
  253. System.DateTime dateV;
  254. if (System.DateTime.TryParse(drValue, out dateV))
  255. {
  256. newCell.SetCellValue(dateV);
  257. }
  258. else
  259. {
  260. newCell.SetCellValue("");
  261. }
  262. newCell.CellStyle = dateStyle;//格式化显示
  263. break;
  264. case "System.Boolean"://布尔型
  265. bool boolV = false;
  266. bool.TryParse(drValue, out boolV);
  267. newCell.SetCellValue(boolV);
  268. break;
  269. case "System.Int16"://整型
  270. case "System.Int32":
  271. case "System.Int64":
  272. case "System.Byte":
  273. int intV = 0;
  274. int.TryParse(drValue, out intV);
  275. newCell.SetCellValue(intV);
  276. break;
  277. case "System.Decimal"://浮点型
  278. case "System.Double":
  279. double doubV = 0;
  280. double.TryParse(drValue, out doubV);
  281. newCell.SetCellValue(doubV);
  282. break;
  283. case "System.DBNull"://空值处理
  284. newCell.SetCellValue("");
  285. break;
  286. default:
  287. newCell.SetCellValue("");
  288. break;
  289. }
  290. }
  291. #endregion
  292. #region 读取excel ,默认第一行为标头
  293. /// <summary>
  294. /// 导入Excel
  295. /// </summary>
  296. /// <param name="lists"></param>
  297. /// <param name="head">中文列名对照</param>
  298. /// <param name="workbookFile">Excel所在路径</param>
  299. /// <returns></returns>
  300. public List<T> ExcelImport(Hashtable head, string workbookFile)
  301. {
  302. try
  303. {
  304. HSSFWorkbook hssfworkbook;
  305. List<T> lists = new List<T>();
  306. using (FileStream file = new FileStream(workbookFile, FileMode.Open, FileAccess.Read))
  307. {
  308. hssfworkbook = new HSSFWorkbook(file);
  309. }
  310. HSSFSheet sheet = hssfworkbook.GetSheetAt(0) as HSSFSheet;
  311. IEnumerator rows = sheet.GetRowEnumerator();
  312. HSSFRow headerRow = sheet.GetRow(0) as HSSFRow;
  313. int cellCount = headerRow.LastCellNum;
  314. //Type type = typeof(T);
  315. PropertyInfo[] properties;
  316. T t = default(T);
  317. for (int i = sheet.FirstRowNum + 1; i <= sheet.LastRowNum; i++)
  318. {
  319. HSSFRow row = sheet.GetRow(i) as HSSFRow;
  320. t = Activator.CreateInstance<T>();
  321. properties = t.GetType().GetProperties();
  322. foreach (PropertyInfo column in properties)
  323. {
  324. int j = headerRow.Cells.FindIndex(delegate(ICell c)
  325. {
  326. return c.StringCellValue == (head[column.Name] == null ? column.Name : head[column.Name].ToString());
  327. });
  328. if (j >= 0 && row.GetCell(j) != null)
  329. {
  330. object value = valueType(column.PropertyType, row.GetCell(j).ToString());
  331. column.SetValue(t, value, null);
  332. }
  333. }
  334. lists.Add(t);
  335. }
  336. return lists;
  337. }
  338. catch (Exception ee)
  339. {
  340. string see = ee.Message;
  341. return null;
  342. }
  343. }
  344. #endregion
  345. #region RGB颜色转NPOI颜色
  346. private static short GetXLColour(HSSFWorkbook workbook, Color SystemColour)
  347. {
  348. short s = 0;
  349. HSSFPalette XlPalette = workbook.GetCustomPalette();
  350. NPOI.HSSF.Util.HSSFColor XlColour = XlPalette.FindColor(SystemColour.R, SystemColour.G, SystemColour.B);
  351. if (XlColour == null)
  352. {
  353. if (NPOI.HSSF.Record.PaletteRecord.STANDARD_PALETTE_SIZE < 255)
  354. {
  355. XlColour = XlPalette.FindSimilarColor(SystemColour.R, SystemColour.G, SystemColour.B);
  356. s = XlColour.Indexed;
  357. }
  358. }
  359. else
  360. s = XlColour.Indexed;
  361. return s;
  362. }
  363. #endregion
  364. object valueType(Type t, string value)
  365. {
  366. object o = null;
  367. string strt = "String";
  368. if (t.Name == "Nullable`1")
  369. {
  370. strt = t.GetGenericArguments()[0].Name;
  371. }
  372. switch (strt)
  373. {
  374. case "Decimal":
  375. o = decimal.Parse(value);
  376. break;
  377. case "Int":
  378. o = int.Parse(value);
  379. break;
  380. case "Float":
  381. o = float.Parse(value);
  382. break;
  383. case "DateTime":
  384. o = DateTime.Parse(value);
  385. break;
  386. default:
  387. o = value;
  388. break;
  389. }
  390. return o;
  391. }
  392. }
  393. }