前言:

本人调式npoi导入、导出试用成功后,引入到项目中,导入完美运行,但是导出怎么样都看不到现在的页面,而且浏览器和后台都没有报任务错误,让人好事纳闷,后来去调式,发现在除了一个IsReadOnly = “book.IsReadOnly”引发了类型“System.NotImplementedException”的异常)。最开始的怀疑是这里问题,然后去调式环境看也是存在的,然后就自然想到的前端问题。最后果然是前端出了问题,在导出的点击函数里写了异步ajax蠢死了,后来异步ajax改成  完美导出。

NPOI 常用本版本下载:

http://download.csdn.net/detail/whk311/6465879

mynpoi导入导出封装:

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using NPOI.SS.UserModel;
  6. using NPOI.HSSF.UserModel;
  7. using NPOI.HSSF.Util;
  8. using System.IO;
  9. using NPOI.HPSF;
  10. using System.Web;
  11. using Newtonsoft.Json.Linq;
  12. using Newtonsoft.Json;
  13. using System.Collections;
  14. using NPOI.SS.Util;
  15. using System.Drawing;
  16. using System.Data;
  17. using System.Reflection;
  18. using System.Linq.Expressions;
  19. using GTJ.Utility.MyNPOI;
  20.  
  21. namespace MyNPOI.Excel
  22. {
  23. internal class ExcelHelper
  24. {
  25. #region "构造函数"
  26. internal ExcelHelper() { }
  27. #endregion
  28.  
  29. #region "私有字段"
  30. /// <summary>
  31. /// 自定义颜色
  32. /// </summary>
  33. HSSFPalette XlPalette = null;
  34. /// <summary>
  35. /// 要导出的excel对象
  36. /// </summary>
  37. private HSSFWorkbook workbook = null;
  38. /// <summary>
  39. /// 要导出的excel对象属性
  40. /// </summary>
  41. private HSSFWorkbook Workbook
  42. {
  43. get
  44. {
  45. if (workbook == null)
  46. {
  47. workbook = new HSSFWorkbook();
  48. }
  49. return workbook;
  50. }
  51. set { workbook = value; }
  52. }
  53. /// <summary>
  54. /// 要导出的excel对象中的一个表
  55. /// </summary>
  56. private ISheet sheet = null;
  57. /// <summary>
  58. /// 导出的内容部分的样式
  59. /// </summary>
  60. HSSFCellStyle cellStyle = null;
  61. /// <summary>
  62. /// 表头行数
  63. /// </summary>
  64. int rowHeadNum = ;
  65. /// <summary>
  66. /// 行数,方便内容正确在行插入
  67. /// </summary>
  68. private List<IRow> rowList = new List<IRow>();
  69.  
  70. private List<GroupClass> gCell = null;
  71. private List<GroupClass> GCell
  72. {
  73. get { return gCell; }
  74. set { gCell = value; }
  75. }
  76.  
  77. /// <summary>
  78. /// 整个表格border样式,默认solid
  79. /// </summary>
  80. private BorderStyle wholeBorderStyle = BorderStyle.Thin;
  81. private BorderStyle WholeBorderStyle
  82. {
  83. get { return wholeBorderStyle; }
  84. set { wholeBorderStyle = value; }
  85. }
  86. /// <summary>
  87. /// 整个表格border颜色,默认黑色
  88. /// </summary>
  89. private short wholeBorderColor = HSSFColor.Black.Index;
  90. public short WholeBorderColor
  91. {
  92. get { return wholeBorderColor; }
  93. set { wholeBorderColor = value; }
  94. }
  95. /// <summary>
  96. /// 表头单元格字体是否加粗
  97. /// </summary>
  98. private short headFontWeight = (short)FontBoldWeight.Bold;
  99. /// <summary>
  100. /// 表头单元格字体是否加粗
  101. /// </summary>
  102. public short HeadFontWeight
  103. {
  104. get { return headFontWeight; }
  105. set { headFontWeight = value; }
  106. }
  107.  
  108. #endregion
  109.  
  110. /// <summary>
  111. /// 创建表头
  112. /// </summary>
  113. /// <param name="json">类似json的字符串</param>
  114. internal void SetHead(string json,List<GroupClass> group,int column)
  115. {
  116. Root T =Utility.JsonUtility.DecodeObject<Root>(json);
  117. //确定表头行数
  118. if (group != null && column > -)
  119. {
  120. int headRow = T.root.rowspan.Value;
  121. int indexs = headRow;
  122. foreach (var item in group)
  123. {
  124. item.column = column;
  125. if (indexs == headRow)
  126. {
  127. item.index = headRow;
  128. }
  129. else
  130. {
  131. item.index = indexs;
  132. }
  133. indexs = item.index.Value + item.groupCount.Value;
  134. }
  135. SetGroupCell(group);
  136. }
  137. if (sheet == null)
  138. {
  139. sheet = Workbook.CreateSheet(T.root.sheetname);
  140. }
  141. sheet.DisplayGridlines = true;
  142. if (T.root.defaultwidth.HasValue)
  143. {
  144. //设置表格默认宽高
  145. sheet.DefaultColumnWidth = T.root.defaultwidth.Value; //
  146. }
  147. if (T.root.defaultheight.HasValue)
  148. {
  149. //设置表格默认行高
  150. sheet.DefaultRowHeight = (short)T.root.defaultheight.Value; //
  151. }
  152. if (!string.IsNullOrEmpty(T.root.borderstyle))
  153. {
  154. string bStyle = T.root.borderstyle.Trim();
  155. if (!string.IsNullOrEmpty(bStyle))
  156. {
  157. switch (bStyle)
  158. {
  159. case "none":
  160. WholeBorderStyle = BorderStyle.None;
  161. break;
  162. case "solid":
  163. WholeBorderStyle = BorderStyle.Thin;
  164. break;
  165. case "dashed":
  166. WholeBorderStyle = BorderStyle.Dashed;
  167. break;
  168. case "dotted":
  169. WholeBorderStyle = BorderStyle.Dotted;
  170. break;
  171. case "double":
  172. WholeBorderStyle = BorderStyle.Double;
  173. break;
  174. default:
  175. WholeBorderStyle = BorderStyle.Thin;
  176. break;
  177. }
  178. }
  179. }
  180. XlPalette = Workbook.GetCustomPalette();
  181. if (!string.IsNullOrEmpty(T.root.bordercolor))
  182. {
  183. Color co = ColorTranslator.FromHtml(T.root.bordercolor);
  184. XlPalette.SetColorAtIndex(HSSFColor.Plum.Index, (byte)co.R, (byte)co.G, (byte)co.B);
  185. WholeBorderColor = NPOI.HSSF.Util.HSSFColor.Plum.Index;//这句代码根据16进制不起作用,起到颜色初始化
  186. }
  187.  
  188. int rowN = Convert.ToInt32(T.root.rowspan);
  189. rowHeadNum = rowN ;
  190. //创建行
  191. for (int i = ; i < rowN; i++)
  192. {
  193. IRow temp = sheet.CreateRow(i);
  194. rowList.Add(temp);
  195.  
  196. }
  197. //合并单元格
  198. //填充内容
  199. for (int i = ; i < T.root.head.Count; i++)
  200. {
  201. //读取最重要的区域,0=fromRow,1=toRow,2=fromColumn,3=toColumn
  202. AttributeList al = T.root.head[i];
  203. int[] c = al.cellregion.Split(',').ToIntArray();
  204. if (c[] < c[] || c[] < c[]) //例如1,1,2,2 第二行中的第3列,例如1,1,2,7 第二行中的(第3列到8列),合并列
  205. {
  206. CellRangeAddress cellr = new CellRangeAddress(c[], c[], c[], c[]);
  207. sheet.AddMergedRegion(cellr);
  208. //设置边框
  209. ((HSSFSheet)sheet).SetEnclosedBorderOfRegion(cellr, WholeBorderStyle, WholeBorderColor);
  210. }
  211. }
  212. //填充内容
  213. for (int i = ; i < T.root.head.Count; i++)
  214. {
  215. //读取最重要的区域,0=fromRow,1=toRow,2=fromColumn,3=toColumn
  216. AttributeList al = T.root.head[i];
  217. int[] c = al.cellregion.Split(',').ToIntArray();
  218. //计算title要插入的位置的索引
  219. int txtIndex = -;
  220. int txtRow = -;
  221.  
  222. if ((c[] == c[] && c[] == c[]) || (c[] == c[] && c[] < c[]))
  223. { //例如1,1,2,2 第二行中的第3列,例如1,1,2,7 第二行中的(第3列到8列)
  224. txtIndex = c[];
  225. txtRow = c[];
  226. ICell cell1 = rowList[txtRow].CreateCell(txtIndex);
  227.  
  228. //设置单元格的高度
  229. if (!T.root.defaultheight.HasValue&& al.height.HasValue)
  230. {
  231. rowList[txtRow].HeightInPoints = (short)al.height.Value ;
  232. }
  233. SetHeadCellBold(al);
  234. cell1.SetCellValue(al.title);
  235. cell1.CellStyle = SetCellStyle(al);
  236.  
  237. }
  238. if (c[] < c[] && c[] == c[]) //合并c[0]到c[1]行 ,列没变 , 'cellregion':'0,1,1,1',
  239. {
  240. txtIndex = c[];
  241. txtRow = c[];
  242. ICell cell1 = rowList[txtRow].CreateCell(txtIndex);
  243. //设置单元格的高度
  244. if (!T.root.defaultheight.HasValue && al.height.HasValue)
  245. {
  246. rowList[txtRow].Height = (short)(al.height.Value * );
  247. }
  248. SetHeadCellBold(al);
  249. cell1.SetCellValue(al.title);
  250. cell1.CellStyle = SetCellStyle(al);
  251. }
  252. if (c[] < c[] && c[] < c[]) //合并c[0]到c[1]行 ,列没变 , 'cellregion':'4,5,2,4',
  253. {
  254. txtIndex = c[];
  255. txtRow = c[];
  256. ICell cell1 = rowList[txtRow].CreateCell(txtIndex);
  257. SetHeadCellBold(al);
  258. //设置单元格的高度
  259. if (!T.root.defaultheight.HasValue && al.height.HasValue)
  260. {
  261. rowList[txtRow].Height = (short)(al.height.Value * );
  262. }
  263. cell1.SetCellValue(al.title);
  264. cell1.CellStyle = SetCellStyle(al);
  265. }
  266.  
  267. //设置单元格的宽度
  268. if (!T.root.defaultwidth.HasValue && al.width.HasValue)
  269. {
  270. sheet.SetColumnWidth(i, al.width.Value * );
  271. }
  272. }
  273.  
  274. }
  275. /// <summary>
  276. /// 设置表头单元格字体是否加粗,默认加粗
  277. /// </summary>
  278. /// <param name="al"></param>
  279. private void SetHeadCellBold(AttributeList al)
  280. {
  281. if (string.IsNullOrEmpty(al.fontweight)) {
  282. HeadFontWeight = (short)FontBoldWeight.Bold;
  283. }
  284. else
  285. {
  286. switch (al.fontweight)
  287. {
  288. case "bold":
  289. HeadFontWeight = (short)FontBoldWeight.Bold;
  290. break;
  291. case "none":
  292. HeadFontWeight = (short)FontBoldWeight.None;
  293. break;
  294. case "normal":
  295. HeadFontWeight = (short)FontBoldWeight.Normal;
  296. break;
  297. default:
  298. HeadFontWeight = (short)FontBoldWeight.Bold;
  299. break;
  300. }
  301. }
  302. }
  303.  
  304. /// <summary>
  305. /// web导出excel
  306. /// </summary>
  307. /// <typeparam name="T">实体类</typeparam>
  308. /// <param name="list">导出的列表对象</param>
  309. /// <param name="fileName">文件名称</param>
  310. /// <param name="titles">标题</param>
  311. /// <param name="fieldFuncs">字段委托,如果不传则T的全部属性</param>
  312. internal void ExportToWeb<T>(List<T> list, string fileName, string[] titles, string headJson, params Func<T, string>[] fieldFuncs)
  313. {
  314. ///创建表头
  315. SetHead(headJson,null,-);
  316. ///转换数据源
  317. DataTable dtSource = list.ToDataTable(titles, fieldFuncs);
  318. ///开始导出
  319. WebCommonExport(dtSource, fileName);
  320. System.GC.Collect();
  321. }
  322. /// <summary>
  323. /// web导出excel
  324. /// </summary>
  325. /// <typeparam name="T">实体类</typeparam>
  326. /// <param name="list">导出的列表对象</param>
  327. /// <param name="fileName">文件名称</param>
  328. /// <param name="titles">标题</param>
  329. /// <param name="fieldFuncs">字段委托,如果不传则T的全部属性</param>
  330. internal void ExportToWeb<T>(List<T> list, string fileName, string[] titles, string headJson,List<GroupClass> group,int groupColumn,params Func<T, string>[] fieldFuncs)
  331. {
  332. ///创建表头
  333. SetHead(headJson, group,groupColumn);
  334. ///转换数据源
  335. DataTable dtSource = list.ToDataTable(titles, fieldFuncs);
  336. ///开始导出
  337. WebCommonExport(dtSource, fileName);
  338. System.GC.Collect();
  339. }
  340.  
  341. /// <summary>
  342. /// 保存到本地
  343. /// </summary>
  344. /// <typeparam name="T">实体类</typeparam>
  345. /// <param name="list">导出的列表对象</param>
  346. /// <param name="fileName">文件名称</param>
  347. /// <param name="titles">标题</param>
  348. /// <param name="fieldFuncs">字段委托,如果不传则T的全部属性</param>
  349. internal void ExportToLocal<T>(List<T> list, string fileName, string[] titles, string headJson, params Func<T, string>[] fieldFuncs)
  350. {
  351. ///创建表头
  352. SetHead(headJson, null, -);
  353. ///转换数据源
  354. DataTable dtSource = list.ToDataTable(titles, fieldFuncs);
  355. ///开始导出
  356. LocalCommonExport(dtSource, fileName);
  357. System.GC.Collect();
  358. }
  359. /// <summary>
  360. /// 保存到本地
  361. /// </summary>
  362. /// <typeparam name="T">实体类</typeparam>
  363. /// <param name="list">导出的列表对象</param>
  364. /// <param name="fileName">文件名称</param>
  365. /// <param name="titles">标题</param>
  366. /// <param name="fieldFuncs">字段委托,如果不传则T的全部属性</param>
  367. internal void ExportToLocal<T>(List<T> list, string fileName, string[] titles, string headJson, List<GroupClass> group, int groupColumn, params Func<T, string>[] fieldFuncs)
  368. {
  369. ///创建表头
  370. SetHead(headJson, group,groupColumn);
  371. ///转换数据源
  372. DataTable dtSource = list.ToDataTable(titles, fieldFuncs);
  373. ///开始导出
  374. LocalCommonExport(dtSource, fileName);
  375. System.GC.Collect();
  376. }
  377. /// DataTable导出到Excel的MemoryStream,#CommonExport,全部都是字符串处理
  378. /// </summary>
  379. /// <param name="dtSource">源DataTable</param>
  380. /// <param name="strHeaderText">表头文本</param>
  381. internal void WebCommonExport(DataTable dtSource, string fileName)
  382. {
  383. BeforeExport(dtSource);
  384. //转换好后开始提供下载
  385. Workbook.ExportToWeb(fileName);
  386. }
  387.  
  388. /// DataTable导出到Excel的MemoryStream,#CommonExport,全部都是字符串处理
  389. /// </summary>
  390. /// <param name="dtSource">源DataTable</param>
  391. /// <param name="fileName">文件存储路径</param>
  392. ///
  393. internal void LocalCommonExport(DataTable dtSource, string fileName)
  394. {
  395. BeforeExport(dtSource);
  396. //转换好后开始保存本地
  397. Workbook.ExportToLocal(fileName);
  398. }
  399.  
  400. /// <summary>
  401. /// 整合数据
  402. /// </summary>
  403. /// <param name="dtSource"></param>
  404. private void BeforeExport(DataTable dtSource)
  405. {
  406. HSSFCellStyle dateStyle = (HSSFCellStyle)Workbook.CreateCellStyle();
  407. cellStyle = SetContentFormat(, );
  408. //取得列宽
  409. int[] arrColWidth = new int[dtSource.Columns.Count];
  410. foreach (DataColumn item in dtSource.Columns)
  411. {
  412. arrColWidth[item.Ordinal] = Encoding.GetEncoding().GetBytes(item.ColumnName.ToString()).Length;
  413. }
  414. for (int i = ; i < dtSource.Rows.Count; i++)
  415. {
  416. for (int j = ; j < dtSource.Columns.Count; j++)
  417. {
  418. int intTemp = Encoding.GetEncoding().GetBytes(dtSource.Rows[i][j].ToString()).Length;
  419. if (intTemp > arrColWidth[j])
  420. {
  421. arrColWidth[j] = intTemp;
  422. }
  423. }
  424. }
  425. int rowIndex = rowList.Count();
  426. dtSource.Rows.RemoveAt(); //移除第一行,因为有表头了
  427.  
  428. foreach (DataRow row in dtSource.Rows)
  429. {
  430. IRow dataRow = sheet.CreateRow(rowIndex);
  431. foreach (DataColumn column in dtSource.Columns)
  432. {
  433. ICell newCell = dataRow.CreateCell(column.Ordinal);
  434. newCell.CellStyle = cellStyle;
  435. string drValue = row[column].ToString();
  436. newCell.SetCellValue(drValue);
  437.  
  438. }
  439. rowIndex++;
  440. }
  441.  
  442. try
  443. {
  444. int temp = ;
  445. if (GCell != null && dtSource.Rows.Count > )
  446. {
  447. foreach (GroupClass gCell in GCell)
  448. {
  449.  
  450. IRow row = sheet.GetRow(gCell.index.Value);//获取工作表第一行
  451. ICell cell = row.GetCell(gCell.column);//获取行的第COLUMN列
  452. string cellValue = cell.ToString();//获取列的值
  453. //如果设置了分组,目前只能一种
  454. temp=gCell.index.Value+gCell.groupCount.Value-;
  455. CellRangeAddress cellr = new CellRangeAddress(gCell.index.Value, temp, gCell.column, gCell.column);
  456. sheet.AddMergedRegion(cellr);
  457. //设置边框
  458. ((HSSFSheet)sheet).SetEnclosedBorderOfRegion(cellr, WholeBorderStyle, WholeBorderColor);
  459. ICell ce = row.CreateCell(gCell.column);
  460. ce.CellStyle = cellStyle;
  461. ce.SetCellValue(cellValue);
  462. }
  463. }
  464. }
  465. catch
  466. {
  467. throw new Exception("GroupCell某些属性可能为空了!");
  468. }
  469.  
  470. }
  471.  
  472. #region 辅助帮助,设置样式和 转换颜色
  473. static bool cellColorBug = true; //关于NPOI自定义颜色设置有个bug,这个可以保证第一次单元格设置不会始终黑色
  474. /// <summary>
  475. /// 设置单元格基本样式
  476. /// </summary>
  477. /// <param name="al"></param>
  478. private HSSFCellStyle SetCellStyle(AttributeList al)
  479. {
  480. HSSFCellStyle headStyle = (HSSFCellStyle)Workbook.CreateCellStyle();
  481. XlPalette = Workbook.GetCustomPalette();
  482. headStyle.Alignment = string.IsNullOrEmpty(al.align) ? HorizontalAlignment.Center : al.align.ToHorAlign(); //默认水平居中
  483. headStyle.VerticalAlignment = string.IsNullOrEmpty(al.valign) ? VerticalAlignment.Center : al.valign.ToVerAlign();//垂直居中
  484. headStyle.FillPattern = FillPattern.SolidForeground; //默认填充整个背景颜色
  485. bool forc = string.IsNullOrEmpty(al.bgcolor); //是否有背景颜色
  486. if (forc)
  487. {
  488. headStyle.FillForegroundColor = HSSFColor.Grey25Percent.Index; //默认灰色
  489. }
  490. else
  491. {
  492. headStyle.FillForegroundColor = GetColorIndex(Workbook, al.bgcolor);//这句代码根据16进制不起作用,起到颜色初始化
  493. if (cellColorBug)
  494. {
  495. Color co = ColorTranslator.FromHtml(al.bgcolor);
  496. XlPalette.SetColorAtIndex(HSSFColor.Pink.Index, (byte)co.R, (byte)co.G, (byte)co.B);
  497. headStyle.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.Pink.Index;
  498. cellColorBug = false;
  499. }
  500. }
  501.  
  502. //设置单元格border
  503. headStyle.BorderRight = headStyle.BorderLeft = headStyle.BorderBottom = headStyle.BorderTop = WholeBorderStyle;
  504. headStyle.BottomBorderColor = headStyle.RightBorderColor = headStyle.LeftBorderColor = headStyle.TopBorderColor = WholeBorderColor;
  505. bool fontc = string.IsNullOrEmpty(al.fontcolor); //是否有字体颜色
  506. //设置单元格字体
  507. HSSFFont font = (HSSFFont)Workbook.CreateFont();
  508. if (fontc)
  509. {
  510. font.Color = ; //默认黑色
  511. }
  512. else
  513. {
  514. font.Color = GetColorIndex(Workbook, al.fontcolor);//这句代码根据16进制不起作用,起到颜色初始化
  515. if (cellColorBug)
  516. {
  517. Color co = ColorTranslator.FromHtml(al.fontcolor);
  518. XlPalette.SetColorAtIndex(HSSFColor.Pink.Index, (byte)co.R, (byte)co.G, (byte)co.B);
  519. font.Color = NPOI.HSSF.Util.HSSFColor.Pink.Index;
  520. cellColorBug = false;
  521. }
  522. }
  523.  
  524. font.FontHeightInPoints = al.fontsize ?? ; //设置字体大小
  525. font.Boldweight =HeadFontWeight;
  526. font.FontName = string.IsNullOrWhiteSpace(al.fontName) ? "宋体" : al.fontName;//设置字体为宋体
  527. font.IsItalic = al.IsItalic.HasValue && al.IsItalic.Value ? true : false;//是否是斜体
  528. font.IsStrikeout = al.IsStrikeout.HasValue && al.IsStrikeout.Value ? true : false;//是否有中间线
  529. font.Underline = al.Underline.HasValue && al.Underline.Value ? FontUnderlineType.Single :FontUnderlineType.None;//设置下划线
  530. headStyle.SetFont(font);
  531. return headStyle;
  532. }
  533.  
  534. /// <summary>
  535. /// 根据十六进制颜色获得颜色索引
  536. /// </summary>
  537. /// <param name="workbook"></param>
  538. /// <param name="color"></param>
  539. /// <returns></returns>
  540. private short GetColorIndex(HSSFWorkbook workbook, string color)
  541. {
  542. Color co = ColorTranslator.FromHtml(color);
  543.  
  544. return GetXLColour(workbook, co);
  545. }
  546.  
  547. //获得excel中的颜色索引
  548. private short GetXLColour(HSSFWorkbook workbook, System.Drawing.Color SystemColour)
  549. {
  550. short s = ;
  551. HSSFPalette XlPalette = workbook.GetCustomPalette();
  552. HSSFColor XlColour = XlPalette.FindColor(SystemColour.R, SystemColour.G, SystemColour.B);
  553. //if (XlColour == null)
  554. //{
  555. // if (NPOI.HSSF.Record.PaletteRecord.STANDARD_PALETTE_SIZE < 255)
  556. // {
  557. // if (NPOI.HSSF.Record.PaletteRecord.STANDARD_PALETTE_SIZE < 64)
  558. // {
  559. // NPOI.HSSF.Record.PaletteRecord.STANDARD_PALETTE_SIZE = 64;
  560. // NPOI.HSSF.Record.PaletteRecord.STANDARD_PALETTE_SIZE += 1;
  561. // XlColour = XlPalette.AddColor(SystemColour.R, SystemColour.G, SystemColour.B);
  562. // }
  563. // else
  564. // {
  565. // XlColour = XlPalette.FindSimilarColor(SystemColour.R, SystemColour.G, SystemColour.B);
  566. // }
  567.  
  568. // s = XlColour.Indexed;
  569. // }
  570.  
  571. //}
  572. //else
  573. // s = XlColour.Indexed;
  574.  
  575. return s;
  576. }
  577.  
  578. #endregion
  579.  
  580. #region 设置excel文件基本属性
  581. /// <summary>
  582. /// 文件基本属性
  583. /// </summary>
  584. /// <param name="company">公司名称,默认 慧择网</param>
  585. /// <param name="author">作者信息,默认 慧择</param>
  586. /// <param name="ApplicationName">创建程序信息</param>
  587. /// <param name="LastAuthor">xls文件最后保存者信息</param>
  588. /// <param name="Comments">填加xls文件作者信息,备注</param>
  589. /// <param name="title">填加xls文件标题信息</param>
  590. /// <param name="Subject">填加文件主题信息</param>
  591. /// <returns>一个初始化的Excel Workbook对象</returns>
  592. internal void SetWorkbook(ExcelProperty ep)
  593. {
  594. #region 右击文件 属性信息
  595. DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();
  596. ///公司
  597. dsi.Company = ep.Company;
  598. dsi.Manager = ep.Manager;
  599. dsi.Category = ep.Catagory;
  600. Workbook.DocumentSummaryInformation = dsi;
  601. SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
  602. si.Author = ep.Author; //填加xls文件作者信息
  603. si.ApplicationName = ep.ApplicationName; //填加xls文件创建程序信息
  604. si.LastAuthor = ep.LastAuthor; //填加xls文件最后保存者信息
  605. si.Comments = ep.Comments; //填加xls文件作者信息
  606. si.Title = ep.Title; //填加xls文件标题信息
  607. si.Subject = ep.Subject;//填加文件主题信息
  608. si.Keywords = ep.KeyWord;
  609. si.CreateDateTime = DateTime.Now;
  610. si.Comments = ep.Comments;
  611. Workbook.SummaryInformation = si;
  612. #endregion
  613. }
  614. /// <summary>
  615. /// 初始化显示的内容的单元格统一的样式
  616. /// </summary>
  617. /// <param name="fontweight">字体粗细</param>
  618. /// <param name="fontsize">字体大小</param>
  619. internal HSSFCellStyle SetContentFormat(short fontweight = , short fontsize = )
  620. {
  621. cellStyle = (HSSFCellStyle)Workbook.CreateCellStyle();
  622. //设置单元格border
  623. cellStyle.BorderRight = cellStyle.BorderLeft = cellStyle.BorderBottom = cellStyle.BorderTop = WholeBorderStyle;
  624. cellStyle.BottomBorderColor = cellStyle.RightBorderColor = cellStyle.LeftBorderColor = cellStyle.TopBorderColor = WholeBorderColor;
  625. cellStyle.Alignment = HorizontalAlignment.Center;
  626. cellStyle.VerticalAlignment = VerticalAlignment.Center;
  627. IFont font = Workbook.CreateFont();
  628. font.FontHeightInPoints = fontsize;
  629. font.Boldweight = fontweight;
  630. cellStyle.SetFont(font);
  631. return cellStyle;
  632. }
  633. #endregion
  634.  
  635. #region 设置分组信息
  636. internal void SetGroupCell(List<GroupClass> ce)
  637. {
  638. GCell = ce;
  639. }
  640. #endregion
  641.  
  642. }
  643.  
  644. /// <summary>
  645. /// 拓展类
  646. /// </summary>
  647. public static class Extend
  648. {
  649.  
  650. /// <summary>
  651. /// 泛型列表转成DataTable
  652. /// </summary>
  653. /// <typeparam name="T">泛型实体</typeparam>
  654. /// <param name="list">要转换的列表</param>
  655. /// <param name="titles">标题</param>
  656. /// <param name="fieldFuncs">字段委托</param>
  657. /// <returns></returns>
  658. internal static DataTable ToDataTable<T>(this List<T> list, string[] titles, params Func<T, string>[] fieldFuncs)
  659. {
  660. if (fieldFuncs.Length > )
  661. {
  662. if (titles == null || fieldFuncs.Length != titles.Length)
  663. {
  664. throw new Exception("titles不能为空且必须与导出字段一一对应");
  665. }
  666.  
  667. DataTable dt = new DataTable();
  668. //标题行
  669. DataRow headerDataRow = dt.NewRow();
  670. for (int i = ; i < fieldFuncs.Length; i++)
  671. {
  672. dt.Columns.Add(new DataColumn());
  673. headerDataRow[i] = titles[i];
  674. }
  675. dt.Rows.Add(headerDataRow);
  676.  
  677. //内容行
  678. foreach (T item in list)
  679. {
  680. DataRow dr = dt.NewRow();
  681. for (int i = ; i < fieldFuncs.Length; i++)
  682. {
  683. dr[i] = fieldFuncs[i](item);
  684. }
  685. dt.Rows.Add(dr);
  686. }
  687. return dt;
  688. }
  689. else
  690. {
  691. Type listType = typeof(T);
  692. PropertyInfo[] properties = listType.GetProperties();
  693. if (properties.Length != titles.Length)
  694. {
  695. throw new Exception("titles不能为空且必须与导出字段一一对应");
  696. }
  697.  
  698. DataTable dt = new DataTable();
  699. //标题行
  700. DataRow headerDataRow = dt.NewRow();
  701. for (int i = ; i < properties.Length; i++)
  702. {
  703. PropertyInfo property = properties[i];
  704. dt.Columns.Add(new DataColumn());
  705. headerDataRow[i] = titles[i];
  706. }
  707. dt.Rows.Add(headerDataRow);
  708.  
  709. //内容行
  710. foreach (T item in list)
  711. {
  712. DataRow dr = dt.NewRow();
  713. for (int i = ; i < dt.Columns.Count; i++)
  714. {
  715. dr[i] = properties[i].GetValue(item, null);
  716. }
  717. dt.Rows.Add(dr);
  718. }
  719. return dt;
  720. }
  721. }
  722.  
  723. /// <summary>
  724. /// List转DataTable
  725. /// </summary>
  726. /// <typeparam name="T"></typeparam>
  727. /// <param name="list"></param>
  728. /// <returns></returns>
  729. internal static DataTable ToDataTable<T>(this IEnumerable<T> list, string tableName)
  730. {
  731. //创建属性的集合
  732. List<PropertyInfo> pList = new List<PropertyInfo>();
  733. //获得反射的入口
  734. Type type = typeof(T);
  735. DataTable dt = new DataTable();
  736. dt.TableName = tableName;
  737. //把所有的public属性加入到集合 并添加DataTable的列
  738. System.Array.ForEach<PropertyInfo>(type.GetProperties(), p => { pList.Add(p); dt.Columns.Add(p.Name, p.PropertyType); });
  739. foreach (var item in list)
  740. {
  741. //创建一个DataRow实例
  742. DataRow row = dt.NewRow();
  743. //给row 赋值
  744. pList.ForEach(p => row[p.Name] = p.GetValue(item, null));
  745. //加入到DataTable
  746. dt.Rows.Add(row);
  747. }
  748. return dt;
  749. }
  750.  
  751. /// <summary>
  752. /// 将WorkBook对象转换成内存流
  753. /// </summary>
  754. /// <param name="wv"></param>
  755. /// <returns></returns>
  756. public static MemoryStream SaveToStream(this HSSFWorkbook wv)
  757. {
  758. using (MemoryStream ms = new MemoryStream())
  759. {
  760. wv.Write(ms);
  761. ms.Flush();
  762. ms.Position = ;
  763. return ms;
  764. }
  765. }
  766.  
  767. internal static int[] ToIntArray(this string[] region)
  768. {
  769. ArrayList aList = new ArrayList();
  770. foreach (string i in region)
  771. aList.Add(Convert.ToInt32(i));
  772. return (int[])aList.ToArray(typeof(int));
  773. }
  774.  
  775. internal static HorizontalAlignment ToHorAlign(this string str)
  776. {
  777. switch (str.ToLower())
  778. {
  779. case "center":
  780. return HorizontalAlignment.Center;
  781. break;
  782. case "left":
  783. return HorizontalAlignment.Left;
  784. break;
  785. case "right":
  786. return HorizontalAlignment.Right;
  787. break;
  788. default:
  789. return HorizontalAlignment.Center;
  790. break;
  791. }
  792. return HorizontalAlignment.Center;
  793. }
  794.  
  795. internal static VerticalAlignment ToVerAlign(this string str)
  796. {
  797. switch (str.ToLower())
  798. {
  799. case "center":
  800. return VerticalAlignment.Center;
  801. break;
  802. case "top":
  803. return VerticalAlignment.Top;
  804. break;
  805. case "bottom":
  806. return VerticalAlignment.Bottom;
  807. break;
  808. default:
  809. return VerticalAlignment.Center;
  810. break;
  811. }
  812. return VerticalAlignment.Center;
  813. }
  814.  
  815. /// <summary>
  816. /// web导出excel
  817. /// </summary>
  818. /// <param name="hssf">已经被处理好的HSSFWorkbook对象</param>
  819. /// <param name="fileName">将要下载显示的名字</param>
  820. public static void ExportToWeb(this HSSFWorkbook hssf, string fileName)
  821. {
  822. byte[] buffers = hssf.SaveToStream().GetBuffer();
  823. ExportToWebExcel(buffers, fileName);
  824. }
  825.  
  826. /// <summary>
  827. /// 本地存储到excel
  828. /// </summary>
  829. /// <param name="hssf">已经被处理好的HSSFWorkbook对象</param>
  830. /// <param name="fileName">文件名称,请自己包含路径,例如C:\\test.xls</param>
  831. public static void ExportToLocal(this HSSFWorkbook hssf, string fileName)
  832. {
  833. byte[] buffers = hssf.SaveToStream().GetBuffer();
  834. ExportToLocalExcel(buffers, fileName);
  835. }
  836.  
  837. /// <summary>
  838. /// 本地存储到excel
  839. /// </summary>
  840. /// <param name="buffers">文件二进制流</param>
  841. /// <param name="fileName">文件目录例如C:\\test.xls</param>
  842. public static void ExportToLocalExcel(byte[] buffers, string fileName)
  843. {
  844. using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write))
  845. {
  846. fs.Write(buffers, , buffers.Length);
  847. fs.Flush();
  848. }
  849. }
  850.  
  851. /// <summary>
  852. /// web导出excel
  853. /// </summary>
  854. /// <param name="buffers">文件二进制流</param>
  855. /// <param name="fileName">文件名称</param>
  856. public static void ExportToWebExcel(byte[] buffers, string fileName)
  857. {
  858. if (HttpContext.Current.Request.Browser.Type.IndexOf("IE") > -)
  859. {
  860. HttpContext.Current.Response.ContentType = "application/octet-stream";
  861. HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" +
  862. HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
  863. }
  864. else
  865. {
  866. HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
  867. HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment;filename*=utf-8'zh_cn'{0}", HttpUtility.UrlEncode(fileName)));
  868. }
  869. HttpContext.Current.Response.Charset = "gb2312";
  870. HttpContext.Current.Response.ContentEncoding = Encoding.GetEncoding("gb2312");
  871.  
  872. HttpContext.Current.Response.Clear();
  873.  
  874. HttpContext.Current.Response.BinaryWrite(buffers);
  875. System.Globalization.CultureInfo myCItrad = new System.Globalization.CultureInfo("zh-CN", true);
  876. HttpContext.Current.Response.End();
  877. }
  878.  
  879. }
  880.  
  881. #region Excel属性类
  882. /// <summary>
  883. /// 用于定义导出的excel属性
  884. /// </summary>
  885. public class ExcelProperty
  886. {
  887. public ExcelProperty() { }
  888. /// <summary>
  889. /// 文件基本属性
  890. /// </summary>
  891. /// <param name="company">公司名称 默认AaronYang</param>
  892. /// <param name="author">作者信息,默认 杨洋</param>
  893. /// <param name="ApplicationName">创建程序信息</param>
  894. /// <param name="LastAuthor">xls文件最后保存者信息</param>
  895. /// <param name="Comments">填加xls文件作者信息,备注</param>
  896. /// <param name="title">填加xls文件标题信息</param>
  897. /// <param name="Subject">填加文件主题信息</param>
  898. /// <param name="keyWord">关键词</param>
  899. /// <param name="catagory">类别</param>
  900. /// <param name="manager">经理</param>
  901. public ExcelProperty(string company, string author, string applicationName, string lastAuthor, string comments, string title, string subject, string keyWord, string catagory, string manager)
  902. {
  903. this.Company = company;
  904. this.Author = author;
  905. this.ApplicationName = applicationName;
  906. this.LastAuthor = lastAuthor;
  907. this.Comments = comments;
  908. this.Title = title;
  909. this.Subject = subject;
  910. this.Manager = manager;
  911. this.KeyWord = keyWord;
  912. this.Catagory = catagory;
  913. }
  914. /// <summary>
  915. /// 公司名称,默认 AaronYang
  916. /// </summary>
  917. private string company = "AaronYang";
  918. /// <summary>
  919. /// 公司名称,默认 AaronYang
  920. /// </summary>
  921. public string Company
  922. {
  923. get { return company; }
  924. set { company = value; }
  925. }
  926. /// <summary>
  927. /// 作者信息,默认 杨洋
  928. /// </summary>
  929. private string author = "杨洋";
  930. /// <summary>
  931. /// 作者信息,默认 杨洋
  932. /// </summary>
  933. public string Author
  934. {
  935. get { return author; }
  936. set { author = value; }
  937. }
  938. /// <summary>
  939. /// 创建程序信息
  940. /// </summary>
  941. private string applicationName = "";
  942. /// <summary>
  943. /// 创建程序信息
  944. /// </summary>
  945. public string ApplicationName
  946. {
  947. get { return applicationName; }
  948. set { applicationName = value; }
  949. }
  950. /// <summary>
  951. /// xls文件最后保存者信息
  952. /// </summary>
  953. private string lastAuthor = "";
  954. /// <summary>
  955. /// xls文件最后保存者信息
  956. /// </summary>
  957. public string LastAuthor
  958. {
  959. get { return lastAuthor; }
  960. set { lastAuthor = value; }
  961. }
  962. /// <summary>
  963. ///填加xls文件作者信息,备注
  964. /// </summary>
  965. private string comments = "";
  966. /// <summary>
  967. ///填加xls文件作者信息,备注
  968. /// </summary>
  969. public string Comments
  970. {
  971. get { return comments; }
  972. set { comments = value; }
  973. }
  974. /// <summary>
  975. /// 填加xls文件标题信息
  976. /// </summary>
  977. private string title = "";
  978. /// <summary>
  979. /// 填加xls文件标题信息
  980. /// </summary>
  981. public string Title
  982. {
  983. get { return title; }
  984. set { title = value; }
  985. }
  986. /// <summary>
  987. /// 填加文件主题信息
  988. /// </summary>
  989. private string subject = "";
  990. /// <summary>
  991. /// 填加文件主题信息
  992. /// </summary>
  993. public string Subject
  994. {
  995. get { return subject; }
  996. set { subject = value; }
  997. }
  998. /// <summary>
  999. /// 关键字
  1000. /// </summary>
  1001. private string keyWord = "";
  1002. /// <summary>
  1003. /// 关键字
  1004. /// </summary>
  1005. public string KeyWord
  1006. {
  1007. get { return keyWord; }
  1008. set { keyWord = value; }
  1009. }
  1010. /// <summary>
  1011. /// 类别
  1012. /// </summary>
  1013. private string catagory = "";
  1014. /// <summary>
  1015. /// 类别
  1016. /// </summary>
  1017. public string Catagory
  1018. {
  1019. get { return catagory; }
  1020. set { catagory = value; }
  1021. }
  1022. /// <summary>
  1023. /// 经理
  1024. /// </summary>
  1025. private string manager = "";
  1026. /// <summary>
  1027. /// 经理
  1028. /// </summary>
  1029. public string Manager
  1030. {
  1031. get { return manager; }
  1032. set { manager = value; }
  1033. }
  1034.  
  1035. }
  1036. #endregion
  1037.  
  1038. #region 定义Json表头的格式
  1039. /// <summary>
  1040. /// 关于表头单元格设置属性:字体默认:黑体,字体大小默认12
  1041. /// </summary>
  1042. internal class AttributeList
  1043. {
  1044. /// <summary>
  1045. /// 显示的文字
  1046. /// </summary>
  1047. public string title { get; set; }
  1048. /// <summary>
  1049. /// 显示方式
  1050. /// </summary>
  1051. public string align { get; set; }
  1052. /// <summary>
  1053. /// 垂直显示方式
  1054. /// </summary>
  1055. public string valign { get; set; }
  1056. /// <summary>
  1057. /// 背景颜色.例如#000000
  1058. /// </summary>
  1059. public string bgcolor { get; set; }
  1060. /// <summary>
  1061. /// 字体大小
  1062. /// </summary>
  1063. public short? fontsize { get; set; }
  1064. /// <summary>
  1065. /// 字体颜色,例如#000000
  1066. /// </summary>
  1067. public string fontcolor { get; set; }
  1068. /// <summary>
  1069. /// 单元格合并位置,(fromRow,toRow,fromColumn,toColumn)
  1070. /// </summary>
  1071. public string cellregion { get; set; }
  1072. /// <summary>
  1073. /// 字体名称
  1074. /// </summary>
  1075. public string fontName { get; set; }
  1076. /// <summary>
  1077. /// 表头文字是否加粗,默认加粗
  1078. /// </summary>
  1079. public string fontweight { get; set; }
  1080. /// <summary>
  1081. /// 宽度
  1082. /// </summary>
  1083. public int? width { get; set; }
  1084. /// <summary>
  1085. /// 高度
  1086. /// </summary>
  1087. public int? height { get; set; }
  1088.  
  1089. /// <summary>
  1090. ///是否是斜体
  1091. /// </summary>
  1092. public bool? IsItalic { get; set; }
  1093. /// <summary>
  1094. /// 是否有中间线
  1095. /// </summary>
  1096. public bool? IsStrikeout { get; set; }
  1097. /// <summary>
  1098. /// 设置下划线
  1099. /// </summary>
  1100. public bool? Underline { get; set; }
  1101.  
  1102. }
  1103.  
  1104. /// <summary>
  1105. /// 合并组,暂时支持一列
  1106. /// </summary>
  1107. public class GroupClass
  1108. {
  1109. /// <summary>
  1110. /// 从哪一行开始
  1111. /// </summary>
  1112. public int? index { get; set; }
  1113. /// <summary>
  1114. /// 分组后每组中多少个值
  1115. /// </summary>
  1116. public int? groupCount{ get; set; }
  1117. /// <summary>
  1118. /// 要合并的那一列的索引
  1119. /// </summary>
  1120. public int column { get; set; }
  1121.  
  1122. }
  1123. /// <summary>
  1124. /// 报表表格头部信息
  1125. /// </summary>
  1126. internal class HeadInfo
  1127. {
  1128. public IList<AttributeList> head { get; set; }
  1129. public int? rowspan { get; set; }
  1130. public string sheetname { get; set; }
  1131. /// <summary>
  1132. /// 默认单元格宽度
  1133. /// </summary>
  1134. public int? defaultwidth { get; set; }
  1135. /// <summary>
  1136. /// 默认行高度
  1137. /// </summary>
  1138. public int? defaultheight { get; set; }
  1139. /// <summary>
  1140. /// 默认黑色,表格边框颜色
  1141. /// </summary>
  1142. public string bordercolor { get; set; }
  1143. /// <summary>
  1144. /// 边框风格,默认 thin
  1145. /// </summary>
  1146. public string borderstyle { get; set; }
  1147. }
  1148. /// <summary>
  1149. /// 根节点
  1150. /// </summary>
  1151. internal class Root
  1152. {
  1153. public HeadInfo root { get; set; }
  1154. }
  1155.  
  1156. #endregion
  1157.  
  1158. /// <summary>
  1159. /// excel 构建
  1160. /// 仿照AutoMaper 调用方式
  1161. /// 调用方式
  1162. /// new ExportBuilder<CustomerInsureModel>()
  1163. /// .Column(c => c.InsureNum)
  1164. /// .Column(c => c.Applicant)
  1165. /// .Column(c => c.Insurant)
  1166. /// .Column(c => c.CompanyName)
  1167. /// .Column(c => c.ProdName)
  1168. /// .Column(c => c.InsureTime, c => c.InsureTime.Value.ToString("yyyy-MM-dd HH:mm"))
  1169. /// .Column(c => c.IsMergePay, c => c.IsMergePay ? c.OrderNum : string.Empty)
  1170. /// .Column(c => c.BuySinglePrice, c => c.BuySinglePrice.Value.ToString("0.00"))
  1171. /// .Column(c => c.OnlinePaymnet, c => c.OnlinePaymnet.GetDescription())
  1172. /// .Export(vdata.ToList(), "用户投保信息.xls");
  1173. /// </summary>
  1174. /// <typeparam name="T"></typeparam>
  1175. public class ExportBuilder<T>
  1176. {
  1177. List<string> titles = new List<string>();
  1178. //循环进行添加func字段的值
  1179. List<Func<T, string>> funcs = new List<Func<T, string>>();
  1180. private ExcelHelper excel;
  1181. internal ExcelHelper Excel
  1182. {
  1183. get
  1184. {
  1185. if (excel == null)
  1186. {
  1187. excel = new ExcelHelper();
  1188. }
  1189. return excel;
  1190. }
  1191. set { excel = value; }
  1192. }
  1193.  
  1194. /// <summary>
  1195. /// 定义列
  1196. /// 2012-08-15 支持 .Column(m => m.Platform01.ToString()) 写法
  1197. /// </summary>
  1198. /// <param name="member">解析Display特性得到列名,如不存在,则使用列名</param>
  1199. /// <returns></returns>
  1200. public ExportBuilder<T> Column(Expression<Func<T, string>> member)
  1201. {
  1202. //var memberParam = member.Body as MemberExpression;
  1203. titles.Add(ExcelUtility.GetDisplayName(member.Body));
  1204. var convert = member.Compile();
  1205. funcs.Add(convert);
  1206. return this;
  1207. }
  1208. public void SetTitleAndColumn(Expression<Func<T, string>> member)
  1209. {
  1210. titles.Add(ExcelUtility.GetDisplayName(member.Body));
  1211. var convert = member.Compile();
  1212. funcs.Add(convert);
  1213. }
  1214. /// <summary>
  1215. /// 定义列
  1216. /// </summary>
  1217. /// <param name="member"></param>
  1218. /// <param name="title">列名</param>
  1219. /// <returns></returns>
  1220. public ExportBuilder<T> Column(Expression<Func<T, string>> member, string title)
  1221. {
  1222. var memberParam = member.Body as MemberExpression;
  1223. titles.Add(title);
  1224. var convert = member.Compile();
  1225. funcs.Add(convert);
  1226. return this;
  1227. }
  1228.  
  1229. /// <summary>
  1230. /// 定义列
  1231. /// </summary>
  1232. /// <param name="member">解析Display特性得到列名,如不存在,则使用列名</param>
  1233. /// <param name="convert">定义数据输出格式</param>
  1234. /// <returns></returns>
  1235. public ExportBuilder<T> Column(Expression<Func<T, object>> member, Func<T, string> convert)
  1236. {
  1237. //var memberParam = member.Body as MemberExpression;
  1238. titles.Add(ExcelUtility.GetDisplayName(member.Body));
  1239. funcs.Add(convert);
  1240. return this;
  1241. }
  1242.  
  1243. /// <summary>
  1244. ///
  1245. /// </summary>
  1246. /// <param name="member"></param>
  1247. /// <param name="title">列名</param>
  1248. /// <param name="convert">定义数据输出格式</param>
  1249. /// <returns></returns>
  1250. public ExportBuilder<T> Column(Expression<Func<T, object>> member, string title, Func<T, string> convert)
  1251. {
  1252. var memberParam = member.Body as MemberExpression;
  1253. titles.Add(title);
  1254. funcs.Add(convert);
  1255. return this;
  1256. }
  1257.  
  1258. /// <summary>
  1259. /// 编辑已经添加的转换
  1260. /// </summary>
  1261. /// <param name="name"></param>
  1262. /// <param name="convert"></param>
  1263. /// <returns></returns>
  1264. public ExportBuilder<T> Edit(string name, Func<T, string> convert)
  1265. {
  1266. var index = titles.FindIndex(m => m == name);
  1267. if (index > -)
  1268. {
  1269. funcs[index] = convert;
  1270. }
  1271. return this;
  1272. }
  1273.  
  1274. /// <summary>
  1275. /// 设置Excel属性
  1276. /// </summary>
  1277. /// <param name="ext"></param>
  1278. /// <returns></returns>
  1279. public ExportBuilder<T> SetExcelProperty(ExcelProperty ext)
  1280. {
  1281. Excel.SetWorkbook(ext);
  1282. return this;
  1283. }
  1284.  
  1285. /// <summary>
  1286. /// 导出WEB
  1287. /// </summary>
  1288. /// <param name="list">数据源</param>
  1289. /// <param name="fileName">文件名</param>
  1290. /// <param name="headJosn">表头JSON</param>
  1291. public void Export(List<T> list, string fileName, string headJson)
  1292. {
  1293. Excel.ExportToWeb<T>(list, fileName, titles.ToArray(), headJson, funcs.ToArray());
  1294. }
  1295. /// <summary>
  1296. /// 导出WEB,含分组
  1297. /// </summary>
  1298. /// <param name="list">数据源(分组后的)</param>
  1299. /// <param name="fileName">文件名</param>
  1300. /// <param name="headJosn">表头JSON</param>
  1301. /// <param name="group">分组集合</param>
  1302. /// <param name="groupColumn">分组所在的列,索引从0开始</param>
  1303. public void Export(List<T> list, string fileName, string headJson, List<GroupClass> group, int groupColumn)
  1304. {
  1305. Excel.ExportToWeb<T>(list, fileName, titles.ToArray(), headJson, group, groupColumn, funcs.ToArray());
  1306. }
  1307. /// <summary>
  1308. /// 导出到本地存储
  1309. /// </summary>
  1310. /// <param name="list">数据源</param>
  1311. /// <param name="fileName">文件名</param>
  1312. /// <param name="headJson">表头JSON</param>
  1313. public void ExportToLocal(List<T> list, string fileName, string headJson)
  1314. {
  1315. Excel.ExportToLocal<T>(list, fileName, titles.ToArray(), headJson, funcs.ToArray());
  1316. }
  1317. /// <summary>
  1318. /// 导出到本地存储,含分组
  1319. /// </summary>
  1320. /// <param name="list">数据源(分组后的)</param>
  1321. /// <param name="fileName">文件名</param>
  1322. /// <param name="headJson">表头JSON</param>
  1323. /// <param name="group">分组集合</param>
  1324. /// <param name="groupColumn">分组所在的列,索引从0开始</param>
  1325. public void ExportToLocal(List<T> list, string fileName, string headJson, List<GroupClass> group, int groupColumn)
  1326. {
  1327. Excel.ExportToLocal<T>(list, fileName, titles.ToArray(), headJson, group, groupColumn, funcs.ToArray());
  1328. }
  1329. }
  1330.  
  1331. }
