NPOIHelper.cs 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data;
  4. using System.IO;
  5. using System.Text;
  6. using System.Web;
  7. using NPOI;
  8. using NPOI.HPSF;
  9. using NPOI.HSSF;
  10. using NPOI.HSSF.UserModel;
  11. using NPOI.HSSF.Util;
  12. using NPOI.POIFS;
  13. using NPOI.SS.Formula.Eval;
  14. using NPOI.SS.UserModel;
  15. using NPOI.Util;
  16. using NPOI.SS;
  17. using NPOI.DDF;
  18. using NPOI.SS.Util;
  19. using System.Collections;
  20. using System.Text.RegularExpressions;
  21. public class NPOIHelper
  22. {
  23. #region 从datatable中将数据导出到excel
  24. /// <summary>
  25. /// DataTable导出到Excel的MemoryStream
  26. /// </summary>
  27. /// <param name="dtSource">源DataTable</param>
  28. /// <param name="strHeaderText">表头文本</param>
  29. static MemoryStream ExportDT(DataTable dtSource, string strHeaderText)
  30. {
  31. HSSFWorkbook workbook = new HSSFWorkbook();
  32. HSSFSheet sheet = workbook.CreateSheet() as HSSFSheet;
  33. #region 右击文件 属性信息
  34. //{
  35. // DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();
  36. // dsi.Company = "http://www.yongfa365.com/";
  37. // workbook.DocumentSummaryInformation = dsi;
  38. // SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
  39. // si.Author = "柳永法"; //填加xls文件作者信息
  40. // si.ApplicationName = "NPOI测试程序"; //填加xls文件创建程序信息
  41. // si.LastAuthor = "柳永法2"; //填加xls文件最后保存者信息
  42. // si.Comments = "说明信息"; //填加xls文件作者信息
  43. // si.Title = "NPOI测试"; //填加xls文件标题信息
  44. // si.Subject = "NPOI测试Demo"; //填加文件主题信息
  45. // si.CreateDateTime = DateTime.Now;
  46. // workbook.SummaryInformation = si;
  47. //}
  48. #endregion
  49. HSSFCellStyle dateStyle = workbook.CreateCellStyle() as HSSFCellStyle;
  50. HSSFDataFormat format = workbook.CreateDataFormat() as HSSFDataFormat;
  51. dateStyle.DataFormat = format.GetFormat("yyyy-mm-dd");
  52. //取得列宽
  53. int[] arrColWidth = new int[dtSource.Columns.Count];
  54. foreach (DataColumn item in dtSource.Columns)
  55. {
  56. arrColWidth[item.Ordinal] = Encoding.GetEncoding(936).GetBytes(item.ColumnName.ToString()).Length;
  57. }
  58. for (int i = 0; i < dtSource.Rows.Count; i++)
  59. {
  60. for (int j = 0; j < dtSource.Columns.Count; j++)
  61. {
  62. int intTemp = Encoding.GetEncoding(936).GetBytes(dtSource.Rows[i][j].ToString()).Length;
  63. if (intTemp > arrColWidth[j])
  64. {
  65. arrColWidth[j] = intTemp;
  66. }
  67. }
  68. }
  69. int rowIndex = 0;
  70. foreach (DataRow row in dtSource.Rows)
  71. {
  72. #region 新建表,填充表头,填充列头,样式
  73. if (rowIndex == 65535 || rowIndex == 0)
  74. {
  75. if (rowIndex != 0)
  76. {
  77. sheet = workbook.CreateSheet() as HSSFSheet;
  78. }
  79. #region 表头及样式
  80. {
  81. HSSFRow headerRow = sheet.CreateRow(0) as HSSFRow;
  82. headerRow.HeightInPoints = 25;
  83. headerRow.CreateCell(0).SetCellValue(strHeaderText);
  84. HSSFCellStyle headStyle = workbook.CreateCellStyle() as HSSFCellStyle;
  85. headStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.CENTER;
  86. HSSFFont font = workbook.CreateFont() as HSSFFont;
  87. font.FontHeightInPoints = 20;
  88. font.Boldweight = 700;
  89. headStyle.SetFont(font);
  90. headerRow.GetCell(0).CellStyle = headStyle;
  91. sheet.AddMergedRegion(new Region(0, 0, 0, dtSource.Columns.Count - 1));
  92. //headerRow.Dispose();
  93. }
  94. #endregion
  95. #region 列头及样式
  96. {
  97. HSSFRow headerRow = sheet.CreateRow(1) as HSSFRow;
  98. HSSFCellStyle headStyle = workbook.CreateCellStyle() as HSSFCellStyle;
  99. headStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.CENTER;
  100. HSSFFont font = workbook.CreateFont() as HSSFFont;
  101. font.FontHeightInPoints = 10;
  102. font.Boldweight = 700;
  103. headStyle.SetFont(font);
  104. foreach (DataColumn column in dtSource.Columns)
  105. {
  106. headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);
  107. headerRow.GetCell(column.Ordinal).CellStyle = headStyle;
  108. //设置列宽
  109. sheet.SetColumnWidth(column.Ordinal, (arrColWidth[column.Ordinal] + 1) * 256);
  110. }
  111. //headerRow.Dispose();
  112. }
  113. #endregion
  114. rowIndex = 2;
  115. }
  116. #endregion
  117. #region 填充内容
  118. HSSFRow dataRow = sheet.CreateRow(rowIndex) as HSSFRow;
  119. foreach (DataColumn column in dtSource.Columns)
  120. {
  121. HSSFCell newCell = dataRow.CreateCell(column.Ordinal) as HSSFCell;
  122. string drValue = row[column].ToString();
  123. switch (column.DataType.ToString())
  124. {
  125. case "System.String": //字符串类型
  126. double result;
  127. if (isNumeric(drValue, out result))
  128. {
  129. double.TryParse(drValue, out result);
  130. newCell.SetCellValue(result);
  131. break;
  132. }
  133. else
  134. {
  135. newCell.SetCellValue(drValue);
  136. break;
  137. }
  138. case "System.DateTime": //日期类型
  139. DateTime dateV;
  140. DateTime.TryParse(drValue, out dateV);
  141. newCell.SetCellValue(dateV);
  142. newCell.CellStyle = dateStyle; //格式化显示
  143. break;
  144. case "System.Boolean": //布尔型
  145. bool boolV = false;
  146. bool.TryParse(drValue, out boolV);
  147. newCell.SetCellValue(boolV);
  148. break;
  149. case "System.Int16": //整型
  150. case "System.Int32":
  151. case "System.Int64":
  152. case "System.Byte":
  153. int intV = 0;
  154. int.TryParse(drValue, out intV);
  155. newCell.SetCellValue(intV);
  156. break;
  157. case "System.Decimal": //浮点型
  158. case "System.Double":
  159. double doubV = 0;
  160. double.TryParse(drValue, out doubV);
  161. newCell.SetCellValue(doubV);
  162. break;
  163. case "System.DBNull": //空值处理
  164. newCell.SetCellValue("");
  165. break;
  166. default:
  167. newCell.SetCellValue("");
  168. break;
  169. }
  170. }
  171. #endregion
  172. rowIndex++;
  173. }
  174. using (MemoryStream ms = new MemoryStream())
  175. {
  176. workbook.Write(ms);
  177. ms.Flush();
  178. ms.Position = 0;
  179. //sheet.Dispose();
  180. //workbook.Dispose();
  181. return ms;
  182. }
  183. }
  184. /// <summary>
  185. /// DataTable导出到Excel的MemoryStream
  186. /// </summary>
  187. /// <param name="dtSource">源DataTable</param>
  188. /// <param name="strHeaderText">表头文本</param>
  189. static void ExportDTI(DataTable dtSource, string strHeaderText, FileStream fs)
  190. {
  191. XSSFWorkbook workbook = new XSSFWorkbook();
  192. XSSFSheet sheet = workbook.CreateSheet() as XSSFSheet;
  193. #region 右击文件 属性信息
  194. //{
  195. // DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();
  196. // dsi.Company = "http://www.yongfa365.com/";
  197. // workbook.DocumentSummaryInformation = dsi;
  198. // SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
  199. // si.Author = "柳永法"; //填加xls文件作者信息
  200. // si.ApplicationName = "NPOI测试程序"; //填加xls文件创建程序信息
  201. // si.LastAuthor = "柳永法2"; //填加xls文件最后保存者信息
  202. // si.Comments = "说明信息"; //填加xls文件作者信息
  203. // si.Title = "NPOI测试"; //填加xls文件标题信息
  204. // si.Subject = "NPOI测试Demo"; //填加文件主题信息
  205. // si.CreateDateTime = DateTime.Now;
  206. // workbook.SummaryInformation = si;
  207. //}
  208. #endregion
  209. XSSFCellStyle dateStyle = workbook.CreateCellStyle() as XSSFCellStyle;
  210. XSSFDataFormat format = workbook.CreateDataFormat() as XSSFDataFormat;
  211. dateStyle.DataFormat = format.GetFormat("yyyy-mm-dd");
  212. //取得列宽
  213. int[] arrColWidth = new int[dtSource.Columns.Count];
  214. foreach (DataColumn item in dtSource.Columns)
  215. {
  216. arrColWidth[item.Ordinal] = Encoding.GetEncoding(936).GetBytes(item.ColumnName.ToString()).Length;
  217. }
  218. for (int i = 0; i < dtSource.Rows.Count; i++)
  219. {
  220. for (int j = 0; j < dtSource.Columns.Count; j++)
  221. {
  222. int intTemp = Encoding.GetEncoding(936).GetBytes(dtSource.Rows[i][j].ToString()).Length;
  223. if (intTemp > arrColWidth[j])
  224. {
  225. arrColWidth[j] = intTemp;
  226. }
  227. }
  228. }
  229. int rowIndex = 0;
  230. foreach (DataRow row in dtSource.Rows)
  231. {
  232. #region 新建表,填充表头,填充列头,样式
  233. if (rowIndex == 0)
  234. {
  235. #region 表头及样式
  236. //{
  237. // XSSFRow headerRow = sheet.CreateRow(0) as XSSFRow;
  238. // headerRow.HeightInPoints = 25;
  239. // headerRow.CreateCell(0).SetCellValue(strHeaderText);
  240. // XSSFCellStyle headStyle = workbook.CreateCellStyle() as XSSFCellStyle;
  241. // headStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.CENTER;
  242. // XSSFFont font = workbook.CreateFont() as XSSFFont;
  243. // font.FontHeightInPoints = 20;
  244. // font.Boldweight = 700;
  245. // headStyle.SetFont(font);
  246. // headerRow.GetCell(0).CellStyle = headStyle;
  247. // //sheet.AddMergedRegion(new Region(0, 0, 0, dtSource.Columns.Count - 1));
  248. // //headerRow.Dispose();
  249. //}
  250. #endregion
  251. #region 列头及样式
  252. {
  253. XSSFRow headerRow = sheet.CreateRow(0) as XSSFRow;
  254. XSSFCellStyle headStyle = workbook.CreateCellStyle() as XSSFCellStyle;
  255. headStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.CENTER;
  256. XSSFFont font = workbook.CreateFont() as XSSFFont;
  257. font.FontHeightInPoints = 10;
  258. font.Boldweight = 700;
  259. headStyle.SetFont(font);
  260. foreach (DataColumn column in dtSource.Columns)
  261. {
  262. headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);
  263. headerRow.GetCell(column.Ordinal).CellStyle = headStyle;
  264. //设置列宽
  265. sheet.SetColumnWidth(column.Ordinal, (arrColWidth[column.Ordinal] + 1) * 256);
  266. }
  267. //headerRow.Dispose();
  268. }
  269. #endregion
  270. rowIndex = 1;
  271. }
  272. #endregion
  273. #region 填充内容
  274. XSSFRow dataRow = sheet.CreateRow(rowIndex) as XSSFRow;
  275. foreach (DataColumn column in dtSource.Columns)
  276. {
  277. XSSFCell newCell = dataRow.CreateCell(column.Ordinal) as XSSFCell;
  278. string drValue = row[column].ToString();
  279. switch (column.DataType.ToString())
  280. {
  281. case "System.String": //字符串类型
  282. double result;
  283. if (isNumeric(drValue, out result))
  284. {
  285. double.TryParse(drValue, out result);
  286. newCell.SetCellValue(result);
  287. break;
  288. }
  289. else
  290. {
  291. newCell.SetCellValue(drValue);
  292. break;
  293. }
  294. case "System.DateTime": //日期类型
  295. DateTime dateV;
  296. DateTime.TryParse(drValue, out dateV);
  297. newCell.SetCellValue(dateV);
  298. newCell.CellStyle = dateStyle; //格式化显示
  299. break;
  300. case "System.Boolean": //布尔型
  301. bool boolV = false;
  302. bool.TryParse(drValue, out boolV);
  303. newCell.SetCellValue(boolV);
  304. break;
  305. case "System.Int16": //整型
  306. case "System.Int32":
  307. case "System.Int64":
  308. case "System.Byte":
  309. int intV = 0;
  310. int.TryParse(drValue, out intV);
  311. newCell.SetCellValue(intV);
  312. break;
  313. case "System.Decimal": //浮点型
  314. case "System.Double":
  315. double doubV = 0;
  316. double.TryParse(drValue, out doubV);
  317. newCell.SetCellValue(doubV);
  318. break;
  319. case "System.DBNull": //空值处理
  320. newCell.SetCellValue("");
  321. break;
  322. default:
  323. newCell.SetCellValue("");
  324. break;
  325. }
  326. }
  327. #endregion
  328. rowIndex++;
  329. }
  330. workbook.Write(fs);
  331. fs.Close();
  332. }
  333. /// <summary>
  334. /// DataTable导出到Excel文件
  335. /// </summary>
  336. /// <param name="dtSource">源DataTable</param>
  337. /// <param name="strHeaderText">表头文本</param>
  338. /// <param name="strFileName">保存位置</param>
  339. public static void ExportDTtoExcel(DataTable dtSource, string strHeaderText, string strFileName)
  340. {
  341. string[] temp = strFileName.Split('.');
  342. if (temp[temp.Length - 1] == "xls" && dtSource.Columns.Count < 256 && dtSource.Rows.Count < 65536)
  343. {
  344. using (MemoryStream ms = ExportDT(dtSource, strHeaderText))
  345. {
  346. using (FileStream fs = new FileStream(strFileName, FileMode.Create, FileAccess.Write))
  347. {
  348. byte[] data = ms.ToArray();
  349. fs.Write(data, 0, data.Length);
  350. fs.Flush();
  351. }
  352. }
  353. }
  354. else
  355. {
  356. if (temp[temp.Length - 1] == "xls")
  357. strFileName = strFileName + "x";
  358. using (FileStream fs = new FileStream(strFileName, FileMode.Create, FileAccess.Write))
  359. {
  360. ExportDTI(dtSource, strHeaderText, fs);
  361. }
  362. }
  363. }
  364. #endregion
  365. #region 从excel中将数据导出到datatable
  366. /// <summary>
  367. /// 读取excel 默认第一行为标头
  368. /// </summary>
  369. /// <param name="strFileName">excel文档路径</param>
  370. /// <returns></returns>
  371. public static DataTable ImportExceltoDt(string strFileName)
  372. {
  373. DataTable dt = new DataTable();
  374. IWorkbook wb;
  375. using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read))
  376. {
  377. wb = WorkbookFactory.Create(file);
  378. }
  379. ISheet sheet = wb.GetSheetAt(0);
  380. dt = ImportDt(sheet, 0, true);
  381. return dt;
  382. }
  383. /// <summary>
  384. /// 读取Excel流到DataTable
  385. /// </summary>
  386. /// <param name="stream">Excel流</param>
  387. /// <returns>第一个sheet中的数据</returns>
  388. public static DataTable ImportExceltoDt(Stream stream)
  389. {
  390. try
  391. {
  392. DataTable dt = new DataTable();
  393. IWorkbook wb;
  394. using (stream)
  395. {
  396. wb = WorkbookFactory.Create(stream);
  397. }
  398. ISheet sheet = wb.GetSheetAt(0);
  399. dt = ImportDt(sheet, 0, true);
  400. return dt;
  401. }
  402. catch (Exception)
  403. {
  404. throw;
  405. }
  406. }
  407. /// <summary>
  408. /// 读取Excel流到DataTable
  409. /// </summary>
  410. /// <param name="stream">Excel流</param>
  411. /// <param name="sheetName">表单名</param>
  412. /// <param name="HeaderRowIndex">列头所在行号,-1表示没有列头</param>
  413. /// <returns>指定sheet中的数据</returns>
  414. public static DataTable ImportExceltoDt(Stream stream, string sheetName, int HeaderRowIndex)
  415. {
  416. try
  417. {
  418. DataTable dt = new DataTable();
  419. IWorkbook wb;
  420. using (stream)
  421. {
  422. wb = WorkbookFactory.Create(stream);
  423. }
  424. ISheet sheet = wb.GetSheet(sheetName);
  425. dt = ImportDt(sheet, HeaderRowIndex, true);
  426. return dt;
  427. }
  428. catch (Exception)
  429. {
  430. throw;
  431. }
  432. }
  433. /// <summary>
  434. /// 读取Excel流到DataSet
  435. /// </summary>
  436. /// <param name="stream">Excel流</param>
  437. /// <returns>Excel中的数据</returns>
  438. public static DataSet ImportExceltoDs(Stream stream)
  439. {
  440. try
  441. {
  442. DataSet ds = new DataSet();
  443. IWorkbook wb;
  444. using (stream)
  445. {
  446. wb = WorkbookFactory.Create(stream);
  447. }
  448. for (int i = 0; i < wb.NumberOfSheets; i++)
  449. {
  450. DataTable dt = new DataTable();
  451. ISheet sheet = wb.GetSheetAt(i);
  452. dt = ImportDt(sheet, 0, true);
  453. ds.Tables.Add(dt);
  454. }
  455. return ds;
  456. }
  457. catch (Exception)
  458. {
  459. throw;
  460. }
  461. }
  462. /// <summary>
  463. /// 读取Excel流到DataSet
  464. /// </summary>
  465. /// <param name="stream">Excel流</param>
  466. /// <param name="dict">字典参数,key:sheet名,value:列头所在行号,-1表示没有列头</param>
  467. /// <returns>Excel中的数据</returns>
  468. public static DataSet ImportExceltoDs(Stream stream, Dictionary<string, int> dict)
  469. {
  470. try
  471. {
  472. DataSet ds = new DataSet();
  473. IWorkbook wb;
  474. using (stream)
  475. {
  476. wb = WorkbookFactory.Create(stream);
  477. }
  478. foreach (string key in dict.Keys)
  479. {
  480. DataTable dt = new DataTable();
  481. ISheet sheet = wb.GetSheet(key);
  482. dt = ImportDt(sheet, dict[key], true);
  483. ds.Tables.Add(dt);
  484. }
  485. return ds;
  486. }
  487. catch (Exception)
  488. {
  489. throw;
  490. }
  491. }
  492. /// <summary>
  493. /// 读取excel
  494. /// </summary>
  495. /// <param name="strFileName">excel文件路径</param>
  496. /// <param name="sheet">需要导出的sheet</param>
  497. /// <param name="HeaderRowIndex">列头所在行号,-1表示没有列头</param>
  498. /// <returns></returns>
  499. public static DataTable ImportExceltoDt(string strFileName, string SheetName, int HeaderRowIndex)
  500. {
  501. HSSFWorkbook workbook;
  502. IWorkbook wb;
  503. using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read))
  504. {
  505. wb = new HSSFWorkbook(file);
  506. }
  507. ISheet sheet = wb.GetSheet(SheetName);
  508. DataTable table = new DataTable();
  509. table = ImportDt(sheet, HeaderRowIndex, true);
  510. //ExcelFileStream.Close();
  511. workbook = null;
  512. sheet = null;
  513. return table;
  514. }
  515. /// <summary>
  516. /// 读取excel
  517. /// </summary>
  518. /// <param name="strFileName">excel文件路径</param>
  519. /// <param name="sheet">需要导出的sheet序号</param>
  520. /// <param name="HeaderRowIndex">列头所在行号,-1表示没有列头</param>
  521. /// <returns></returns>
  522. public static DataTable ImportExceltoDt(string strFileName, int SheetIndex, int HeaderRowIndex)
  523. {
  524. HSSFWorkbook workbook;
  525. IWorkbook wb;
  526. using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read))
  527. {
  528. wb = WorkbookFactory.Create(file);
  529. }
  530. ISheet isheet = wb.GetSheetAt(SheetIndex);
  531. DataTable table = new DataTable();
  532. table = ImportDt(isheet, HeaderRowIndex, true);
  533. //ExcelFileStream.Close();
  534. workbook = null;
  535. isheet = null;
  536. return table;
  537. }
  538. /// <summary>
  539. /// 读取excel
  540. /// </summary>
  541. /// <param name="strFileName">excel文件路径</param>
  542. /// <param name="sheet">需要导出的sheet</param>
  543. /// <param name="HeaderRowIndex">列头所在行号,-1表示没有列头</param>
  544. /// <returns></returns>
  545. public static DataTable ImportExceltoDt(string strFileName, string SheetName, int HeaderRowIndex, bool needHeader)
  546. {
  547. HSSFWorkbook workbook;
  548. IWorkbook wb;
  549. using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read))
  550. {
  551. wb = WorkbookFactory.Create(file);
  552. }
  553. ISheet sheet = wb.GetSheet(SheetName);
  554. DataTable table = new DataTable();
  555. table = ImportDt(sheet, HeaderRowIndex, needHeader);
  556. //ExcelFileStream.Close();
  557. workbook = null;
  558. sheet = null;
  559. return table;
  560. }
  561. /// <summary>
  562. /// 读取excel
  563. /// </summary>
  564. /// <param name="strFileName">excel文件路径</param>
  565. /// <param name="sheet">需要导出的sheet序号</param>
  566. /// <param name="HeaderRowIndex">列头所在行号,-1表示没有列头</param>
  567. /// <returns></returns>
  568. public static DataTable ImportExceltoDt(string strFileName, int SheetIndex, int HeaderRowIndex, bool needHeader)
  569. {
  570. HSSFWorkbook workbook;
  571. IWorkbook wb;
  572. using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read))
  573. {
  574. wb = WorkbookFactory.Create(file);
  575. }
  576. ISheet sheet = wb.GetSheetAt(SheetIndex);
  577. DataTable table = new DataTable();
  578. table = ImportDt(sheet, HeaderRowIndex, needHeader);
  579. //ExcelFileStream.Close();
  580. workbook = null;
  581. sheet = null;
  582. return table;
  583. }
  584. /// <summary>
  585. /// 将制定sheet中的数据导出到datatable中
  586. /// </summary>
  587. /// <param name="sheet">需要导出的sheet</param>
  588. /// <param name="HeaderRowIndex">列头所在行号,-1表示没有列头</param>
  589. /// <returns></returns>
  590. static DataTable ImportDt(ISheet sheet, int HeaderRowIndex, bool needHeader)
  591. {
  592. DataTable table = new DataTable();
  593. IRow headerRow;
  594. int cellCount;
  595. try
  596. {
  597. if (HeaderRowIndex < 0 || !needHeader)
  598. {
  599. headerRow = sheet.GetRow(0);
  600. cellCount = headerRow.LastCellNum;
  601. for (int i = headerRow.FirstCellNum; i <= cellCount; i++)
  602. {
  603. DataColumn column = new DataColumn(Convert.ToString(i));
  604. table.Columns.Add(column);
  605. }
  606. }
  607. else
  608. {
  609. headerRow = sheet.GetRow(HeaderRowIndex);
  610. cellCount = headerRow.LastCellNum;
  611. for (int i = headerRow.FirstCellNum; i <= cellCount; i++)
  612. {
  613. if (headerRow.GetCell(i) == null)
  614. {
  615. if (table.Columns.IndexOf(Convert.ToString(i)) > 0)
  616. {
  617. DataColumn column = new DataColumn(Convert.ToString("重复列名" + i));
  618. table.Columns.Add(column);
  619. }
  620. else
  621. {
  622. DataColumn column = new DataColumn(Convert.ToString(i));
  623. table.Columns.Add(column);
  624. }
  625. }
  626. else if (table.Columns.IndexOf(headerRow.GetCell(i).ToString()) > 0)
  627. {
  628. DataColumn column = new DataColumn(Convert.ToString("重复列名" + i));
  629. table.Columns.Add(column);
  630. }
  631. else
  632. {
  633. DataColumn column = new DataColumn(headerRow.GetCell(i).ToString());
  634. table.Columns.Add(column);
  635. }
  636. }
  637. }
  638. int rowCount = sheet.LastRowNum;
  639. for (int i = (HeaderRowIndex + 1); i <= sheet.LastRowNum; i++)
  640. {
  641. try
  642. {
  643. IRow row;
  644. if (sheet.GetRow(i) == null)
  645. {
  646. row = sheet.CreateRow(i);
  647. }
  648. else
  649. {
  650. row = sheet.GetRow(i);
  651. }
  652. DataRow dataRow = table.NewRow();
  653. for (int j = row.FirstCellNum; j <= cellCount; j++)
  654. {
  655. try
  656. {
  657. if (row.GetCell(j) != null)
  658. {
  659. switch (row.GetCell(j).CellType)
  660. {
  661. case CellType.STRING:
  662. string str = row.GetCell(j).StringCellValue;
  663. if (str != null && str.Length > 0)
  664. {
  665. dataRow[j] = str.ToString();
  666. }
  667. else
  668. {
  669. dataRow[j] = null;
  670. }
  671. break;
  672. case CellType.NUMERIC:
  673. if (DateUtil.IsCellDateFormatted(row.GetCell(j)))
  674. {
  675. dataRow[j] = DateTime.FromOADate(row.GetCell(j).NumericCellValue);
  676. }
  677. else
  678. {
  679. dataRow[j] = Convert.ToDouble(row.GetCell(j).NumericCellValue);
  680. }
  681. break;
  682. case CellType.BOOLEAN:
  683. dataRow[j] = Convert.ToString(row.GetCell(j).BooleanCellValue);
  684. break;
  685. case CellType.ERROR:
  686. dataRow[j] = ErrorEval.GetText(row.GetCell(j).ErrorCellValue);
  687. break;
  688. case CellType.FORMULA:
  689. switch (row.GetCell(j).CachedFormulaResultType)
  690. {
  691. case CellType.STRING:
  692. string strFORMULA = row.GetCell(j).StringCellValue;
  693. if (strFORMULA != null && strFORMULA.Length > 0)
  694. {
  695. dataRow[j] = strFORMULA.ToString();
  696. }
  697. else
  698. {
  699. dataRow[j] = null;
  700. }
  701. break;
  702. case CellType.NUMERIC:
  703. dataRow[j] = Convert.ToString(row.GetCell(j).NumericCellValue);
  704. break;
  705. case CellType.BOOLEAN:
  706. dataRow[j] = Convert.ToString(row.GetCell(j).BooleanCellValue);
  707. break;
  708. case CellType.ERROR:
  709. dataRow[j] = ErrorEval.GetText(row.GetCell(j).ErrorCellValue);
  710. break;
  711. default:
  712. dataRow[j] = "";
  713. break;
  714. }
  715. break;
  716. default:
  717. dataRow[j] = "";
  718. break;
  719. }
  720. }
  721. }
  722. catch (Exception exception)
  723. {
  724. wl.WriteLogs(exception.ToString());
  725. }
  726. }
  727. table.Rows.Add(dataRow);
  728. }
  729. catch (Exception exception)
  730. {
  731. wl.WriteLogs(exception.ToString());
  732. }
  733. }
  734. }
  735. catch (Exception exception)
  736. {
  737. wl.WriteLogs(exception.ToString());
  738. }
  739. return table;
  740. }
  741. #endregion
  742. public static void InsertSheet(string outputFile, string sheetname, DataTable dt)
  743. {
  744. FileStream readfile = new FileStream(outputFile, FileMode.Open, FileAccess.Read);
  745. IWorkbook hssfworkbook = WorkbookFactory.Create(readfile);
  746. //HSSFWorkbook hssfworkbook = new HSSFWorkbook(readfile);
  747. int num = hssfworkbook.GetSheetIndex(sheetname);
  748. ISheet sheet1;
  749. if (num >= 0)
  750. sheet1 = hssfworkbook.GetSheet(sheetname);
  751. else
  752. {
  753. sheet1 = hssfworkbook.CreateSheet(sheetname);
  754. }
  755. try
  756. {
  757. if (sheet1.GetRow(0) == null)
  758. {
  759. sheet1.CreateRow(0);
  760. }
  761. for (int coluid = 0; coluid < dt.Columns.Count; coluid++)
  762. {
  763. if (sheet1.GetRow(0).GetCell(coluid) == null)
  764. {
  765. sheet1.GetRow(0).CreateCell(coluid);
  766. }
  767. sheet1.GetRow(0).GetCell(coluid).SetCellValue(dt.Columns[coluid].ColumnName);
  768. }
  769. }
  770. catch (Exception ex)
  771. {
  772. wl.WriteLogs(ex.ToString());
  773. throw;
  774. }
  775. for (int i = 1; i <= dt.Rows.Count; i++)
  776. {
  777. try
  778. {
  779. if (sheet1.GetRow(i) == null)
  780. {
  781. sheet1.CreateRow(i);
  782. }
  783. for (int coluid = 0; coluid < dt.Columns.Count; coluid++)
  784. {
  785. if (sheet1.GetRow(i).GetCell(coluid) == null)
  786. {
  787. sheet1.GetRow(i).CreateCell(coluid);
  788. }
  789. sheet1.GetRow(i).GetCell(coluid).SetCellValue(dt.Rows[i - 1][coluid].ToString());
  790. }
  791. }
  792. catch (Exception ex)
  793. {
  794. wl.WriteLogs(ex.ToString());
  795. //throw;
  796. }
  797. }
  798. try
  799. {
  800. readfile.Close();
  801. FileStream writefile = new FileStream(outputFile, FileMode.OpenOrCreate, FileAccess.Write);
  802. hssfworkbook.Write(writefile);
  803. writefile.Close();
  804. }
  805. catch (Exception ex)
  806. {
  807. wl.WriteLogs(ex.ToString());
  808. }
  809. }
  810. #region 更新excel中的数据
  811. /// <summary>
  812. /// 更新Excel表格
  813. /// </summary>
  814. /// <param name="outputFile">需更新的excel表格路径</param>
  815. /// <param name="sheetname">sheet名</param>
  816. /// <param name="updateData">需更新的数据</param>
  817. /// <param name="coluid">需更新的列号</param>
  818. /// <param name="rowid">需更新的开始行号</param>
  819. public static void UpdateExcel(string outputFile, string sheetname, string[] updateData, int coluid, int rowid)
  820. {
  821. //FileStream readfile = new FileStream(outputFile, FileMode.Open, FileAccess.Read);
  822. IWorkbook hssfworkbook = null;// WorkbookFactory.Create(outputFile);
  823. //HSSFWorkbook hssfworkbook = new HSSFWorkbook(readfile);
  824. ISheet sheet1 = hssfworkbook.GetSheet(sheetname);
  825. for (int i = 0; i < updateData.Length; i++)
  826. {
  827. try
  828. {
  829. if (sheet1.GetRow(i + rowid) == null)
  830. {
  831. sheet1.CreateRow(i + rowid);
  832. }
  833. if (sheet1.GetRow(i + rowid).GetCell(coluid) == null)
  834. {
  835. sheet1.GetRow(i + rowid).CreateCell(coluid);
  836. }
  837. sheet1.GetRow(i + rowid).GetCell(coluid).SetCellValue(updateData[i]);
  838. }
  839. catch (Exception ex)
  840. {
  841. wl.WriteLogs(ex.ToString());
  842. throw;
  843. }
  844. }
  845. try
  846. {
  847. //readfile.Close();
  848. FileStream writefile = new FileStream(outputFile, FileMode.OpenOrCreate, FileAccess.Write);
  849. hssfworkbook.Write(writefile);
  850. writefile.Close();
  851. }
  852. catch (Exception ex)
  853. {
  854. wl.WriteLogs(ex.ToString());
  855. }
  856. }
  857. /// <summary>
  858. /// 更新Excel表格
  859. /// </summary>
  860. /// <param name="outputFile">需更新的excel表格路径</param>
  861. /// <param name="sheetname">sheet名</param>
  862. /// <param name="updateData">需更新的数据</param>
  863. /// <param name="coluids">需更新的列号</param>
  864. /// <param name="rowid">需更新的开始行号</param>
  865. public static void UpdateExcel(string outputFile, string sheetname, string[][] updateData, int[] coluids, int rowid)
  866. {
  867. FileStream readfile = new FileStream(outputFile, FileMode.Open, FileAccess.Read);
  868. HSSFWorkbook hssfworkbook = new HSSFWorkbook(readfile);
  869. readfile.Close();
  870. ISheet sheet1 = hssfworkbook.GetSheet(sheetname);
  871. for (int j = 0; j < coluids.Length; j++)
  872. {
  873. for (int i = 0; i < updateData[j].Length; i++)
  874. {
  875. try
  876. {
  877. if (sheet1.GetRow(i + rowid) == null)
  878. {
  879. sheet1.CreateRow(i + rowid);
  880. }
  881. if (sheet1.GetRow(i + rowid).GetCell(coluids[j]) == null)
  882. {
  883. sheet1.GetRow(i + rowid).CreateCell(coluids[j]);
  884. }
  885. sheet1.GetRow(i + rowid).GetCell(coluids[j]).SetCellValue(updateData[j][i]);
  886. }
  887. catch (Exception ex)
  888. {
  889. wl.WriteLogs(ex.ToString());
  890. }
  891. }
  892. }
  893. try
  894. {
  895. FileStream writefile = new FileStream(outputFile, FileMode.Create);
  896. hssfworkbook.Write(writefile);
  897. writefile.Close();
  898. }
  899. catch (Exception ex)
  900. {
  901. wl.WriteLogs(ex.ToString());
  902. }
  903. }
  904. /// <summary>
  905. /// 更新Excel表格
  906. /// </summary>
  907. /// <param name="outputFile">需更新的excel表格路径</param>
  908. /// <param name="sheetname">sheet名</param>
  909. /// <param name="updateData">需更新的数据</param>
  910. /// <param name="coluid">需更新的列号</param>
  911. /// <param name="rowid">需更新的开始行号</param>
  912. public static void UpdateExcel(string outputFile, string sheetname, double[] updateData, int coluid, int rowid)
  913. {
  914. FileStream readfile = new FileStream(outputFile, FileMode.Open, FileAccess.Read);
  915. HSSFWorkbook hssfworkbook = new HSSFWorkbook(readfile);
  916. ISheet sheet1 = hssfworkbook.GetSheet(sheetname);
  917. for (int i = 0; i < updateData.Length; i++)
  918. {
  919. try
  920. {
  921. if (sheet1.GetRow(i + rowid) == null)
  922. {
  923. sheet1.CreateRow(i + rowid);
  924. }
  925. if (sheet1.GetRow(i + rowid).GetCell(coluid) == null)
  926. {
  927. sheet1.GetRow(i + rowid).CreateCell(coluid);
  928. }
  929. sheet1.GetRow(i + rowid).GetCell(coluid).SetCellValue(updateData[i]);
  930. }
  931. catch (Exception ex)
  932. {
  933. wl.WriteLogs(ex.ToString());
  934. throw;
  935. }
  936. }
  937. try
  938. {
  939. readfile.Close();
  940. FileStream writefile = new FileStream(outputFile, FileMode.Create, FileAccess.Write);
  941. hssfworkbook.Write(writefile);
  942. writefile.Close();
  943. }
  944. catch (Exception ex)
  945. {
  946. wl.WriteLogs(ex.ToString());
  947. }
  948. }
  949. /// <summary>
  950. /// 更新Excel表格
  951. /// </summary>
  952. /// <param name="outputFile">需更新的excel表格路径</param>
  953. /// <param name="sheetname">sheet名</param>
  954. /// <param name="updateData">需更新的数据</param>
  955. /// <param name="coluids">需更新的列号</param>
  956. /// <param name="rowid">需更新的开始行号</param>
  957. public static void UpdateExcel(string outputFile, string sheetname, double[][] updateData, int[] coluids, int rowid)
  958. {
  959. FileStream readfile = new FileStream(outputFile, FileMode.Open, FileAccess.Read);
  960. HSSFWorkbook hssfworkbook = new HSSFWorkbook(readfile);
  961. readfile.Close();
  962. ISheet sheet1 = hssfworkbook.GetSheet(sheetname);
  963. for (int j = 0; j < coluids.Length; j++)
  964. {
  965. for (int i = 0; i < updateData[j].Length; i++)
  966. {
  967. try
  968. {
  969. if (sheet1.GetRow(i + rowid) == null)
  970. {
  971. sheet1.CreateRow(i + rowid);
  972. }
  973. if (sheet1.GetRow(i + rowid).GetCell(coluids[j]) == null)
  974. {
  975. sheet1.GetRow(i + rowid).CreateCell(coluids[j]);
  976. }
  977. sheet1.GetRow(i + rowid).GetCell(coluids[j]).SetCellValue(updateData[j][i]);
  978. }
  979. catch (Exception ex)
  980. {
  981. wl.WriteLogs(ex.ToString());
  982. }
  983. }
  984. }
  985. try
  986. {
  987. FileStream writefile = new FileStream(outputFile, FileMode.Create);
  988. hssfworkbook.Write(writefile);
  989. writefile.Close();
  990. }
  991. catch (Exception ex)
  992. {
  993. wl.WriteLogs(ex.ToString());
  994. }
  995. }
  996. #endregion
  997. public static int GetSheetNumber(string outputFile)
  998. {
  999. int number = 0;
  1000. try
  1001. {
  1002. FileStream readfile = new FileStream(outputFile, FileMode.Open, FileAccess.Read);
  1003. HSSFWorkbook hssfworkbook = new HSSFWorkbook(readfile);
  1004. number = hssfworkbook.NumberOfSheets;
  1005. }
  1006. catch (Exception exception)
  1007. {
  1008. wl.WriteLogs(exception.ToString());
  1009. }
  1010. return number;
  1011. }
  1012. public static ArrayList GetSheetName(string outputFile)
  1013. {
  1014. ArrayList arrayList = new ArrayList();
  1015. try
  1016. {
  1017. FileStream readfile = new FileStream(outputFile, FileMode.Open, FileAccess.Read);
  1018. HSSFWorkbook hssfworkbook = new HSSFWorkbook(readfile);
  1019. for (int i = 0; i < hssfworkbook.NumberOfSheets; i++)
  1020. {
  1021. arrayList.Add(hssfworkbook.GetSheetName(i));
  1022. }
  1023. }
  1024. catch (Exception exception)
  1025. {
  1026. wl.WriteLogs(exception.ToString());
  1027. }
  1028. return arrayList;
  1029. }
  1030. public static bool isNumeric(String message, out double result)
  1031. {
  1032. Regex rex = new Regex(@"^[-]?\d+[.]?\d*$");
  1033. result = -1;
  1034. if (rex.IsMatch(message))
  1035. {
  1036. result = double.Parse(message);
  1037. return true;
  1038. }
  1039. else
  1040. return false;
  1041. }
  1042. ////////// 现用导出 \\\\\\\\\\
  1043. /// <summary>
  1044. /// 用于Web导出 第一步
  1045. /// </summary>
  1046. /// <param name="dtSource">源DataTable</param>
  1047. /// <param name="strHeaderText">表头文本</param>
  1048. /// <param name="strFileName">文件名</param>
  1049. public static void ExportByWeb(DataTable dtSource, string strHeaderText, string strFileName)
  1050. {
  1051. HttpContext curContext = HttpContext.Current;
  1052. // 设置编码和附件格式
  1053. curContext.Response.ContentType = "application/vnd.ms-excel";
  1054. curContext.Response.ContentEncoding = Encoding.UTF8;
  1055. curContext.Response.Charset = "";
  1056. curContext.Response.AppendHeader("Content-Disposition",
  1057. "attachment;filename=" + HttpUtility.UrlEncode(strFileName, Encoding.UTF8));
  1058. curContext.Response.BinaryWrite(Export(dtSource, strHeaderText).GetBuffer());
  1059. curContext.Response.End();
  1060. }
  1061. /// <summary>
  1062. /// DataTable导出到Excel的MemoryStream 第二步
  1063. /// </summary>
  1064. /// <param name="dtSource">源DataTable</param>
  1065. /// <param name="strHeaderText">表头文本</param>
  1066. public static MemoryStream Export(DataTable dtSource, string strHeaderText)
  1067. {
  1068. HSSFWorkbook workbook = new HSSFWorkbook();
  1069. HSSFSheet sheet = workbook.CreateSheet() as HSSFSheet;
  1070. #region 右击文件 属性信息
  1071. {
  1072. DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();
  1073. dsi.Company = "NPOI";
  1074. workbook.DocumentSummaryInformation = dsi;
  1075. SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
  1076. si.Author = "文件作者信息"; //填加xls文件作者信息
  1077. si.ApplicationName = "创建程序信息"; //填加xls文件创建程序信息
  1078. si.LastAuthor = "最后保存者信息"; //填加xls文件最后保存者信息
  1079. si.Comments = "作者信息"; //填加xls文件作者信息
  1080. si.Title = "标题信息"; //填加xls文件标题信息
  1081. si.Subject = "主题信息";//填加文件主题信息
  1082. si.CreateDateTime = DateTime.Now;
  1083. workbook.SummaryInformation = si;
  1084. }
  1085. #endregion
  1086. HSSFCellStyle dateStyle = workbook.CreateCellStyle() as HSSFCellStyle;
  1087. HSSFDataFormat format = workbook.CreateDataFormat() as HSSFDataFormat;
  1088. dateStyle.DataFormat = format.GetFormat("yyyy-mm-dd");
  1089. //取得列宽
  1090. int[] arrColWidth = new int[dtSource.Columns.Count];
  1091. foreach (DataColumn item in dtSource.Columns)
  1092. {
  1093. arrColWidth[item.Ordinal] = Encoding.GetEncoding(936).GetBytes(item.ColumnName.ToString()).Length;
  1094. }
  1095. for (int i = 0; i < dtSource.Rows.Count; i++)
  1096. {
  1097. for (int j = 0; j < dtSource.Columns.Count; j++)
  1098. {
  1099. int intTemp = Encoding.GetEncoding(936).GetBytes(dtSource.Rows[i][j].ToString()).Length;
  1100. if (intTemp > arrColWidth[j])
  1101. {
  1102. arrColWidth[j] = intTemp;
  1103. }
  1104. }
  1105. }
  1106. int rowIndex = 0;
  1107. foreach (DataRow row in dtSource.Rows)
  1108. {
  1109. #region 新建表,填充表头,填充列头,样式
  1110. if (rowIndex == 65535 || rowIndex == 0)
  1111. {
  1112. if (rowIndex != 0)
  1113. {
  1114. sheet = workbook.CreateSheet() as HSSFSheet;
  1115. }
  1116. #region 表头及样式
  1117. {
  1118. if (string.IsNullOrEmpty(strHeaderText))
  1119. {
  1120. HSSFRow headerRow = sheet.CreateRow(0) as HSSFRow;
  1121. headerRow.HeightInPoints = 25;
  1122. headerRow.CreateCell(0).SetCellValue(strHeaderText);
  1123. HSSFCellStyle headStyle = workbook.CreateCellStyle() as HSSFCellStyle;
  1124. //headStyle.Alignment = CellHorizontalAlignment.CENTER;
  1125. HSSFFont font = workbook.CreateFont() as HSSFFont;
  1126. font.FontHeightInPoints = 20;
  1127. font.Boldweight = 700;
  1128. headStyle.SetFont(font);
  1129. headerRow.GetCell(0).CellStyle = headStyle;
  1130. sheet.AddMergedRegion(new Region(0, 0, 0, dtSource.Columns.Count - 1));
  1131. //headerRow.Dispose();
  1132. }
  1133. }
  1134. #endregion
  1135. #region 列头及样式
  1136. {
  1137. HSSFRow headerRow = sheet.CreateRow(0) as HSSFRow;
  1138. HSSFCellStyle headStyle = workbook.CreateCellStyle() as HSSFCellStyle;
  1139. //headStyle.Alignment = CellHorizontalAlignment.CENTER;
  1140. HSSFFont font = workbook.CreateFont() as HSSFFont;
  1141. font.FontHeightInPoints = 10;
  1142. font.Boldweight = 700;
  1143. headStyle.SetFont(font);
  1144. foreach (DataColumn column in dtSource.Columns)
  1145. {
  1146. headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);
  1147. headerRow.GetCell(column.Ordinal).CellStyle = headStyle;
  1148. //设置列宽
  1149. sheet.SetColumnWidth(column.Ordinal, (arrColWidth[column.Ordinal] + 1) * 256);
  1150. }
  1151. //headerRow.Dispose();
  1152. }
  1153. #endregion
  1154. rowIndex = 1;
  1155. }
  1156. #endregion
  1157. #region 填充内容
  1158. HSSFRow dataRow = sheet.CreateRow(rowIndex) as HSSFRow;
  1159. foreach (DataColumn column in dtSource.Columns)
  1160. {
  1161. HSSFCell newCell = dataRow.CreateCell(column.Ordinal) as HSSFCell;
  1162. string drValue = row[column].ToString();
  1163. switch (column.DataType.ToString())
  1164. {
  1165. case "System.String"://字符串类型
  1166. newCell.SetCellValue(drValue);
  1167. break;
  1168. case "System.DateTime"://日期类型
  1169. DateTime dateV;
  1170. DateTime.TryParse(drValue, out dateV);
  1171. newCell.SetCellValue(dateV);
  1172. newCell.CellStyle = dateStyle;//格式化显示
  1173. break;
  1174. case "System.Boolean"://布尔型
  1175. bool boolV = false;
  1176. bool.TryParse(drValue, out boolV);
  1177. newCell.SetCellValue(boolV);
  1178. break;
  1179. case "System.Int16"://整型
  1180. case "System.Int32":
  1181. case "System.Int64":
  1182. case "System.Byte":
  1183. int intV = 0;
  1184. int.TryParse(drValue, out intV);
  1185. newCell.SetCellValue(intV);
  1186. break;
  1187. case "System.Decimal"://浮点型
  1188. case "System.Double":
  1189. double doubV = 0;
  1190. double.TryParse(drValue, out doubV);
  1191. newCell.SetCellValue(doubV);
  1192. break;
  1193. case "System.DBNull"://空值处理
  1194. newCell.SetCellValue("");
  1195. break;
  1196. default:
  1197. newCell.SetCellValue("");
  1198. break;
  1199. }
  1200. }
  1201. #endregion
  1202. rowIndex++;
  1203. }
  1204. using (MemoryStream ms = new MemoryStream())
  1205. {
  1206. workbook.Write(ms);
  1207. ms.Flush();
  1208. ms.Position = 0;
  1209. //sheet.Dispose();
  1210. //workbook.Dispose();//一般只用写这一个就OK了,他会遍历并释放所有资源,但当前版本有问题所以只释放sheet
  1211. return ms;
  1212. }
  1213. }
  1214. /// <summary>
  1215. /// /注:分浏览器进行编码(IE必须编码,FireFox不能编码,Chrome可编码也可不编码)
  1216. /// </summary>
  1217. /// <param name="ds"></param>
  1218. /// <param name="strHeaderText"></param>
  1219. /// <param name="strFileName"></param>
  1220. public static void ExportByWeb(DataSet ds, string strHeaderText, string strFileName)
  1221. {
  1222. HttpContext curContext = HttpContext.Current;
  1223. curContext.Response.ContentType = "application/vnd.ms-excel";
  1224. curContext.Response.Charset = "";
  1225. if (curContext.Request.UserAgent.ToLower().IndexOf("firefox", System.StringComparison.Ordinal) > 0)
  1226. {
  1227. curContext.Response.AppendHeader("Content-Disposition", "attachment;filename=" + strFileName);
  1228. }
  1229. else
  1230. {
  1231. curContext.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(strFileName, System.Text.Encoding.UTF8));
  1232. }
  1233. // curContext.Response.AppendHeader("Content-Disposition", "attachment;filename=" +strFileName);
  1234. curContext.Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
  1235. curContext.Response.BinaryWrite(ExportDataSetToExcel(ds, strHeaderText).GetBuffer());
  1236. curContext.Response.End();
  1237. }
  1238. /// <summary>
  1239. /// 由DataSet导出Excel
  1240. /// </summary>
  1241. /// <param name="sourceTable">要导出数据的DataTable</param>
  1242. /// <param name="sheetName">工作表名称</param>
  1243. /// <returns>Excel工作表</returns>
  1244. private static MemoryStream ExportDataSetToExcel(DataSet sourceDs, string sheetName)
  1245. {
  1246. HSSFWorkbook workbook = new HSSFWorkbook();
  1247. MemoryStream ms = new MemoryStream();
  1248. string[] sheetNames = sheetName.Split(',');
  1249. for (int i = 0; i < sheetNames.Length; i++)
  1250. {
  1251. ISheet sheet = workbook.CreateSheet(sheetNames[i]);
  1252. #region 列头
  1253. IRow headerRow = sheet.CreateRow(0);
  1254. HSSFCellStyle headStyle = workbook.CreateCellStyle() as HSSFCellStyle;
  1255. HSSFFont font = workbook.CreateFont() as HSSFFont;
  1256. font.FontHeightInPoints = 10;
  1257. font.Boldweight = 700;
  1258. headStyle.SetFont(font);
  1259. //取得列宽
  1260. int[] arrColWidth = new int[sourceDs.Tables[i].Columns.Count];
  1261. foreach (DataColumn item in sourceDs.Tables[i].Columns)
  1262. {
  1263. arrColWidth[item.Ordinal] = Encoding.GetEncoding(936).GetBytes(item.ColumnName.ToString()).Length;
  1264. }
  1265. // 处理列头
  1266. foreach (DataColumn column in sourceDs.Tables[i].Columns)
  1267. {
  1268. headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);
  1269. headerRow.GetCell(column.Ordinal).CellStyle = headStyle;
  1270. //设置列宽
  1271. sheet.SetColumnWidth(column.Ordinal, (arrColWidth[column.Ordinal] + 1) * 256);
  1272. }
  1273. #endregion
  1274. #region 填充值
  1275. int rowIndex = 1;
  1276. foreach (DataRow row in sourceDs.Tables[i].Rows)
  1277. {
  1278. IRow dataRow = sheet.CreateRow(rowIndex);
  1279. foreach (DataColumn column in sourceDs.Tables[i].Columns)
  1280. {
  1281. dataRow.CreateCell(column.Ordinal).SetCellValue(row[column].ToString());
  1282. }
  1283. rowIndex++;
  1284. }
  1285. #endregion
  1286. }
  1287. workbook.Write(ms);
  1288. ms.Flush();
  1289. ms.Position = 0;
  1290. workbook = null;
  1291. return ms;
  1292. }
  1293. /// <summary>
  1294. /// 验证导入的Excel是否有数据
  1295. /// </summary>
  1296. /// <param name="excelFileStream"></param>
  1297. /// <returns></returns>
  1298. public static bool HasData(Stream excelFileStream)
  1299. {
  1300. using (excelFileStream)
  1301. {
  1302. IWorkbook workBook = new HSSFWorkbook(excelFileStream);
  1303. if (workBook.NumberOfSheets > 0)
  1304. {
  1305. ISheet sheet = workBook.GetSheetAt(0);
  1306. return sheet.PhysicalNumberOfRows > 0;
  1307. }
  1308. }
  1309. return false;
  1310. }
  1311. }