NpoiExcelHelper.cs 72 KB

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