请选择 进入手机版 | 继续访问电脑版

马上加入IBC程序猿 各种源码随意下,各种教程随便看! 注册 每日签到 加入编程讨论群

C#教程 ASP.NET教程 C#视频教程程序源码享受不尽 C#技术求助 ASP.NET技术求助

【源码下载】 社群合作 申请版主 程序开发 【远程协助】 每天乐一乐 每日签到 【承接外包项目】 面试-葵花宝典下载

官方一群:

官方二群:

ASP.NET操作Excel

[复制链接]
查看1729 | 回复3 | 2019-12-26 09:06:35 | 显示全部楼层 |阅读模式

使用NPOI使用Excel,无需Office COM组件

部门代码来自于:https://docs.microsoft.com/zh-tw/previous-versions/ee818993(v=msdn.10)?redirectedfrom=MSDN

  1. using System.Data;
  2. using System.IO;
  3. using System.Text;
  4. using System.Web;
  5. using NPOI.HSSF.UserModel;
  6. using NPOI.SS.UserModel;
  7. /// <summary>
  8. /// 使用NPOI使用Excel,无需Office COM组件
  9. /// 部门代码取自http://msdn.microsoft.com/zh-tw/ee818993.asp
  10. /// </summary>
  11. public class ExcelRender
  12. {
  13. /// <summary>
  14. /// 根据Excel列范例获取列的值
  15. /// </summary>
  16. /// <param name="cell">Excel列</param>
  17. /// <returns></returns>
  18. private static string GetCellValue(ICell cell)
  19. {
  20. if (cell == null)
  21. return string.Empty;
  22. switch (cell.CellType)
  23. {
  24. case CellType.BLANK:
  25. return string.Empty;
  26. case CellType.BOOLEAN:
  27. return cell.BooleanCellValue.ToString();
  28. case CellType.ERROR:
  29. return cell.ErrorCellValue.ToString();
  30. case CellType.NUMERIC:
  31. case CellType.Unknown:
  32. default:
  33. return cell.ToString();//This is a trick to get the correct value of the cell. NumericCellValue will return a numeric value no matter the cell value is a date or a number
  34. case CellType.STRING:
  35. return cell.StringCellValue;
  36. case CellType.FORMULA:
  37. try
  38. {
  39. HSSFFormulaEvaluator e = new HSSFFormulaEvaluator(cell.Sheet.Workbook);
  40. e.EvaluateInCell(cell);
  41. return cell.ToString();
  42. }
  43. catch
  44. {
  45. return cell.NumericCellValue.ToString();
  46. }
  47. }
  48. }
  49. /// <summary>
  50. /// 主动设置Excel列宽
  51. /// </summary>
  52. /// <param name="sheet">Excel表</param>
  53. private static void AutoSizeColumns(ISheet sheet)
  54. {
  55. if (sheet.PhysicalNumberOfRows > 0)
  56. {
  57. IRow headerRow = sheet.GetRow(0);
  58. for (int i = 0, l = headerRow.LastCellNum; i < l; i++)
  59. {
  60. sheet.AutoSizeColumn(i);
  61. }
  62. }
  63. }
  64. /// <summary>
  65. /// 生存Excel文档流到文件
  66. /// </summary>
  67. /// <param name="ms">Excel文档流</param>
  68. /// <param name="fileName">文件名</param>
  69. private static void SaveToFile(MemoryStream ms, string fileName)
  70. {
  71. using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write))
  72. {
  73. byte[] data = ms.ToArray();
  74. fs.Write(data, 0, data.Length);
  75. fs.Flush();
  76. data = null;
  77. }
  78. }
  79. /// <summary>
  80. /// 输出文件到欣赏器
  81. /// </summary>
  82. /// <param name="ms">Excel文档流</param>
  83. /// <param name="context">HTTP上下文</param>
  84. /// <param name="fileName">文件名</param>
  85. private static void RenderToBrowser(MemoryStream ms, HttpContext context, string fileName)
  86. {
  87. if (context.Request.Browser.Browser == "IE")
  88. fileName = HttpUtility.UrlEncode(fileName);
  89. context.Response.AddHeader("Content-Disposition", "attachment;fileName=" + fileName);
  90. context.Response.BinaryWrite(ms.ToArray());
  91. }
  92. /// <summary>
  93. /// DataReader转换成Excel文档流
  94. /// </summary>
  95. /// <param name="reader"></param>
  96. /// <returns></returns>
  97. public static MemoryStream RenderToExcel(IDataReader reader)
  98. {
  99. MemoryStream ms = new MemoryStream();
  100. using (reader)
  101. {
  102. using (IWorkbook workbook = new HSSFWorkbook())
  103. {
  104. using (ISheet sheet = workbook.CreateSheet())
  105. {
  106. IRow headerRow = sheet.CreateRow(0);
  107. int cellCount = reader.FieldCount;
  108. // handling header.
  109. for (int i = 0; i < cellCount; i++)
  110. {
  111. headerRow.CreateCell(i).SetCellValue(reader.GetName(i));
  112. }
  113. // handling value.
  114. int rowIndex = 1;
  115. while (reader.Read())
  116. {
  117. IRow dataRow = sheet.CreateRow(rowIndex);
  118. for (int i = 0; i < cellCount; i++)
  119. {
  120. dataRow.CreateCell(i).SetCellValue(reader[i].ToString());
  121. }
  122. rowIndex++;
  123. }
  124. AutoSizeColumns(sheet);
  125. workbook.Write(ms);
  126. ms.Flush();
  127. ms.Position = 0;
  128. }
  129. }
  130. }
  131. return ms;
  132. }
  133. /// <summary>
  134. /// DataReader转换成Excel文档流,并生存到文件
  135. /// </summary>
  136. /// <param name="reader"></param>
  137. /// <param name="fileName">生存的路径</param>
  138. public static void RenderToExcel(IDataReader reader, string fileName)
  139. {
  140. using (MemoryStream ms = RenderToExcel(reader))
  141. {
  142. SaveToFile(ms, fileName);
  143. }
  144. }
  145. /// <summary>
  146. /// DataReader转换成Excel文档流,并输出到客户端
  147. /// </summary>
  148. /// <param name="reader"></param>
  149. /// <param name="context">HTTP上下文</param>
  150. /// <param name="fileName">输出的文件名</param>
  151. public static void RenderToExcel(IDataReader reader, HttpContext context, string fileName)
  152. {
  153. using (MemoryStream ms = RenderToExcel(reader))
  154. {
  155. RenderToBrowser(ms, context, fileName);
  156. }
  157. }
  158. /// <summary>
  159. /// DataTable转换成Excel文档流
  160. /// </summary>
  161. /// <param name="table"></param>
  162. /// <returns></returns>
  163. public static MemoryStream RenderToExcel(DataTable table)
  164. {
  165. MemoryStream ms = new MemoryStream();
  166. using (table)
  167. {
  168. using (IWorkbook workbook = new HSSFWorkbook())
  169. {
  170. using (ISheet sheet = workbook.CreateSheet())
  171. {
  172. IRow headerRow = sheet.CreateRow(0);
  173. // handling header.
  174. foreach (DataColumn column in table.Columns)
  175. headerRow.CreateCell(column.Ordinal).SetCellValue(column.Caption);//If Caption not set, returns the ColumnName value
  176. // handling value.
  177. int rowIndex = 1;
  178. foreach (DataRow row in table.Rows)
  179. {
  180. IRow dataRow = sheet.CreateRow(rowIndex);
  181. foreach (DataColumn column in table.Columns)
  182. {
  183. dataRow.CreateCell(column.Ordinal).SetCellValue(row[column].ToString());
  184. }
  185. rowIndex++;
  186. }
  187. AutoSizeColumns(sheet);
  188. workbook.Write(ms);
  189. ms.Flush();
  190. ms.Position = 0;
  191. }
  192. }
  193. }
  194. return ms;
  195. }
  196. /// <summary>
  197. /// DataTable转换成Excel文档流,并生存到文件
  198. /// </summary>
  199. /// <param name="table"></param>
  200. /// <param name="fileName">生存的路径</param>
  201. public static void RenderToExcel(DataTable table, string fileName)
  202. {
  203. using (MemoryStream ms = RenderToExcel(table))
  204. {
  205. SaveToFile(ms, fileName);
  206. }
  207. }
  208. /// <summary>
  209. /// DataTable转换成Excel文档流,并输出到客户端
  210. /// </summary>
  211. /// <param name="table"></param>
  212. /// <param name="response"></param>
  213. /// <param name="fileName">输出的文件名</param>
  214. public static void RenderToExcel(DataTable table, HttpContext context, string fileName)
  215. {
  216. using (MemoryStream ms = RenderToExcel(table))
  217. {
  218. RenderToBrowser(ms, context, fileName);
  219. }
  220. }
  221. /// <summary>
  222. /// Excel文档流是否有数据
  223. /// </summary>
  224. /// <param name="excelFileStream">Excel文档流</param>
  225. /// <returns></returns>
  226. public static bool HasData(Stream excelFileStream)
  227. {
  228. return HasData(excelFileStream, 0);
  229. }
  230. /// <summary>
  231. /// Excel文档流是否有数据
  232. /// </summary>
  233. /// <param name="excelFileStream">Excel文档流</param>
  234. /// <param name="sheetIndex">表索引号,如第一个表为0</param>
  235. /// <returns></returns>
  236. public static bool HasData(Stream excelFileStream, int sheetIndex)
  237. {
  238. using (excelFileStream)
  239. {
  240. using (IWorkbook workbook = new HSSFWorkbook(excelFileStream))
  241. {
  242. if (workbook.NumberOfSheets > 0)
  243. {
  244. if (sheetIndex < workbook.NumberOfSheets)
  245. {
  246. using (ISheet sheet = workbook.GetSheetAt(sheetIndex))
  247. {
  248. return sheet.PhysicalNumberOfRows > 0;
  249. }
  250. }
  251. }
  252. }
  253. }
  254. return false;
  255. }
  256. /// <summary>
  257. /// Excel文档流转换成DataTable
  258. /// 第一行必须为标题行
  259. /// </summary>
  260. /// <param name="excelFileStream">Excel文档流</param>
  261. /// <param name="sheetName">表名称</param>
  262. /// <returns></returns>
  263. public static DataTable RenderFromExcel(Stream excelFileStream, string sheetName)
  264. {
  265. return RenderFromExcel(excelFileStream, sheetName, 0);
  266. }
  267. /// <summary>
  268. /// Excel文档流转换成DataTable
  269. /// </summary>
  270. /// <param name="excelFileStream">Excel文档流</param>
  271. /// <param name="sheetName">表名称</param>
  272. /// <param name="headerRowIndex">标题行索引号,如第一运动0</param>
  273. /// <returns></returns>
  274. public static DataTable RenderFromExcel(Stream excelFileStream, string sheetName, int headerRowIndex)
  275. {
  276. DataTable table = null;
  277. using (excelFileStream)
  278. {
  279. using (IWorkbook workbook = new HSSFWorkbook(excelFileStream))
  280. {
  281. using (ISheet sheet = workbook.GetSheet(sheetName))
  282. {
  283. table = RenderFromExcel(sheet, headerRowIndex);
  284. }
  285. }
  286. }
  287. return table;
  288. }
  289. /// <summary>
  290. /// Excel文档流转换成DataTable
  291. /// 默认转换Excel的第一个表
  292. /// 第一行必须为标题行
  293. /// </summary>
  294. /// <param name="excelFileStream">Excel文档流</param>
  295. /// <returns></returns>
  296. public static DataTable RenderFromExcel(Stream excelFileStream)
  297. {
  298. return RenderFromExcel(excelFileStream, 0, 0);
  299. }
  300. /// <summary>
  301. /// Excel文档流转换成DataTable
  302. /// 第一行必须为标题行
  303. /// </summary>
  304. /// <param name="excelFileStream">Excel文档流</param>
  305. /// <param name="sheetIndex">表索引号,如第一个表为0</param>
  306. /// <returns></returns>
  307. public static DataTable RenderFromExcel(Stream excelFileStream, int sheetIndex)
  308. {
  309. return RenderFromExcel(excelFileStream, sheetIndex, 0);
  310. }
  311. /// <summary>
  312. /// Excel文档流转换成DataTable
  313. /// </summary>
  314. /// <param name="excelFileStream">Excel文档流</param>
  315. /// <param name="sheetIndex">表索引号,如第一个表为0</param>
  316. /// <param name="headerRowIndex">标题行索引号,如第一运动0</param>
  317. /// <returns></returns>
  318. public static DataTable RenderFromExcel(Stream excelFileStream, int sheetIndex, int headerRowIndex)
  319. {
  320. DataTable table = null;
  321. using (excelFileStream)
  322. {
  323. using (IWorkbook workbook = new HSSFWorkbook(excelFileStream))
  324. {
  325. using (ISheet sheet = workbook.GetSheetAt(sheetIndex))
  326. {
  327. table = RenderFromExcel(sheet, headerRowIndex);
  328. }
  329. }
  330. }
  331. return table;
  332. }
  333. /// <summary>
  334. /// Excel表格转换成DataTable
  335. /// </summary>
  336. /// <param name="sheet">表格</param>
  337. /// <param name="headerRowIndex">标题行索引号,如第一运动0</param>
  338. /// <returns></returns>
  339. private static DataTable RenderFromExcel(ISheet sheet, int headerRowIndex)
  340. {
  341. DataTable table = new DataTable();
  342. IRow headerRow = sheet.GetRow(headerRowIndex);
  343. int cellCount = headerRow.LastCellNum;//LastCellNum = PhysicalNumberOfCells
  344. int rowCount = sheet.LastRowNum;//LastRowNum = PhysicalNumberOfRows - 1
  345. //handling header.
  346. for (int i = headerRow.FirstCellNum; i < cellCount; i++)
  347. {
  348. DataColumn column = new DataColumn(headerRow.GetCell(i).StringCellValue);
  349. table.Columns.Add(column);
  350. }
  351. for (int i = (sheet.FirstRowNum + 1); i <= rowCount; i++)
  352. {
  353. IRow row = sheet.GetRow(i);
  354. DataRow dataRow = table.NewRow();
  355. if (row != null)
  356. {
  357. for (int j = row.FirstCellNum; j < cellCount; j++)
  358. {
  359. if (row.GetCell(j) != null)
  360. dataRow[j] = GetCellValue(row.GetCell(j));
  361. }
  362. }
  363. table.Rows.Add(dataRow);
  364. }
  365. return table;
  366. }
  367. /// <summary>
  368. /// Excel文档导入到数据库
  369. /// 默认取Excel的第一个表
  370. /// 第一行必须为标题行
  371. /// </summary>
  372. /// <param name="excelFileStream">Excel文档流</param>
  373. /// <param name="insertSql">插入语句</param>
  374. /// <param name="dbAction">更新到数据库的方法</param>
  375. /// <returns></returns>
  376. public static int RenderToDb(Stream excelFileStream, string insertSql, DBAction dbAction)
  377. {
  378. return RenderToDb(excelFileStream, insertSql, dbAction, 0, 0);
  379. }
  380. public delegate int DBAction(string sql, params IDataParameter[] parameters);
  381. /// <summary>
  382. /// Excel文档导入到数据库
  383. /// </summary>
  384. /// <param name="excelFileStream">Excel文档流</param>
  385. /// <param name="insertSql">插入语句</param>
  386. /// <param name="dbAction">更新到数据库的方法</param>
  387. /// <param name="sheetIndex">表索引号,如第一个表为0</param>
  388. /// <param name="headerRowIndex">标题行索引号,如第一运动0</param>
  389. /// <returns></returns>
  390. public static int RenderToDb(Stream excelFileStream, string insertSql, DBAction dbAction, int sheetIndex, int headerRowIndex)
  391. {
  392. int rowAffected = 0;
  393. using (excelFileStream)
  394. {
  395. using (IWorkbook workbook = new HSSFWorkbook(excelFileStream))
  396. {
  397. using (ISheet sheet = workbook.GetSheetAt(sheetIndex))
  398. {
  399. StringBuilder builder = new StringBuilder();
  400. IRow headerRow = sheet.GetRow(headerRowIndex);
  401. int cellCount = headerRow.LastCellNum;//LastCellNum = PhysicalNumberOfCells
  402. int rowCount = sheet.LastRowNum;//LastRowNum = PhysicalNumberOfRows - 1
  403. for (int i = (sheet.FirstRowNum + 1); i <= rowCount; i++)
  404. {
  405. IRow row = sheet.GetRow(i);
  406. if (row != null)
  407. {
  408. builder.Append(insertSql);
  409. builder.Append(" values (");
  410. for (int j = row.FirstCellNum; j < cellCount; j++)
  411. {
  412. builder.AppendFormat("'{0}',", GetCellValue(row.GetCell(j)).Replace("'", "''"));
  413. }
  414. builder.Length = builder.Length - 1;
  415. builder.Append(");");
  416. }
  417. if ((i % 50 == 0 || i == rowCount) && builder.Length > 0)
  418. {
  419. //每50条记载一次批量插入到数据库
  420. rowAffected += dbAction(builder.ToString());
  421. builder.Length = 0;
  422. }
  423. }
  424. }
  425. }
  426. }
  427. return rowAffected;
  428. }
  429. }
复制代码

弄一个DBheple 就可以完成该使用Excel

C#论坛 www.ibcibc.com IBC编程社区
C#
C#论坛
IBC编程社区
*滑块验证:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则