using MyNPOI.Excel;
using NPOI.SS.UserModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks; namespace GTJ.Utility.MyNPOI.Excel
{
public class ExcelUtility
{
private static IWorkbook workbook = null; public static void CreateWorkbook(Stream file)
{
workbook = WorkbookFactory.Create(file);
} /// <summary>
/// 解析Excel
/// </summary>
/// <param name="strFileName">Excel文件路径</param>
/// <param name="SheetIndex">sheet号</param>
/// <param name="dataIndex">数据开始行</param>
/// <param name="needHeader"></param>
/// <returns></returns>
public static List<StringBuilder> ImportExceltoList(int SheetIndex, int dataIndex)
{
int num = ;
try
{
List<StringBuilder> listTemp = new List<StringBuilder>(); ISheet sheet = workbook.GetSheetAt(SheetIndex);
int rows = sheet.LastRowNum;//获得总行数 for (int i = dataIndex; i <= rows; i++)
{
num = i;
IRow row = sheet.GetRow(i);
if (row == null)
{
break;
}
int cellnum = row.LastCellNum;//单元格数
StringBuilder sb = new StringBuilder();
for (int j = ; j < cellnum; j++)
{
ICell cell = row.GetCell(j);
if (cell != null)
{
cell.SetCellType(CellType.String);//全都设置成String
string value = cell.StringCellValue;
sb.Append(value.Trim()).Append(";"); }
else
{
sb.Append(";");
}
}
listTemp.Add(sb);//每行数据以分号(;)隔开拼接成字符串存入list中
}
return listTemp;
}
catch
{
GTJ.Utility.ScriptHelper.writer(System.Web.HttpContext.Current.Response, "导入Excel出错,在" + num + "行有错误,请检查");
}
return null;
} /// <summary>
/// 进行数据库的导出
/// </summary>
/// <typeparam name="T">model 属性值</typeparam>
/// <param name="list"></param>
/// <param name="fileName"></param>
/// <param name="headJson"></param>
/// <param name="funcs"></param>
public static void ExportToLocal<T>(List<T> list, string fileName, string headJson, params Expression<Func<T,string>>[] funcs)
{
ExportBuilder<T> ExportBuild = new ExportBuilder<T>();
for(var i=;i< funcs.Length; i++)
{
//设置对应的title和列的情况
ExportBuild.SetTitleAndColumn(funcs[i]); }
ExportBuild.ExportToLocal(list,fileName,headJson);
}
/// <summary>
/// 导入到web端
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list"></param>
/// <param name="fileName"></param>
/// <param name="headJson"></param>
/// <param name="funcs"></param>
public static void ExportToWeb<T>(List<T> list, string fileName, string headJson, params Expression<Func<T, string>>[] funcs)
{
ExportBuilder<T> ExportBuild = new ExportBuilder<T>();
for (var i = ; i < funcs.Length; i++)
{
//设置对应的title和列的情况
ExportBuild.SetTitleAndColumn(funcs[i]); }
ExportBuild.Export(list, fileName, headJson);
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json;
using System.IO;
using System.Linq.Expressions;
using System.ComponentModel.DataAnnotations;
using System.Reflection;
using System.ComponentModel; namespace GTJ.Utility.MyNPOI
{
/// <summary>
///JsonUtility 的摘要说明
/// </summary>
public class Utility
{
/// <summary>
/// Json工具类
/// </summary>
public static class JsonUtility
{
/// <summary>
/// 添加时间转换器
/// </summary>
/// <param name="serializer"></param>
private static void AddIsoDateTimeConverter(JsonSerializer serializer)
{
IsoDateTimeConverter idtc = new IsoDateTimeConverter();
//定义时间转化格式
idtc.DateTimeFormat = "yyyy-MM-dd";
//idtc.DateTimeFormat = "yyyy-MM-dd";
serializer.Converters.Add(idtc);
} /// <summary>
/// Json转换配置
/// </summary>
/// <param name="serializer"></param>
private static void SerializerSetting(JsonSerializer serializer)
{
serializer.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
//serializer.NullValueHandling = NullValueHandling.Ignore;
//serializer.MissingMemberHandling = MissingMemberHandling.Ignore;
//serializer.DefaultValueHandling = DefaultValueHandling.Ignore;
} /// <summary>
/// 返回结果消息编码
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="sucess"></param>
/// <param name="message"></param>
/// <param name="exMessage"></param>
/// <param name="data"></param>
/// <returns></returns>
public static string ReturnMessage(bool sucess, int total, string message, string exMessage, string data)
{
message = message.Replace("'", "").Replace("\"", "").Replace("<", "").Replace(">", "");
exMessage = exMessage.Replace("'", "").Replace("\"", "").Replace("<", "").Replace(">", ""); return string.Format("{{success:{0},total:{1},data:{2},message:\"{3}\",exMessage:\"{4}\"}}",
sucess.ToString().ToLower(), total, data, message, exMessage);
} /// <summary>
/// 返回失败信息
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="message"></param>
/// <param name="exMessage"></param>
/// <returns></returns>
public static string ReturnFailureMessage(string message, string exMessage)
{
return ReturnMessage(false, , message, exMessage, "[]");
} /// <summary>
/// 返回失败信息
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="message"></param>
/// <param name="exMessage"></param>
/// <returns></returns>
public static string ReturnFailureMessageTouch(string message, string exMessage)
{
return "{\"success\":\"false\",\"msg\":\"" + exMessage + "\"}";
} /// <summary>
/// 返回成功信息
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="total"></param>
/// <param name="message"></param>
/// <param name="exMessage"></param>
/// <param name="objList"></param>
/// <returns></returns>
public static string ReturnSuccessMessage<T>(int total, string message, string exMessage, List<T> objList)
{
string data = ListToJson<T>(objList);
return ReturnMessage(true, total, message, exMessage, data);
} public static string ReturnSuccessMessageTouch<T>(T obj)
{
string data = ObjectToJson<T>(obj);
return data;
} /// <summary>
/// 返回成功信息
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="total"></param>
/// <param name="message"></param>
/// <param name="exMessage"></param>
/// <param name="objList"></param>
/// <returns></returns>
public static string ReturnSuccessMessage(string message, string exMessage)
{
return ReturnMessage(true, , message, exMessage, "[]");
} /// <summary>
/// 返回成功信息
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="total"></param>
/// <param name="message"></param>
/// <param name="exMessage"></param>
/// <param name="objList"></param>
/// <returns></returns>
public static string ReturnSuccessMessageTouch(string message, string exMessage)
{
return "{\"success\":\"true\",\"msg\":\"" + message + "\"}";
} /// <summary>
/// 返回成功信息
/// </summary>
/// <param name="message"></param>
/// <param name="exMessage"></param>
/// <param name="data">JSON 对象</param>
/// <returns></returns>
public static string ReturnSuccessMessage(string message, string exMessage, string data)
{
return ReturnMessage(true, , message, exMessage, "[" + data + "]");
} /// <summary>
/// 返回成功消息
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="total"></param>
/// <param name="message"></param>
/// <param name="exMessage"></param>
/// <param name="obj"></param>
/// <returns></returns>
public static string ReturnSuccessMessage<T>(int total, string message, string exMessage, T obj)
{
string data = ObjectToJson<T>(obj);
return ReturnMessage(true, total, message, exMessage, data);
} /// <summary>
/// 把对象列表编码为Json数据
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="objList"></param>
/// <returns></returns>
public static string ListToJson<T>(List<T> objList)
{
JsonSerializer serializer = new JsonSerializer();
SerializerSetting(serializer);
AddIsoDateTimeConverter(serializer); using (TextWriter sw = new StringWriter())
using (JsonWriter writer = new JsonTextWriter(sw))
{
serializer.Serialize(writer, objList);
return sw.ToString();
}
} /// <summary>
/// 把一个对象编码为Json数据
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="obj"></param>
/// <returns></returns>
public static string ObjectToJson<T>(T obj)
{
JsonSerializer serializer = new JsonSerializer();
SerializerSetting(serializer);
AddIsoDateTimeConverter(serializer); using (TextWriter sw = new StringWriter())
using (JsonWriter writer = new JsonTextWriter(sw))
{
serializer.Serialize(writer, obj);
return sw.ToString();
}
} /// <summary>
/// 根据传入的Json数据,解码为对象(一个)
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="data"></param>
/// <returns></returns>
public static T DecodeObject<T>(string data)
{
JsonSerializer serializer = new JsonSerializer();
serializer.MissingMemberHandling = MissingMemberHandling.Ignore;
AddIsoDateTimeConverter(serializer);
StringReader sr = new StringReader(data);
return (T)serializer.Deserialize(sr, typeof(T)); } /// <summary>
/// 功能同DecodeObject
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="data"></param>
/// <returns></returns>
public static List<T> DecodeObjectList<T>(string data)
{
JsonSerializer serializer = new JsonSerializer();
serializer.MissingMemberHandling = MissingMemberHandling.Ignore;
AddIsoDateTimeConverter(serializer);
StringReader sr = new StringReader(data);
return (List<T>)serializer.Deserialize(sr, typeof(List<T>));
} public static string EncodeAjaxResponseJson(string jsonString, string callback)
{
String responseString = "";
//判断是否jsonp调用
if (!String.IsNullOrEmpty(callback))
{
//jsonp调用,需要封装回调函数,并返回
responseString = callback + "(" + jsonString + ")";
}
else
{
//普通ajax调用,直接返回Json数据
responseString = jsonString;
} return responseString;
} public static string ExtGridSortInfo(string property, string direction)
{
return string.Format("[{{\"property\":\"{0}\",\"direction\":\"{1}\"}}]", property, direction);
} } } public static class ExcelUtility
{
/// <summary>
/// [Display(Name = "")]
/// 获得类属性中标记的名称
/// </summary>
/// <param name="expr"></param>
/// <returns></returns>
public static string GetDisplayName(Expression expr)
{
var memberParam = expr as MemberExpression;
if (memberParam != null)
{
return GetDisplayName(memberParam);
}
var unary = expr as UnaryExpression;
if (unary != null)
{
return GetDisplayName(unary.Operand as MemberExpression);
}
var call = expr as MethodCallExpression;
if (call != null)
{
return GetDisplayName(call.Object as MemberExpression);
} return string.Empty; } /// <summary>
/// [Display(Name = "记住帐号")]
/// 获得类属性中标记的中文名
/// </summary>
/// <param name="memberParam"></param>
/// <returns></returns>
private static string GetDisplayName(MemberExpression memberParam)
{
var name = memberParam.Member.Name;
var property = memberParam.Member.ReflectedType.GetProperty(name);
var displays = property.GetCustomAttributes(typeof(DisplayAttribute), false);
if (displays == null || displays.Length == )
return property.Name;
else
return (displays[] as DisplayAttribute).Name;
}
} public static class typeUtility
{
/// <summary>
/// 获取枚举的描述
/// </summary>
/// <param name="enumType">枚举类型</param>
/// <param name="fieldName">枚举字段名称</param>
/// <returns></returns>
public static string GetDescription(Type enumType, string fieldName)
{
if (!enumType.IsEnum)
throw new InvalidOperationException("亲,必须是Enum类型哦,请检查类型是否正确哈。"); FieldInfo field = enumType.GetField(fieldName);
DescriptionAttribute[] attributes = (DescriptionAttribute[])field.GetCustomAttributes(
typeof(DescriptionAttribute), false);
return (attributes.Length > ) ? attributes[].Description : fieldName;
} /// <summary>
/// 获取枚举的描述
/// </summary>
/// <typeparam name="TEnum">枚举类型</typeparam>
/// <param name="enumObject">枚举对象</param>
/// <returns></returns>
public static string GetDescription<TEnum>(this TEnum enumObject)
{
FieldInfo field = enumObject.GetType().GetField(enumObject.ToString());
if (field == null)
{
return "";
}
DescriptionAttribute[] attributes = (DescriptionAttribute[])field.GetCustomAttributes(
typeof(DescriptionAttribute), false);
return (attributes.Length > ) ? attributes[].Description : enumObject.ToString();
}
}
}

使用NPOI导出Excel引发异常(IsReadOnly = “book.IsReadOnly”引发了类型“System.NotImplementedException”的异常)的更多相关文章

  1. .NET NPOI导出Excel详解

    NPOI,顾名思义,就是POI的.NET版本.那POI又是什么呢?POI是一套用Java写成的库,能够帮助开发者在没有安装微软Office的情况下读写Office的文件. 支持的文件格式包括xls, ...

  2. NPOI导出Excel示例

    摘要:使用开源程序NPOI导出Excel示例.NPOI首页地址:http://npoi.codeplex.com/,NPOI示例博客:http://tonyqus.sinaapp.com/. 示例编写 ...

  3. NPOI导出Excel及使用问题

    NPOI导出Excel及使用问题 因为最近公司质管部门提出了一个统计报表的需求:要求导出一个2016及2017年度深圳区域的所有供应商的费用成本计算--一个22列的Excel表,其中还包括多列的合并单 ...

  4. NPOI导出Excel (C#) 踩坑 之--The maximum column width for an individual cell is 255 charaters

    /******************************************************************* * 版权所有: * 类 名 称:ExcelHelper * 作 ...

  5. Asp.Net 使用Npoi导出Excel

    引言 使用Npoi导出Excel 服务器可以不装任何office组件,昨天在做一个导出时用到Npoi导出Excel,而且所导Excel也符合规范,打开时不会有任何文件损坏之类的提示.但是在做导入时还是 ...

  6. NPOI导出EXCEL 打印设置分页及打印标题

    在用NPOI导出EXCEL的时候设置分页,在网上有查到用sheet1.SetRowBreak(i)方法,但一直都没有起到作用.经过研究是要设置  sheet1.FitToPage = false; 而 ...

  7. NPOI导出Excel(含有超过65335的处理情况)

    NPOI导出Excel的网上有很多,正好自己遇到就学习并总结了一下: 首先说明几点: 1.Excel2003及一下:后缀xls,单个sheet最大行数为65335 Excel2007 单个sheet ...

  8. [转]NPOI导出EXCEL 打印设置分页及打印标题

    本文转自:http://www.cnblogs.com/Gyoung/p/4483475.html 在用NPOI导出EXCEL的时候设置分页,在网上有查到用sheet1.SetRowBreak(i)方 ...

  9. 分享使用NPOI导出Excel树状结构的数据,如部门用户菜单权限

    大家都知道使用NPOI导出Excel格式数据 很简单,网上一搜,到处都有示例代码. 因为工作的关系,经常会有处理各种数据库数据的场景,其中处理Excel 数据导出,以备客户人员确认数据,场景很常见. ...

随机推荐

  1. Centos下快速安装Nginx

    1.准备工作 选首先安装这几个软件:GCC,PCRE(Perl Compatible Regular Expression),zlib,OpenSSL. Nginx是C写的,需要用GCC编译:Ngin ...

  2. Java集合框架(五)—— Map、HashMap、Hashtable、Properties、SortedMap、TreeMap、WeakHashMap、IdentityHashMap、EnumMap

    Map Map用于保存具有映射关系的数据,因此Map集合里保存着两组值,一组值用于保存Map里的key,另一组值用于保存Map里的value,key和value都可以是任何引用类型的数据.Map的ke ...

  3. the c programing language 学习过程5

    lumped 集成总结 mandating托管 consecutively连续地 contiguous临近的 mnemonic记忆力的 mimics 酷似 魔方 bind捆绑 synonym同义词 s ...

  4. 使用stringstream对象简化类型转换

    < sstream>库定义了三种类:istringstream.ostringstream和stringstream,分别用来进行流的输入.输出和输入输出操作.另外,每个类都有一个对应的宽 ...

  5. ACM==迷茫

    写给迷茫的自己~~ 从家里来学校一周多了,没做几个题,也没学习新的算法,就这样迷茫地无所事事.有时我就在想我是不是真的喜欢算法?曾经自己定下的竞赛目标要置之不理吗? 我高中毕业于一个普通高中,在上大学 ...

  6. java网络编程(4)——udp实现聊天

    UDP可以实现在线聊天功能,我这里就是简单模拟一下: 发送端: package com.seven.udp; import java.io.BufferedReader; import java.io ...

  7. Spring data mongodb 替换 Repository 实现类,findAll 排除 字段

    因文档比较大,有时候findAll 不想返回所有数据.没有找到默认的findAll 能够include 或者 exclude 的方法,所以想办法扩展一下实现类 query.fields().inclu ...

  8. vim编辑器——常用操作整理

    注意:以下的操作都是在命令状态下进行的,不要进入插入状态了.参考这里 1.删除 dd       删除一行 ndd    删除以当前行开始的n行dw    删除以当前字符开始的一个字符ndw   删除 ...

  9. eclipse Maven配置

    ①下载:http://maven.apache.org/download.cgi ②解压至:F:\Study\apache-maven-3.5.2 ③配置环境变量 变量名:M2_HOME 变量值:F: ...

  10. C语言中的sizeof函数总结

    sizeof函数的结果: 变量:变量所占的字节数. ; printf( 数组:数组所占的字节数. ,,,,}; ] = {,,,,}; printf("size_arr1=%d\n" ...