NpoiExcelHelper.cs 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.IO;
  6. using System.Data;
  7. using System.Web;
  8. using System.Configuration;
  9. using NPOI.HPSF;
  10. using NPOI.HSSF.UserModel;
  11. using NPOI.HSSF.Util;
  12. using NPOI.POIFS.FileSystem;
  13. using NPOI.SS.UserModel;
  14. using System.Reflection;
  15. using System.Text.RegularExpressions;
  16. using System.Collections;
  17. using NPOI.XSSF.UserModel;
  18. namespace Bowin.Common.Utility
  19. {
  20. public class NpoiExcelHelper : IDisposable
  21. {
  22. /// excel路径
  23. /// </summary>
  24. public string FilePath { get; set; }
  25. private List<IGrouping<Func<IWorkbook, HSSFCellStyle>, NpoiExcelCellStyle>> _cellStyleListField;
  26. private List<IGrouping<Func<IWorkbook, HSSFCellStyle>, NpoiExcelCellStyle>> _cellStyleList
  27. {
  28. get
  29. {
  30. if (_cellStyleListField == null)
  31. {
  32. _cellStyleListField = new List<IGrouping<Func<IWorkbook, HSSFCellStyle>, NpoiExcelCellStyle>>();
  33. }
  34. return _cellStyleListField;
  35. }
  36. set
  37. {
  38. _cellStyleListField = value;
  39. }
  40. }
  41. public void PresetCellStyle(List<NpoiExcelCellStyle> cellStyleList)
  42. {
  43. var styleGroup = cellStyleList.GroupBy(x => x.StyleFunc).ToList();
  44. this._cellStyleList = styleGroup;
  45. }
  46. /// <summary>
  47. /// 导出
  48. /// </summary>
  49. /// <param name="dtSource">数据源</param>
  50. /// <param name="CloumnList">中文列名列表</param>
  51. /// <param name="HeaderText">表头</param>
  52. /// <param name="SavePath">保存路径</param>
  53. public void Export(DataTable dtSource, string[] CloumnList, string HeaderText)
  54. {
  55. string fileName = HeaderText + ".xls";
  56. HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
  57. if (HttpContext.Current.Request.UserAgent.ToLower().IndexOf("firefox") > -1)
  58. {
  59. HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", fileName));
  60. }
  61. else
  62. {
  63. HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
  64. }
  65. HttpContext.Current.Response.Clear();
  66. HSSFWorkbook hssfworkbook = new HSSFWorkbook();
  67. ISheet sheet1 = hssfworkbook.CreateSheet("Sheet1");
  68. //默认宽度-高度
  69. sheet1.DefaultColumnWidth = 1 * 15;
  70. short color_BLACK = HSSFColor.BLACK.index;
  71. ICellStyle style = hssfworkbook.CreateCellStyle();
  72. style.BorderBottom = BorderStyle.THIN;
  73. style.BorderLeft = BorderStyle.THIN;
  74. style.BorderRight = BorderStyle.THIN;
  75. style.BorderTop = BorderStyle.THIN;
  76. //设置背景(根据上面的定义的颜色 进行赋值)
  77. //style.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.BLUE_GREY.index;
  78. //style.FillPattern = ICellStyle.SQUARES;
  79. //style.FillBackgroundColor = NPOI.HSSF.Util.HSSFColor.BLUE_GREY.index;
  80. //居中
  81. style.Alignment = HorizontalAlignment.CENTER;
  82. style.VerticalAlignment = VerticalAlignment.CENTER;
  83. //设置字体
  84. IFont font = hssfworkbook.CreateFont();
  85. font.FontHeightInPoints = 12;//字号
  86. font.Boldweight = (short)FontBoldWeight.BOLD;//粗体
  87. style.SetFont(font);
  88. var customerStyleGroupList = _cellStyleList
  89. .Select(x => new { Style = x.Key.Invoke(hssfworkbook), CellList = x.Select(w => new { w.RowIndex, w.ColumnIndex }).ToList() })
  90. .ToList();
  91. if (CloumnList.Length > 0)
  92. {
  93. IRow row = sheet1.CreateRow(0);
  94. for (int i = 0; i < CloumnList.Length; i++)
  95. {
  96. ICell cell = row.CreateCell(i);
  97. cell.SetCellValue(CloumnList[i]);
  98. var customCellStyle = customerStyleGroupList.FirstOrDefault(x => x.CellList.Any(w => w.ColumnIndex == i && w.RowIndex == -1));
  99. if (customCellStyle != null)
  100. {
  101. cell.CellStyle = customCellStyle.Style;
  102. }
  103. else
  104. {
  105. cell.CellStyle = style;
  106. }
  107. }
  108. }
  109. if (dtSource.Rows.Count > 0)
  110. {
  111. for (int i = 0; i < dtSource.Rows.Count; i++)
  112. {
  113. IRow rowsub = sheet1.CreateRow(i + 1);
  114. for (int j = 0; j < dtSource.Columns.Count; j++)
  115. {
  116. var cell = rowsub.CreateCell(j);
  117. if (dtSource.Rows[i][j] != "" && dtSource.Rows[i][j] != null)
  118. {
  119. if (dtSource.Rows[i][j].GetType().FullName == "System.Int32")
  120. {
  121. cell.SetCellValue(Convert.ToInt32(dtSource.Rows[i][j]));//如果是值类型、那么以原格式输出
  122. }
  123. else
  124. {
  125. cell.SetCellValue(dtSource.Rows[i][j].ToString());
  126. }
  127. }
  128. else
  129. {
  130. cell.SetCellValue(dtSource.Rows[i][j] as string);
  131. }
  132. var customCellStyle = customerStyleGroupList.FirstOrDefault(x => x.CellList.Any(w => w.ColumnIndex == j && w.RowIndex == i));
  133. if (customCellStyle != null)
  134. {
  135. cell.CellStyle = customCellStyle.Style;
  136. }
  137. }
  138. }
  139. }
  140. MemoryStream file = new MemoryStream();
  141. hssfworkbook.Write(file);
  142. HttpContext.Current.Response.BinaryWrite(file.GetBuffer());
  143. HttpContext.Current.Response.End();
  144. }
  145. public void ExportTable(string html, string HeaderText = null)
  146. {
  147. string fileName = HeaderText + ".xls";
  148. HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
  149. if (HttpContext.Current.Request.UserAgent.ToLower().IndexOf("firefox") > -1)
  150. {
  151. HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", fileName));
  152. }
  153. else
  154. {
  155. HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
  156. }
  157. HttpContext.Current.Response.Clear();
  158. string rowContent = string.Empty;
  159. MatchCollection rowCollection = Regex.Matches(html, @"<tr[^>]*>[\s\S]*?<\/tr>", RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture); //对tr进行筛选
  160. HSSFWorkbook hssfworkbook = new HSSFWorkbook(); ;//创建Workbook对象
  161. HSSFSheet sheet1 = (HSSFSheet)hssfworkbook.CreateSheet("Sheet1");//创建工作表
  162. short color_BLACK = HSSFColor.BLACK.index;
  163. ICellStyle style = hssfworkbook.CreateCellStyle();
  164. style.BorderBottom = BorderStyle.THIN;
  165. style.BorderLeft = BorderStyle.THIN;
  166. style.BorderRight = BorderStyle.THIN;
  167. style.BorderTop = BorderStyle.THIN;
  168. //设置背景(根据上面的定义的颜色 进行赋值)
  169. //style.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.BLUE_GREY.index;
  170. //style.FillPattern = ICellStyle.SQUARES;
  171. //style.FillBackgroundColor = NPOI.HSSF.Util.HSSFColor.BLUE_GREY.index;
  172. //居中
  173. style.Alignment = HorizontalAlignment.CENTER;
  174. style.VerticalAlignment = VerticalAlignment.CENTER;
  175. //设置字体
  176. IFont font = hssfworkbook.CreateFont();
  177. font.FontHeightInPoints = 12;//字号
  178. font.Boldweight = (short)FontBoldWeight.BOLD;//粗体
  179. style.SetFont(font);
  180. var customerStyleGroupList = _cellStyleList
  181. .Select(x => new { Style = x.Key.Invoke(hssfworkbook), CellList = x.Select(w => new { w.RowIndex, w.ColumnIndex }).ToList() })
  182. .ToList();
  183. //写在tr循环中
  184. for (int i = 0; i < rowCollection.Count; i++)
  185. {
  186. HSSFRow row = (HSSFRow)sheet1.CreateRow(i);
  187. rowContent = rowCollection[i].Value;
  188. MatchCollection columnCollection = Regex.Matches(rowCollection[i].Value, @"<td[^>]*>[\s\S]*?<\/td>", RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture); //对td进行筛选
  189. //遍历td
  190. for (int j = 0; j < columnCollection.Count; j++)
  191. {
  192. var customCellStyle = customerStyleGroupList.FirstOrDefault(x => x.CellList.Any(w => w.ColumnIndex == j && w.RowIndex == i));
  193. var match = Regex.Match(columnCollection[j].Value, "<td.*?rowspan=\"(?<row>.*?)\".*?colspan=\"(?<col>.*?)\".*?row=\"(?<row1>.*?)\".*?col=\"(?<col1>.*?)\">(?<value>.*?)<\\/td>", RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture);
  194. if (match.Success)
  195. {
  196. int rowspan = Convert.ToInt32(match.Groups["row"].Value);//表格跨行
  197. int colspan = Convert.ToInt32(match.Groups["col"].Value);//表格跨列
  198. int rowcount = Convert.ToInt32(match.Groups["row1"].Value);//所在行
  199. int col = Convert.ToInt32(match.Groups["col1"].Value);//所在列
  200. string value = match.Groups["value"].Value;
  201. if (colspan == 1)//判断是否跨列
  202. {
  203. var cell = row.CreateCell(col);//创建列
  204. cell.SetCellValue(value);//设置列的值
  205. if (customCellStyle != null)
  206. {
  207. cell.CellStyle = customCellStyle.Style;
  208. }
  209. else
  210. {
  211. cell.CellStyle = style;
  212. }
  213. if (value.Length > 0)
  214. {
  215. int width = value.Length * 25 / 6;
  216. if (width > 255)
  217. width = 250;
  218. sheet1.SetColumnWidth(col, width * 256);
  219. }
  220. }
  221. else if (colspan == 0)
  222. {
  223. var cell = row.CreateCell(col);//创建列
  224. cell.SetCellValue(value);//设置列的值
  225. if (customCellStyle != null)
  226. {
  227. cell.CellStyle = customCellStyle.Style;
  228. }
  229. else
  230. {
  231. cell.CellStyle = style;
  232. }
  233. }
  234. //判断是否跨行、跨列
  235. if (rowspan > 1 || colspan > 1)
  236. {
  237. int firstRow = 0, lastRow = 0, firstCol = 0, lastCol = 0;
  238. if (rowspan > 1)//跨行
  239. {
  240. firstRow = rowcount;
  241. lastRow = firstRow + rowspan - 1;
  242. }
  243. else
  244. {
  245. firstRow = lastRow = i;
  246. }
  247. if (colspan > 1)//跨列
  248. {
  249. firstCol = col;
  250. int cols = col + colspan;
  251. for (; col < cols; col++)
  252. {
  253. var cell = row.CreateCell(col);
  254. cell.SetCellValue(value);
  255. if (customCellStyle != null)
  256. {
  257. cell.CellStyle = customCellStyle.Style;
  258. }
  259. else
  260. {
  261. cell.CellStyle = style;
  262. }
  263. }
  264. lastCol = col - 1;
  265. }
  266. else
  267. {
  268. firstCol = lastCol = col;
  269. }
  270. //关键是这里,设置起始行数,结束行数;起始列数,结束列数
  271. sheet1.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(firstRow, lastRow, firstCol, lastCol));
  272. }
  273. }
  274. }
  275. }
  276. MemoryStream file = new MemoryStream();
  277. hssfworkbook.Write(file);
  278. HttpContext.Current.Response.BinaryWrite(file.GetBuffer());
  279. HttpContext.Current.Response.End();
  280. }
  281. public void Export(DataTable dtSource, string fileName = null)
  282. {
  283. fileName = (fileName ?? Function.GetGUID()) + ".xls";
  284. //HttpContext.Current.Response.Headers.Clear();
  285. HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
  286. HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", HttpUtility.UrlPathEncode(fileName)));
  287. HttpContext.Current.Response.Clear();
  288. HSSFWorkbook hssfworkbook = new HSSFWorkbook();
  289. ISheet sheet1 = hssfworkbook.CreateSheet("Sheet1");
  290. //默认宽度-高度
  291. sheet1.DefaultColumnWidth = 1 * 15;
  292. short color_BLACK = HSSFColor.BLACK.index;
  293. ICellStyle style = hssfworkbook.CreateCellStyle();
  294. style.BorderBottom = BorderStyle.THICK;
  295. style.BorderLeft = BorderStyle.THICK;
  296. style.BorderRight = BorderStyle.THICK;
  297. style.BorderTop = BorderStyle.THICK;
  298. //设置背景(根据上面的定义的颜色 进行赋值)
  299. //style.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.BLUE_GREY.index;
  300. //style.FillPattern = ICellStyle.SQUARES;
  301. //style.FillBackgroundColor = NPOI.HSSF.Util.HSSFColor.BLUE_GREY.index;
  302. //居中
  303. style.Alignment = HorizontalAlignment.CENTER;
  304. style.VerticalAlignment = VerticalAlignment.CENTER;
  305. //设置字体
  306. IFont font = hssfworkbook.CreateFont();
  307. font.FontHeightInPoints = 12;//字号
  308. font.Boldweight = (short)FontBoldWeight.BOLD;//粗体
  309. style.SetFont(font);
  310. var customerStyleGroupList = _cellStyleList
  311. .Select(x => new { Style = x.Key.Invoke(hssfworkbook), CellList = x.Select(w => new { w.RowIndex, w.ColumnIndex }).ToList() })
  312. .ToList();
  313. if (dtSource.Columns.Count > 0)
  314. {
  315. IRow row = sheet1.CreateRow(0);
  316. for (int i = 0; i < dtSource.Columns.Count; i++)
  317. {
  318. ICell cell = row.CreateCell(i);
  319. cell.SetCellValue(dtSource.Columns[i] != null ? dtSource.Columns[i].ToString() : "");
  320. var customCellStyle = customerStyleGroupList.FirstOrDefault(x => x.CellList.Any(w => w.ColumnIndex == i && w.RowIndex == 0));
  321. if (customCellStyle != null)
  322. {
  323. cell.CellStyle = customCellStyle.Style;
  324. }
  325. else
  326. {
  327. cell.CellStyle = style;
  328. }
  329. }
  330. }
  331. if (dtSource.Rows.Count > 0)
  332. {
  333. for (int i = 0; i < dtSource.Rows.Count; i++)
  334. {
  335. IRow rowsub = sheet1.CreateRow(i + 1);
  336. for (int j = 0; j < dtSource.Columns.Count; j++)
  337. {
  338. var cell = rowsub.CreateCell(j);
  339. if (dtSource.Rows[i][j] != null && dtSource.Rows[i][j] != "")
  340. {
  341. cell.SetCellValue(dtSource.Rows[i][j].ToString());
  342. }
  343. else
  344. {
  345. cell.SetCellValue(dtSource.Rows[i][j] as string);
  346. }
  347. var customCellStyle = customerStyleGroupList.FirstOrDefault(x => x.CellList.Any(w => w.ColumnIndex == j && w.RowIndex == i));
  348. if (customCellStyle != null)
  349. {
  350. cell.CellStyle = customCellStyle.Style;
  351. }
  352. }
  353. }
  354. }
  355. MemoryStream file = new MemoryStream();
  356. hssfworkbook.Write(file);
  357. HttpContext.Current.Response.BinaryWrite(file.GetBuffer());
  358. HttpContext.Current.Response.End();
  359. }
  360. public byte[] ExportMemoryStream(DataTable dtSource, string FileName, string[] CloumnList)
  361. {
  362. string fileName = FileName + DateTime.Now.ToString("yyyyMMdd") + ".xls";
  363. HSSFWorkbook hssfworkbook = new HSSFWorkbook();
  364. ISheet sheet1 = hssfworkbook.CreateSheet("Sheet1");
  365. //默认宽度-高度
  366. sheet1.DefaultColumnWidth = 1 * 15;
  367. short color_BLACK = HSSFColor.BLACK.index;
  368. ICellStyle style = hssfworkbook.CreateCellStyle();
  369. style.BorderBottom = BorderStyle.THICK;
  370. style.BorderLeft = BorderStyle.THICK;
  371. style.BorderRight = BorderStyle.THICK;
  372. style.BorderTop = BorderStyle.THICK;
  373. //设置背景(根据上面的定义的颜色 进行赋值)
  374. //style.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.BLUE_GREY.index;
  375. //style.FillPattern = ICellStyle.SQUARES;
  376. //style.FillBackgroundColor = NPOI.HSSF.Util.HSSFColor.BLUE_GREY.index;
  377. //居中
  378. style.Alignment = HorizontalAlignment.CENTER; ;
  379. style.VerticalAlignment = VerticalAlignment.CENTER; ;
  380. //设置字体
  381. IFont font = hssfworkbook.CreateFont();
  382. font.FontHeightInPoints = 12;//字号
  383. font.Boldweight = (short)FontBoldWeight.BOLD;//粗体
  384. style.SetFont(font);
  385. var customerStyleGroupList = _cellStyleList
  386. .Select(x => new { Style = x.Key.Invoke(hssfworkbook), CellList = x.Select(w => new { w.RowIndex, w.ColumnIndex }).ToList() })
  387. .ToList();
  388. if (CloumnList.Length > 0)
  389. {
  390. IRow row = sheet1.CreateRow(0);
  391. for (int i = 0; i < CloumnList.Length; i++)
  392. {
  393. ICell cell = row.CreateCell(i);
  394. cell.SetCellValue(CloumnList[i]);
  395. var customCellStyle = customerStyleGroupList.FirstOrDefault(x => x.CellList.Any(w => w.ColumnIndex == i && w.RowIndex == 0));
  396. if (customCellStyle != null)
  397. {
  398. cell.CellStyle = customCellStyle.Style;
  399. }
  400. else
  401. {
  402. cell.CellStyle = style;
  403. }
  404. }
  405. }
  406. if (dtSource.Rows.Count > 0)
  407. {
  408. for (int i = 0; i < dtSource.Rows.Count; i++)
  409. {
  410. IRow rowsub = sheet1.CreateRow(i + 1);
  411. for (int j = 0; j < dtSource.Columns.Count; j++)
  412. {
  413. var cell = rowsub.CreateCell(j);
  414. if (dtSource.Rows[i][j] != "" && dtSource.Rows[i][j] != null)
  415. {
  416. cell.SetCellValue(dtSource.Rows[i][j].ToString());
  417. }
  418. else
  419. {
  420. cell.SetCellValue(dtSource.Rows[i][j] as string);
  421. }
  422. var customCellStyle = customerStyleGroupList.FirstOrDefault(x => x.CellList.Any(w => w.ColumnIndex == j && w.RowIndex == i));
  423. if (customCellStyle != null)
  424. {
  425. cell.CellStyle = customCellStyle.Style;
  426. }
  427. }
  428. }
  429. }
  430. MemoryStream file = new MemoryStream();
  431. hssfworkbook.Write(file);
  432. byte[] b = file.ToArray();
  433. hssfworkbook = null;
  434. file.Close();
  435. file.Dispose();
  436. return b;
  437. //HttpContext.Current.Response.BinaryWrite(file.GetBuffer());
  438. //HttpContext.Current.Response.End();
  439. }
  440. /// <summary>
  441. /// 将指定路径的文件,写入table中,不带列标题,返回该DataTable
  442. /// </summary>
  443. /// <param name="FilePath">导入数据文件路径</param>
  444. /// <returns></returns>
  445. public DataTable Import(string FilePath)
  446. {
  447. DataTable dt = new DataTable();
  448. HSSFWorkbook wk = new HSSFWorkbook(File.Open(FilePath, FileMode.Open));
  449. ISheet sheet = wk.GetSheetAt(0);
  450. int rowCount = sheet.PhysicalNumberOfRows;
  451. int columnCount = sheet.GetRow(0).PhysicalNumberOfCells;
  452. try
  453. {
  454. for (int i = 0; i < columnCount; i++)
  455. {
  456. dt.Columns.Add(i.ToString());
  457. }
  458. for (int i = 0; i < rowCount; i++)
  459. {
  460. DataRow row = dt.NewRow();
  461. for (int y = 0; y < columnCount; y++)
  462. {
  463. row[y] = sheet.GetRow(i).GetCell(y);
  464. }
  465. dt.Rows.Add(row);
  466. }
  467. }
  468. catch (Exception e)
  469. { }
  470. sheet = null;
  471. wk = null;
  472. return dt;
  473. }
  474. /// <summary>
  475. /// 将指定路径的文件,写入table中,带列标题,返回该DataTable
  476. /// </summary>
  477. /// <param name="FilePath"></param>
  478. /// <returns></returns>
  479. public DataTable ImpotColumns(string FilePath)
  480. {
  481. DataTable dt = new DataTable();
  482. HSSFWorkbook wk = new HSSFWorkbook(File.Open(FilePath, FileMode.Open));
  483. ISheet sheet = wk.GetSheetAt(0);
  484. int rowCount = sheet.PhysicalNumberOfRows;
  485. int columnCount = sheet.GetRow(0).PhysicalNumberOfCells;
  486. try
  487. {
  488. for (int i = 0; i < columnCount; i++)
  489. {
  490. DataColumn dtColumn = new DataColumn(sheet.GetRow(0).GetCell(i).StringCellValue);
  491. dt.Columns.Add(dtColumn);
  492. // dt.Columns.Add(i.ToString());
  493. }
  494. for (int i = 1; i < rowCount; i++)
  495. {
  496. DataRow row = dt.NewRow();
  497. for (int y = 0; y < columnCount; y++)
  498. {
  499. row[y] = sheet.GetRow(i).GetCell(y);
  500. }
  501. dt.Rows.Add(row);
  502. }
  503. }
  504. catch (Exception e)
  505. { }
  506. sheet = null;
  507. wk = null;
  508. return dt;
  509. }
  510. /// <summary>
  511. /// 将指定路径的文件,写入DataSet中,带列标题,返回该DataSet
  512. /// </summary>
  513. /// <param name="FilePath"></param>
  514. /// <returns></returns>
  515. public DataSet ImpotAllExcel(string FilePath)
  516. {
  517. var ds = new DataSet();
  518. HSSFWorkbook wk = new HSSFWorkbook(File.Open(FilePath, FileMode.Open));
  519. for (int sheetIndex = 0; sheetIndex < wk.NumberOfSheets; sheetIndex++)
  520. {
  521. ISheet sheet = wk.GetSheetAt(sheetIndex);
  522. DataTable dt = new DataTable(sheet.SheetName);
  523. int rowCount = sheet.PhysicalNumberOfRows;
  524. int columnCount = sheet.GetRow(0).PhysicalNumberOfCells;
  525. try
  526. {
  527. for (int i = 0; i < columnCount; i++)
  528. {
  529. DataColumn dtColumn = new DataColumn(sheet.GetRow(0).GetCell(i).StringCellValue);
  530. dt.Columns.Add(dtColumn);
  531. }
  532. for (int i = 1; i < rowCount; i++)
  533. {
  534. var row = sheet.GetRow(i);
  535. DataRow drRow = dt.NewRow();
  536. for (int y = 0; y < columnCount; y++)
  537. {
  538. drRow[y] = row.GetCell(y);
  539. }
  540. dt.Rows.Add(drRow);
  541. }
  542. }
  543. catch (Exception e)
  544. { }
  545. sheet = null;
  546. ds.Tables.Add(dt);
  547. }
  548. wk = null;
  549. return ds;
  550. }
  551. /// <summary>
  552. /// 上传文件
  553. /// </summary>
  554. /// <param name="path">路径</param>
  555. public void SaveAs(Stream fileStream, string filePath)
  556. {
  557. FileStream stream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None);
  558. int bufferLen = 4096;
  559. byte[] buffer = new byte[bufferLen];
  560. int count = 0;
  561. while ((count = fileStream.Read(buffer, 0, bufferLen)) > 0)
  562. {
  563. stream.Write(buffer, 0, count);
  564. }
  565. stream.Close();
  566. fileStream.Close();
  567. stream.Dispose();
  568. fileStream.Dispose();
  569. }
  570. /// <summary>
  571. /// 创建一个包含多个列名的excel,返回创建的文件路径
  572. /// </summary>
  573. /// <param name="Columns">列名</param>
  574. /// <returns></returns>
  575. public string CreateFile(string[] Columns)
  576. {
  577. string path = HttpContext.Current.Server.MapPath(Function.GetTempFile()) + Function.GetGUID() + ".xls";
  578. try
  579. {
  580. HSSFWorkbook wk = new HSSFWorkbook();
  581. ISheet sheet = wk.CreateSheet("sheet1");
  582. IRow row = sheet.CreateRow(0);
  583. for (int i = 0; i < Columns.Length; i++)
  584. {
  585. ICell cell = row.CreateCell(i);
  586. cell.SetCellValue(Columns[i]);
  587. }
  588. FileStream stream = new FileStream(path, FileMode.Create);
  589. wk.Write(stream);
  590. stream.Dispose();
  591. wk = null;
  592. return path;
  593. }
  594. catch (Exception e)
  595. {
  596. return e.ToString();
  597. }
  598. }
  599. /// <summary>
  600. /// 导出数据到服务器
  601. /// </summary>
  602. /// <param name="dtSource">数据源</param>
  603. /// <param name="filpath">保存路径</param>
  604. public void SaveInServer(DataTable dtSource, string filpath)
  605. {
  606. //HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
  607. //HttpContext.Current.Response.Clear();
  608. HSSFWorkbook hssfworkbook = new HSSFWorkbook();
  609. ISheet sheet1 = hssfworkbook.CreateSheet("Sheet1");
  610. //默认宽度-高度
  611. sheet1.DefaultColumnWidth = 1 * 15;
  612. short color_BLACK = HSSFColor.BLACK.index;
  613. ICellStyle style = hssfworkbook.CreateCellStyle();
  614. style.BorderBottom = BorderStyle.THICK;
  615. style.BorderLeft = BorderStyle.THICK;
  616. style.BorderRight = BorderStyle.THICK;
  617. style.BorderTop = BorderStyle.THICK;
  618. style.Alignment = HorizontalAlignment.CENTER; ;
  619. style.VerticalAlignment = VerticalAlignment.CENTER; ;
  620. //设置字体
  621. IFont font = hssfworkbook.CreateFont();
  622. font.FontHeightInPoints = 12;//字号
  623. font.Boldweight = (short)FontBoldWeight.BOLD;//粗体
  624. style.SetFont(font);
  625. var customerStyleGroupList = _cellStyleList
  626. .Select(x => new { Style = x.Key.Invoke(hssfworkbook), CellList = x.Select(w => new { w.RowIndex, w.ColumnIndex }).ToList() })
  627. .ToList();
  628. if (dtSource.Columns.Count > 0)
  629. {
  630. IRow row = sheet1.CreateRow(0);
  631. for (int i = 0; i < dtSource.Columns.Count; i++)
  632. {
  633. ICell cell = row.CreateCell(i);
  634. cell.SetCellValue(dtSource.Columns[i] != null ? dtSource.Columns[i].ToString() : "");
  635. var customCellStyle = customerStyleGroupList.FirstOrDefault(x => x.CellList.Any(w => w.ColumnIndex == i && w.RowIndex == 0));
  636. if (customCellStyle != null)
  637. {
  638. cell.CellStyle = customCellStyle.Style;
  639. }
  640. else
  641. {
  642. cell.CellStyle = style;
  643. }
  644. }
  645. }
  646. if (dtSource.Rows.Count > 0)
  647. {
  648. for (int i = 0; i < dtSource.Rows.Count; i++)
  649. {
  650. IRow rowsub = sheet1.CreateRow(i + 1);
  651. for (int j = 0; j < dtSource.Columns.Count; j++)
  652. {
  653. var cell = rowsub.CreateCell(j);
  654. if (dtSource.Rows[i][j] != null && dtSource.Rows[i][j] != "")
  655. {
  656. cell.SetCellValue(dtSource.Rows[i][j].ToString());
  657. }
  658. else
  659. {
  660. cell.SetCellValue(dtSource.Rows[i][j] as string);
  661. }
  662. var customCellStyle = customerStyleGroupList.FirstOrDefault(x => x.CellList.Any(w => w.ColumnIndex == j && w.RowIndex == i));
  663. if (customCellStyle != null)
  664. {
  665. cell.CellStyle = customCellStyle.Style;
  666. }
  667. }
  668. }
  669. }
  670. FileStream fs = new FileStream(filpath, FileMode.Create);
  671. hssfworkbook.Write(fs);
  672. fs.Dispose();
  673. hssfworkbook = null;
  674. }
  675. public void SaveInServer(DataSet dsSource, string filpath)
  676. {
  677. HSSFWorkbook hssfworkbook = new HSSFWorkbook();
  678. foreach (DataTable dtSource in dsSource.Tables)
  679. {
  680. ISheet sheet1 = hssfworkbook.CreateSheet(dtSource.TableName);
  681. //默认宽度-高度
  682. sheet1.DefaultColumnWidth = 1 * 15;
  683. short color_BLACK = HSSFColor.BLACK.index;
  684. ICellStyle style = hssfworkbook.CreateCellStyle();
  685. style.BorderBottom = BorderStyle.THICK;
  686. style.BorderLeft = BorderStyle.THICK;
  687. style.BorderRight = BorderStyle.THICK;
  688. style.BorderTop = BorderStyle.THICK;
  689. style.Alignment = HorizontalAlignment.CENTER; ;
  690. style.VerticalAlignment = VerticalAlignment.CENTER; ;
  691. //设置字体
  692. IFont font = hssfworkbook.CreateFont();
  693. font.FontHeightInPoints = 12;//字号
  694. font.Boldweight = (short)FontBoldWeight.BOLD;//粗体
  695. style.SetFont(font);
  696. var customerStyleGroupList = _cellStyleList
  697. .Select(x => new { Style = x.Key.Invoke(hssfworkbook), CellList = x.Select(w => new { w.RowIndex, w.ColumnIndex }).ToList() })
  698. .ToList();
  699. if (dtSource.Columns.Count > 0)
  700. {
  701. IRow row = sheet1.CreateRow(0);
  702. for (int i = 0; i < dtSource.Columns.Count; i++)
  703. {
  704. ICell cell = row.CreateCell(i);
  705. cell.SetCellValue(dtSource.Columns[i] != null ? dtSource.Columns[i].ToString() : "");
  706. var customCellStyle = customerStyleGroupList.FirstOrDefault(x => x.CellList.Any(w => w.ColumnIndex == i && w.RowIndex == 0));
  707. if (customCellStyle != null)
  708. {
  709. cell.CellStyle = customCellStyle.Style;
  710. }
  711. else
  712. {
  713. cell.CellStyle = style;
  714. }
  715. }
  716. }
  717. if (dtSource.Rows.Count > 0)
  718. {
  719. for (int i = 0; i < dtSource.Rows.Count; i++)
  720. {
  721. IRow rowsub = sheet1.CreateRow(i + 1);
  722. for (int j = 0; j < dtSource.Columns.Count; j++)
  723. {
  724. var cell = rowsub.CreateCell(j);
  725. if (dtSource.Rows[i][j] != null && dtSource.Rows[i][j] != "")
  726. {
  727. cell.SetCellValue(dtSource.Rows[i][j].ToString());
  728. }
  729. else
  730. {
  731. cell.SetCellValue(dtSource.Rows[i][j] as string);
  732. }
  733. var customCellStyle = customerStyleGroupList.FirstOrDefault(x => x.CellList.Any(w => w.ColumnIndex == j && w.RowIndex == i));
  734. if (customCellStyle != null)
  735. {
  736. cell.CellStyle = customCellStyle.Style;
  737. }
  738. }
  739. }
  740. }
  741. }
  742. FileStream fs = new FileStream(filpath, FileMode.Create);
  743. hssfworkbook.Write(fs);
  744. fs.Dispose();
  745. hssfworkbook = null;
  746. }
  747. public static DataTable ToDataTable<T>(List<T> items)
  748. {
  749. DataTable dataTable = new DataTable(typeof(T).Name);
  750. //Get all the properties
  751. PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
  752. foreach (PropertyInfo prop in Props)
  753. {
  754. if (GetDefault(prop.PropertyType.FullName) != null)
  755. {
  756. //Setting column names as Property names
  757. dataTable.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
  758. }
  759. }
  760. foreach (T item in items)
  761. {
  762. if (item != null)
  763. {
  764. DataRow dr = dataTable.NewRow();
  765. foreach (PropertyInfo prop in Props)
  766. {
  767. if (GetDefault(prop.PropertyType.FullName) != null)
  768. {
  769. //inserting property values to datatable rows
  770. dr[prop.Name] = prop.GetValue(item, null) ?? GetDefault(prop.PropertyType.FullName);
  771. }
  772. }
  773. dataTable.Rows.Add(dr);
  774. }
  775. }
  776. //put a breakpoint here and check datatable
  777. return dataTable;
  778. }
  779. public static object GetDefault(string dataType)
  780. {
  781. if (dataType.Contains("System.String"))
  782. {
  783. return string.Empty;
  784. }
  785. if (dataType.Contains("System.Boolean"))
  786. {
  787. return false;
  788. }
  789. if (dataType.Contains("System.Decimal"))
  790. {
  791. return 0.0;
  792. }
  793. if (dataType.Contains("System.DateTime"))
  794. {
  795. return DateTime.MinValue;
  796. }
  797. if (dataType.Contains("System.Int64"))
  798. {
  799. return 0;
  800. }
  801. if (dataType.Contains("System.Guid"))
  802. {
  803. return null;
  804. }
  805. if (dataType.Contains("System.Int16"))
  806. {
  807. return 0;
  808. }
  809. if (dataType.Contains("Int32"))
  810. {
  811. return 0;
  812. }
  813. if (dataType.Contains("System.Object"))
  814. {
  815. return null;
  816. }
  817. return null;
  818. }
  819. public string Path { get; set; }
  820. internal HSSFWorkbook Wookbook { get; set; }
  821. internal ISheet Sheet { get; set; }
  822. /// <summary>
  823. /// 创建一个包含多个列名的excel,返回创建的文件路径
  824. /// </summary>
  825. /// <param name="Columns">列名</param>
  826. /// <returns></returns>
  827. public static NpoiExcelHelper Create(string[] Columns)
  828. {
  829. NpoiExcelHelper excelHelper = new NpoiExcelHelper();
  830. excelHelper.Path = HttpContext.Current.Server.MapPath(Function.GetTempFile()) + Function.GetGUID() + ".xls";
  831. try
  832. {
  833. excelHelper.Wookbook = new HSSFWorkbook();
  834. excelHelper.Sheet = excelHelper.Wookbook.CreateSheet("sheet1");
  835. IRow row = excelHelper.Sheet.CreateRow(0);
  836. for (int i = 0; i < Columns.Length; i++)
  837. {
  838. ICell cell = row.CreateCell(i);
  839. cell.SetCellValue(Columns[i]);
  840. }
  841. return excelHelper;
  842. }
  843. catch (Exception e)
  844. {
  845. throw e;
  846. }
  847. }
  848. public ICellStyle CreateStyle()
  849. {
  850. return Wookbook.CreateCellStyle();
  851. }
  852. public void SetValue(DataTable dtSource, ICellStyle headerStyle = null, ICellStyle cellStyle = null)
  853. {
  854. var customerStyleGroupList = _cellStyleList
  855. .Select(x => new { Style = x.Key.Invoke(Wookbook), CellList = x.Select(w => new { w.RowIndex, w.ColumnIndex }).ToList() })
  856. .ToList();
  857. if (dtSource.Columns.Count > 0)
  858. {
  859. IRow row = Sheet.CreateRow(0);
  860. for (int i = 0; i < dtSource.Columns.Count; i++)
  861. {
  862. ICell cell = row.CreateCell(i);
  863. cell.SetCellValue(dtSource.Columns[i] != null ? dtSource.Columns[i].ToString() : "");
  864. var customCellStyle = customerStyleGroupList.FirstOrDefault(x => x.CellList.Any(w => w.ColumnIndex == i && w.RowIndex == 0));
  865. if (customCellStyle != null)
  866. {
  867. cell.CellStyle = customCellStyle.Style;
  868. }
  869. if (headerStyle != null)
  870. {
  871. cell.CellStyle = headerStyle;
  872. }
  873. }
  874. }
  875. if (dtSource.Rows.Count > 0)
  876. {
  877. for (int i = 0; i < dtSource.Rows.Count; i++)
  878. {
  879. IRow rowsub = Sheet.CreateRow(i + 1);
  880. for (int j = 0; j < dtSource.Columns.Count; j++)
  881. {
  882. ICell cell;
  883. cell = rowsub.CreateCell(j);
  884. if (dtSource.Rows[i][j] != null && dtSource.Rows[i][j] != "")
  885. {
  886. cell.SetCellValue(dtSource.Rows[i][j].ToString());
  887. }
  888. else
  889. {
  890. cell.SetCellValue(dtSource.Rows[i][j] as string);
  891. }
  892. var customCellStyle = customerStyleGroupList.FirstOrDefault(x => x.CellList.Any(w => w.ColumnIndex == j && w.RowIndex == i));
  893. if (customCellStyle != null)
  894. {
  895. cell.CellStyle = customCellStyle.Style;
  896. }
  897. if (cellStyle != null)
  898. {
  899. cell.CellStyle = cellStyle;
  900. }
  901. }
  902. }
  903. }
  904. }
  905. public void MergeColumn(int firstRow, int lastRow, int firstColumn, int lastColumn)
  906. {
  907. Sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(firstRow, lastRow, firstColumn, lastColumn));
  908. }
  909. public void DrawBorder(int firstRow, int lastRow, int firstColumn, int lastColumn)
  910. {
  911. var cellRange = new NPOI.SS.Util.CellRangeAddress(firstRow, lastRow, firstColumn, lastColumn);
  912. for (int i = 0; i <= (lastRow - firstRow); i++)
  913. {
  914. var row = Sheet.GetRow(i + firstRow);
  915. for (int j = 0; j <= (lastColumn - firstColumn); j++)
  916. {
  917. var cell = row.GetCell(j + firstColumn);
  918. cell.CellStyle.BorderTop = BorderStyle.THICK;
  919. cell.CellStyle.BorderBottom = BorderStyle.THICK;
  920. cell.CellStyle.BorderLeft = BorderStyle.THICK;
  921. cell.CellStyle.BorderRight = BorderStyle.THICK;
  922. }
  923. }
  924. }
  925. public void Save()
  926. {
  927. try
  928. {
  929. FileStream stream = new FileStream(Path, FileMode.Create);
  930. Wookbook.Write(stream);
  931. stream.Dispose();
  932. }
  933. catch (Exception ex)
  934. {
  935. throw ex;
  936. }
  937. }
  938. public void Dispose()
  939. {
  940. Path = null;
  941. Sheet = null;
  942. Wookbook = null;
  943. }
  944. #region 从Excel取数据并记录到List集合里
  945. /// <summary>
  946. /// 从Excel取数据并记录到List集合里
  947. /// </summary>
  948. /// <param name="cellHeard">单元头的Key和Value:{ { "Author", "作者" }, { "Price", "单价" } };</param>
  949. /// <param name="filePath">保存文件绝对路径</param>
  950. /// <param name="errorMsg">错误信息</param>
  951. /// <returns>转换后的List对象集合</returns>
  952. public static List<T> ExcelToEntityList<T>(Dictionary<string, string> cellHeard, string filePath, out StringBuilder errorMsg, out List<T> errList) where T : new()
  953. {
  954. List<T> enlist = new List<T>();
  955. errorMsg = new StringBuilder();
  956. errList = new List<T>();
  957. try
  958. {
  959. if (Regex.IsMatch(filePath, ".xls$")) // 2003
  960. {
  961. enlist = Excel2003ToEntityList<T>(cellHeard, filePath, out errorMsg, out errList);
  962. }
  963. else if (Regex.IsMatch(filePath, ".xlsx$")) // 2007
  964. {
  965. enlist = Excel2007ToEntityList<T>(cellHeard, filePath, out errorMsg, out errList);
  966. }
  967. return enlist;
  968. }
  969. catch (Exception ex)
  970. {
  971. throw ex;
  972. }
  973. }
  974. #endregion
  975. #region 从Excel2003取数据并记录到List集合里
  976. /// <summary>
  977. /// 从Excel2003取数据并记录到List集合里
  978. /// </summary>
  979. /// <param name="cellHeard">单元头的Key和Value:{ { "Author", "作者" }, { "Price", "单价" } };</param>
  980. /// <param name="filePath">保存文件绝对路径</param>
  981. /// <param name="errorMsg">错误信息</param>
  982. /// <returns>转换好的List对象集合</returns>
  983. private static List<T> Excel2003ToEntityList<T>(Dictionary<string, string> cellHeard, string filePath, out StringBuilder errorMsg, out List<T> errList) where T : new()
  984. {
  985. try
  986. {
  987. using (FileStream fs = File.OpenRead(filePath))
  988. {
  989. HSSFWorkbook workbook = new HSSFWorkbook(fs);
  990. HSSFSheet sheet = (HSSFSheet)workbook.GetSheetAt(0); // 获取此文件第一个Sheet页
  991. return ExcelToEntityList(cellHeard, sheet, out errorMsg, out errList);
  992. }
  993. }
  994. catch (Exception ex)
  995. {
  996. throw ex;
  997. }
  998. }
  999. #endregion
  1000. #region 从Excel2007取数据并记录到List集合里
  1001. /// <summary>
  1002. /// 从Excel2007取数据并记录到List集合里
  1003. /// </summary>
  1004. /// <param name="cellHeard">单元头的Key和Value:{ { "Author", "作者" }, { "Price", "单价" } };</param>
  1005. /// <param name="filePath">保存文件绝对路径</param>
  1006. /// <param name="errorMsg">错误信息</param>
  1007. /// <returns>转换好的List对象集合</returns>
  1008. private static List<T> Excel2007ToEntityList<T>(Dictionary<string, string> cellHeard, string filePath, out StringBuilder errorMsg, out List<T> errList) where T : new()
  1009. {
  1010. try
  1011. {
  1012. using (FileStream fs = File.OpenRead(filePath))
  1013. {
  1014. XSSFWorkbook workbook = new XSSFWorkbook(fs);
  1015. XSSFSheet sheet = (XSSFSheet)workbook.GetSheetAt(0); // 获取此文件第一个Sheet页
  1016. return ExcelToEntityList(cellHeard, sheet, out errorMsg, out errList);
  1017. }
  1018. }
  1019. catch (Exception ex)
  1020. {
  1021. throw ex;
  1022. }
  1023. }
  1024. #endregion
  1025. private static List<T> ExcelToEntityList<T>(Dictionary<string, string> cellHeard, ISheet sheet, out StringBuilder errorMsg, out List<T> errList) where T : new()
  1026. {
  1027. errorMsg = new StringBuilder(); // 错误信息,Excel转换到实体对象时,会有格式的错误信息
  1028. errList = new List<T>();//将错误的数据记录在集合中
  1029. List<T> enlist = new List<T>(); // 转换后的集合
  1030. List<string> keys = cellHeard.Keys.ToList(); // 要赋值的实体对象属性名称
  1031. List<string> vals = cellHeard.Values.ToList(); // 属性名称
  1032. IRow row = sheet.GetRow(0);
  1033. for (int i = 0; i < vals.Count; i++)
  1034. {
  1035. //string cellValer = row.Cells[i].ToString();
  1036. if (!row.Cells.Select(x => x.StringCellValue).Contains(vals[i]))//判断Excel列名是否在单元头中存在
  1037. {
  1038. throw new Exception("Excel导入列信息不完整。");
  1039. }
  1040. }
  1041. for (int i = 1; i <= sheet.LastRowNum; i++) // 从1开始,第0行为单元头
  1042. {
  1043. // 1.判断当前行是否空行,若空行就不在进行读取下一行操作,结束Excel读取操作
  1044. if (sheet.GetRow(i) == null)
  1045. {
  1046. continue;
  1047. }
  1048. if (sheet.GetRow(i).Cells.Count == 0)
  1049. {
  1050. continue;
  1051. }
  1052. if (sheet.GetRow(i) != null && string.IsNullOrWhiteSpace(sheet.GetRow(i).Cells.FirstOrDefault().ToString()))//TODO:针对于Excel清除内容读取的空白行做调整
  1053. {
  1054. continue;
  1055. }
  1056. T en = new T();
  1057. string errStr = ""; // 当前行转换时,是否有错误信息,格式为:第1行数据转换异常:XXX列;
  1058. for (int j = 0; j < keys.Count; j++)
  1059. {
  1060. // 2.若属性头的名称包含'.',就表示是子类里的属性,那么就要遍历子类,eg:UserEn.TrueName
  1061. if (keys[j].IndexOf(".") >= 0)
  1062. {
  1063. // 2.1解析子类属性
  1064. string[] properotyArray = keys[j].Split(new string[] { "." }, StringSplitOptions.RemoveEmptyEntries);
  1065. string subClassName = properotyArray[0]; // '.'前面的为子类的名称
  1066. string subClassProperotyName = properotyArray[1]; // '.'后面的为子类的属性名称
  1067. System.Reflection.PropertyInfo subClassInfo = en.GetType().GetProperty(subClassName); // 获取子类的类型
  1068. if (subClassInfo != null)
  1069. {
  1070. // 2.1.1 获取子类的实例
  1071. var subClassEn = en.GetType().GetProperty(subClassName).GetValue(en, null);
  1072. // 2.1.2 根据属性名称获取子类里的属性信息
  1073. System.Reflection.PropertyInfo properotyInfo = subClassInfo.PropertyType.GetProperty(subClassProperotyName);
  1074. if (properotyInfo != null)
  1075. {
  1076. try
  1077. {
  1078. // Excel单元格的值转换为对象属性的值,若类型不对,记录出错信息
  1079. properotyInfo.SetValue(subClassEn, GetExcelCellToProperty(properotyInfo.PropertyType, sheet.GetRow(i).GetCell(j)), null);
  1080. }
  1081. catch (Exception e)
  1082. {
  1083. if (errStr.Length == 0)
  1084. {
  1085. errStr = "第" + i + "行数据转换异常:";
  1086. }
  1087. errStr += cellHeard[keys[j]] + "列;";
  1088. errList.Add(en);//将错误的数据记录起来
  1089. }
  1090. }
  1091. }
  1092. }
  1093. else
  1094. {
  1095. // 3.给指定的属性赋值
  1096. System.Reflection.PropertyInfo properotyInfo = en.GetType().GetProperty(keys[j]);
  1097. if (properotyInfo != null)
  1098. {
  1099. try
  1100. {
  1101. // Excel单元格的值转换为对象属性的值,若类型不对,记录出错信息
  1102. properotyInfo.SetValue(en, GetExcelCellToProperty(properotyInfo.PropertyType, sheet.GetRow(i).GetCell(j)), null);
  1103. }
  1104. catch (Exception e)
  1105. {
  1106. if (errStr.Length == 0)
  1107. {
  1108. errStr = "第" + i + "行数据转换异常:";
  1109. }
  1110. errStr += cellHeard[keys[j]] + "列;";
  1111. errList.Add(en);//将错误的数据记录起来
  1112. }
  1113. }
  1114. }
  1115. }
  1116. // 若有错误信息,就添加到错误信息里
  1117. if (errStr.Length > 0)
  1118. {
  1119. errorMsg.AppendLine(errStr);
  1120. }
  1121. enlist.Add(en);
  1122. }
  1123. return enlist;
  1124. }
  1125. #region 从Excel获取值传递到对象的属性里
  1126. /// <summary>
  1127. /// 从Excel获取值传递到对象的属性里
  1128. /// </summary>
  1129. /// <param name="distanceType">目标对象类型</param>
  1130. /// <param name="sourceCell">对象属性的值</param>
  1131. private static Object GetExcelCellToProperty(Type distanceType, ICell sourceCell)
  1132. {
  1133. object rs = distanceType.IsValueType ? Activator.CreateInstance(distanceType) : null;
  1134. // 1.判断传递的单元格是否为空
  1135. if (sourceCell == null || string.IsNullOrEmpty(sourceCell.ToString()))
  1136. {
  1137. return rs;
  1138. }
  1139. // 2.Excel文本和数字单元格转换,在Excel里文本和数字是不能进行转换,所以这里预先存值
  1140. object sourceValue = null;
  1141. switch (sourceCell.CellType)
  1142. {
  1143. case CellType.BLANK:
  1144. break;
  1145. case CellType.BOOLEAN: sourceValue = sourceCell.BooleanCellValue;
  1146. break;
  1147. case CellType.ERROR: sourceValue = sourceCell.ErrorCellValue;
  1148. break;
  1149. case CellType.FORMULA: sourceValue = sourceCell.CellFormula;
  1150. break;
  1151. case CellType.NUMERIC: sourceValue = sourceCell.NumericCellValue;
  1152. break;
  1153. case CellType.STRING: sourceValue = sourceCell.StringCellValue;
  1154. break;
  1155. case CellType.Unknown:
  1156. break;
  1157. default:
  1158. break;
  1159. }
  1160. string valueDataType = distanceType.Name;
  1161. // 在这里进行特定类型的处理
  1162. switch (valueDataType.ToLower()) // 以防出错,全部小写
  1163. {
  1164. case "string":
  1165. rs = sourceValue.ToString();
  1166. break;
  1167. case "int":
  1168. case "int16":
  1169. case "int32":
  1170. rs = (int)Convert.ChangeType(sourceCell.NumericCellValue.ToString(), distanceType);
  1171. break;
  1172. case "float":
  1173. case "nullable`1": //由于ChangeType无法强制转换可空类型 所以对单价为空的数据做处理
  1174. rs = (decimal?)Convert.ChangeType(sourceCell.NumericCellValue.ToString(), (Nullable.GetUnderlyingType(distanceType) ?? distanceType));
  1175. break;
  1176. case "single":
  1177. rs = (float)Convert.ChangeType(sourceCell.NumericCellValue.ToString(), distanceType);
  1178. break;
  1179. case "datetime":
  1180. rs = sourceCell.DateCellValue;
  1181. break;
  1182. case "guid":
  1183. rs = (Guid)Convert.ChangeType(sourceCell.NumericCellValue.ToString(), distanceType);
  1184. return rs;
  1185. }
  1186. return rs;
  1187. }
  1188. #endregion
  1189. #region Excel导出
  1190. /// <summary>
  1191. /// 实体类集合导出到EXCLE2003
  1192. /// </summary>
  1193. /// <param name="cellHeard">单元头的Key和Value:{ { "UserName", "姓名" }, { "Age", "年龄" } };</param>
  1194. /// <param name="enList">数据源</param>
  1195. /// <param name="sheetName">工作表名称</param>
  1196. /// <returns>文件的下载地址</returns>
  1197. private static string _ImportFileVirtualFolder;
  1198. /// <summary>
  1199. /// 导入文件的储存地址
  1200. /// </summary>
  1201. public static string ImportFileVirtualFolder
  1202. {
  1203. get
  1204. {
  1205. if (string.IsNullOrEmpty(_ImportFileVirtualFolder))
  1206. _ImportFileVirtualFolder = GetAppSettingValue<string>("ImportFileVirtualFolder");
  1207. return _ImportFileVirtualFolder;
  1208. }
  1209. }
  1210. public static string EntityListToExcel2003(Dictionary<string, string> cellHeard, IList enList, string sheetName, string filestr, List<NpoiExcelCellStyle> cellStyleList = null)
  1211. {
  1212. try
  1213. {
  1214. if (cellStyleList == null)
  1215. {
  1216. cellStyleList = new List<NpoiExcelCellStyle>();
  1217. }
  1218. string fileName = Guid.NewGuid() + ".xls"; // 文件名称
  1219. string urlPath = string.Format("{0}{1}/{2}", ImportFileVirtualFolder, DateTime.Now.ToString("yyyy-MM-dd"), fileName); // 文件下载的URL地址,供给前台下载
  1220. string filePath = HttpContext.Current.Server.MapPath(urlPath); // 文件路径
  1221. // 1.检测是否存在文件夹,若不存在就建立个文件夹
  1222. filePath = HttpContext.Current.Server.MapPath(string.Format("{0}//{1}//{2}", ImportFileVirtualFolder, DateTime.Now.ToString("yyyy-MM-dd"), fileName));
  1223. string directoryName = System.IO.Path.GetDirectoryName(filePath);// System.IO.Path.GetDirectoryName(filePath);
  1224. if (!Directory.Exists(directoryName))
  1225. {
  1226. Directory.CreateDirectory(directoryName);
  1227. }
  1228. // 2.解析单元格头部,设置单元头的中文名称
  1229. IWorkbook workbook = new HSSFWorkbook(); // 工作簿
  1230. ISheet sheet = workbook.CreateSheet(sheetName); // 工作表
  1231. IRow row = sheet.CreateRow(0);
  1232. List<string> keys = cellHeard.Keys.ToList();
  1233. ICellStyle style = workbook.CreateCellStyle();//设置行样式;
  1234. ICellStyle cellStyle = setCellStyle(workbook);//设置行样式;
  1235. IFont font = workbook.CreateFont();//设置字体样式
  1236. font.Color = HSSFColor.OLIVE_GREEN.RED.index;
  1237. //设置字体加粗样式
  1238. font.Boldweight = short.MaxValue;
  1239. style.SetFont(font);
  1240. for (int i = 0; i < keys.Count; i++)
  1241. {
  1242. var cell = row.CreateCell(i);
  1243. cell.SetCellValue(cellHeard[keys[i]]); // 列名为Key的值
  1244. row.RowStyle = style;
  1245. var customCellStyle = cellStyleList.FirstOrDefault(x => x.ColumnIndex == i && x.RowIndex == 0);
  1246. if (customCellStyle != null)
  1247. {
  1248. cell.CellStyle = customCellStyle.StyleFunc.Invoke(workbook);
  1249. }
  1250. }
  1251. // 3.List对象的值赋值到Excel的单元格里
  1252. int rowIndex = 1; // 从第二行开始赋值(第一行已设置为单元头)
  1253. foreach (var en in enList)
  1254. {
  1255. IRow rowTmp = sheet.CreateRow(rowIndex);
  1256. for (int i = 0; i < keys.Count; i++) // 根据指定的属性名称,获取对象指定属性的值
  1257. {
  1258. string cellValue = ""; // 单元格的值
  1259. object properotyValue = null; // 属性的值
  1260. System.Reflection.PropertyInfo properotyInfo = null; // 属性的信息
  1261. // 3.1 若属性头的名称包含'.',就表示是子类里的属性,那么就要遍历子类,eg:UserEn.UserName
  1262. if (keys[i].IndexOf(".") >= 0)
  1263. {
  1264. // 3.1.1 解析子类属性(这里只解析1层子类,多层子类未处理)
  1265. string[] properotyArray = keys[i].Split(new string[] { "." }, StringSplitOptions.RemoveEmptyEntries);
  1266. string subClassName = properotyArray[0]; // '.'前面的为子类的名称
  1267. string subClassProperotyName = properotyArray[1]; // '.'后面的为子类的属性名称
  1268. System.Reflection.PropertyInfo subClassInfo = en.GetType().GetProperty(subClassName); // 获取子类的类型
  1269. if (subClassInfo != null)
  1270. {
  1271. // 3.1.2 获取子类的实例
  1272. var subClassEn = en.GetType().GetProperty(subClassName).GetValue(en, null);
  1273. // 3.1.3 根据属性名称获取子类里的属性类型
  1274. properotyInfo = subClassInfo.PropertyType.GetProperty(subClassProperotyName);
  1275. if (properotyInfo != null)
  1276. {
  1277. properotyValue = properotyInfo.GetValue(subClassEn, null); // 获取子类属性的值
  1278. }
  1279. }
  1280. }
  1281. else
  1282. {
  1283. // 3.2 若不是子类的属性,直接根据属性名称获取对象对应的属性
  1284. properotyInfo = en.GetType().GetProperty(keys[i]);
  1285. if (properotyInfo != null)
  1286. {
  1287. properotyValue = properotyInfo.GetValue(en, null);
  1288. }
  1289. }
  1290. // 3.3 属性值经过转换赋值给单元格值
  1291. if (properotyValue != null)
  1292. {
  1293. cellValue = properotyValue.ToString();
  1294. // 3.3.1 对时间初始值赋值为空
  1295. if (cellValue.Trim() == "0001/1/1 0:00:00" || cellValue.Trim() == "0001/1/1 23:59:59")
  1296. {
  1297. cellValue = "";
  1298. }
  1299. }
  1300. // 3.4 填充到Excel的单元格里
  1301. // rowTmp.CreateCell(i).SetCellValue(cellValue);
  1302. ICell cell1 = rowTmp.CreateCell(i);
  1303. cell1.SetCellValue(cellValue);
  1304. var customCellStyle = cellStyleList.FirstOrDefault(x => x.ColumnIndex == i && x.RowIndex == rowIndex);
  1305. if (customCellStyle != null)
  1306. {
  1307. cell1.CellStyle = customCellStyle.StyleFunc.Invoke(workbook);
  1308. }
  1309. else if (keys[i].Equals("ErrorMessage"))//异常信息标红
  1310. {
  1311. cell1.CellStyle = cellStyle;
  1312. }
  1313. }
  1314. rowIndex++;
  1315. }
  1316. // 4.生成文件
  1317. FileStream file = new FileStream(filePath, FileMode.Create);
  1318. workbook.Write(file);
  1319. file.Close();
  1320. // 5.返回下载路径
  1321. return urlPath;
  1322. }
  1323. catch (Exception ex)
  1324. {
  1325. throw ex;
  1326. }
  1327. }
  1328. //设置单元格字体颜色
  1329. private static HSSFCellStyle setCellStyle(IWorkbook workbook)
  1330. {
  1331. HSSFCellStyle fCellStyle = (HSSFCellStyle)workbook.CreateCellStyle();
  1332. HSSFFont ffont = (HSSFFont)workbook.CreateFont();
  1333. //ffont.FontHeight = 20 * 20;
  1334. //ffont.FontName = "宋体";
  1335. ffont.Color = HSSFColor.RED.index;
  1336. fCellStyle.SetFont(ffont);
  1337. return fCellStyle;
  1338. }
  1339. #endregion Excel导出
  1340. #region 获取配置信息
  1341. private static AppSettingsReader _reader;
  1342. private static AppSettingsReader Reader { get { return _reader ?? (_reader = new AppSettingsReader()); } }
  1343. /// <summary>
  1344. /// 从appSettings节中读取相应键值
  1345. /// </summary>
  1346. public static T GetAppSettingValue<T>(string key)
  1347. {
  1348. T result = default(T);
  1349. object value = Reader.GetValue(key, typeof(T));
  1350. if (value != null)
  1351. {
  1352. result = (T)value;
  1353. }
  1354. return result;
  1355. }
  1356. #endregion
  1357. #region 判断是否为兼容 { ".xls", ".xlsx" }
  1358. /// <summary>
  1359. /// 判断是否为兼容 { ".xls", ".xlsx" }
  1360. /// </summary>
  1361. /// <param name="filePath"></param>
  1362. /// <returns></returns>
  1363. public static bool GetIsCompatible(string filePath)
  1364. {
  1365. string ext = System.IO.Path.GetExtension(filePath);
  1366. return new[] { ".xls", ".xlsx" }.Count(e => e.Equals(ext, StringComparison.OrdinalIgnoreCase)) > 0;
  1367. }
  1368. #endregion
  1369. }
  1370. public class NpoiExcelCellStyle
  1371. {
  1372. /// <summary>
  1373. /// 应用样式的列序号,从0开始
  1374. /// </summary>
  1375. public int ColumnIndex { get; set; }
  1376. /// <summary>
  1377. /// 应用样式的行序号,从0开始
  1378. /// </summary>
  1379. public int RowIndex { get; set; }
  1380. public Func<IWorkbook, HSSFCellStyle> StyleFunc { get; set; }
  1381. }
  1382. }