ExcelHelper.T.cs 17 KB

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