ASP.NET Core导入导出Excel文件


希望在ASP.NET Core中导入导出Excel文件,在网上搜了一遍,基本都是使用EPPlus插件,EPPlus挺好用,但商用需要授权,各位码友若有好的工具包推荐,请给我留言,谢谢!

本文利用Asp.net core Razor页面实现Excel文件的导入导出,参考大神的文章:ASP.NET Core 导入导出Excel xlsx 文件 - LineZero - 博客园 (cnblogs.com)

下面为详细步骤。

1,创建Razor项目

2,在Nuget包管理器中搜索EPPlus, 安装依赖包。EPPlus.Core已经弃用,EPPlus是支持Net Core的最新版本。

3,修改pages/Index.cshtml文件,创建基本导入导出页面。

  1. @page
  2. @model IndexModel
  3. @{
  4. ViewData["Title"] = "Home page";
  5. }
  6.  
  7. <div class="text-center">
  8. <h1 class="display-4">ASP.NET Core导入导出Excel文件</h1>
  9. </div>
  10.  
  11. <h2></h2>
  12. <hr />
  13. <div>
  14. <h4>导入Excel</h4>
  15. <hr />
  16. <form enctype="multipart/form-data" method="post" asp-page-handler="Import">
  17. <input type="file" name="excelFile"/>
  18. <input type="submit" value="导入"/>
  19. </form>
  20. <hr />
  21.  
  22. </div>
  23. <hr />
  24. <div>
  25. <h4>导出Excel</h4>
  26. <form enctype="multipart/form-data" method="post"asp-page-handler="Export">
  27. <input type="submit" value="导出"/>
  28. </form>
  29. </div>
  30. <hr />

4,修改Index.cshtml.cs文件中的代码,增加OnPostImport 和OnPostExport方法,分别用于导入、导出文件。

首先在构造函数中注入webHostEnvironment

  1. private readonly IWebHostEnvironment _webHostEnvironment;
  2.  
  3. public IndexModel(IWebHostEnvironment webHostEnvironment)
  4. {
  5. _webHostEnvironment = webHostEnvironment;
  6. }

OnPostImport代码:

  1. public IActionResult OnPostImport(IFormFile excelFile)
  2. {
  3. ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
  4. string sWebRootFolder = _webHostEnvironment.WebRootPath;
  5. string sFileName = $"{Guid.NewGuid()}.xlsx";
  6. FileInfo file = new FileInfo(Path.Combine(sWebRootFolder, sFileName));
  7. try
  8. {
  9. using (FileStream fs = new FileStream(file.ToString(), FileMode.Create))
  10. {
  11. excelFile.CopyTo(fs);
  12. fs.Flush();
  13. }
  14. using(ExcelPackage package = new ExcelPackage(file))
  15. {
  16. StringBuilder sb = new StringBuilder();
  17. ExcelWorksheet worksheet = package.Workbook.Worksheets[0];
  18. int rowCount = worksheet.Dimension.Rows;
  19. int colCount = worksheet.Dimension.Columns;
  20. bool bheaderRow = true;
  21. for(int row = 1; row <= rowCount; row++)
  22. {
  23. for(int col = 1; col <= colCount; col++)
  24. {
  25. if (bheaderRow)
  26. {
  27. if(worksheet.Cells[row, col].Value != null)
  28. {
  29. sb.Append(worksheet.Cells[row, col].Value.ToString() + "\t");
  30. }
  31. else
  32. {
  33. sb.Append("\t");
  34. }
  35. }
  36. else
  37. {
  38. if(worksheet.Cells[row, col].Value != null)
  39. {
  40. sb.Append(worksheet.Cells[row, col].Value.ToString() + "\t");
  41. }
  42. else
  43. {
  44. sb.Append("\t");
  45. }
  46. }
  47. }
  48. sb.Append(Environment.NewLine);
  49. if (bheaderRow)
  50. {
  51. sb.Append("-----------------------------------------");
  52. sb.Append(Environment.NewLine);
  53. }
  54. bheaderRow = false;
  55. }
  56. return Content(sb.ToString());
  57. }
  58. }
  59. catch(Exception ex)
  60. {
  61. return Content(ex.Message);
  62. }
  63. }

其中必须添加

  1. ExcelPackage.LicenseContext = LicenseContext.NonCommercial 用于指定EPPlus的使用授权为非商用。缺少会报错。

    OnPostExport代码:
  1. public IActionResult OnPostExport()
  2. {
  3. string sWebRootFolder = _webHostEnvironment.WebRootPath;
  4. string sFileName = $"{Guid.NewGuid()}.xlsx";
  5. FileInfo file = new FileInfo(Path.Combine(sWebRootFolder, sFileName));
  6. ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
  7. using (ExcelPackage package=new ExcelPackage(file))
  8. {
  9. //add worksheet
  10. ExcelWorksheet workSheet = package.Workbook.Worksheets.Add("AspNetCore");
  11. //add table header
  12. workSheet.Cells[1, 1].Value = "ID";
  13. workSheet.Cells[1, 2].Value = "Name";
  14. workSheet.Cells[1, 3].Value = "Gender";
  15. workSheet.Cells[1, 4].Value = "Age";
  16. workSheet.Cells[1, 5].Value = "Remark";
  17.  
  18. //Add value
  19. workSheet.Cells["A2"].Value = 1000;
  20. workSheet.Cells["B2"].Value = "张三";
  21. workSheet.Cells["C2"].Value = "男";
  22. workSheet.Cells["D2"].Value = 25;
  23. workSheet.Cells["E2"].Value = "ABCD";
  24.  
  25. workSheet.Cells["A3"].Value = 1001;
  26. workSheet.Cells["B3"].Value = "李四";
  27. workSheet.Cells["C3"].Value = "女";
  28. workSheet.Cells["D3"].Value = 35;
  29. workSheet.Cells["D3"].Style.Font.Bold = true;
  30.  
  31. workSheet.Cells["A4"].Value = 1003;
  32. workSheet.Cells["B4"].Value = "Amy";
  33. workSheet.Cells["C4"].Value = "Female";
  34. workSheet.Cells["D4"].Value = 22;
  35. workSheet.Cells["E4"].Value = "Hello world";
  36.  
  37. workSheet.Cells["A5"].Value = 1004;
  38. workSheet.Cells["B5"].Value = "Jim";
  39. workSheet.Cells["C5"].Value = "Male";
  40. workSheet.Cells["D5"].Value = 35;
  41. workSheet.Cells["E5"].Value = 500;
  42.  
  43. package.Save();
  44. }
  45.  
  46. return File(sFileName, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
  47. }

Index.cshtml.cs的完整代码如下:

  1. using Microsoft.AspNetCore.Hosting;
  2. using Microsoft.AspNetCore.Http;
  3. using Microsoft.AspNetCore.Mvc;
  4. using Microsoft.AspNetCore.Mvc.RazorPages;
  5. using Microsoft.Extensions.Logging;
  6. using OfficeOpenXml;
  7. using System;
  8. using System.Collections.Generic;
  9. using System.IO;
  10. using System.Linq;
  11. using System.Text;
  12. using System.Threading.Tasks;
  13. using WebAppTest.Models;
  14.  
  15. namespace WebAppTest.Pages
  16. {
  17. public class IndexModel : PageModel
  18. {
  19. private readonly ILogger<IndexModel> _logger;
  20. private readonly IWebHostEnvironment _webHostEnvironment;
  21.  
  22. public IndexModel(ILogger<IndexModel> logger,IWebHostEnvironment webHostEnvironment)
  23. {
  24. _logger = logger;
  25. _context = context;
  26. _webHostEnvironment = webHostEnvironment;
  27. }
  28.  
  29. public void OnGet()
  30. {
  31.  
  32. }
  33.  
  34. public IActionResult OnPostImport(IFormFile excelFile)
  35. {
  36. ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
  37. string sWebRootFolder = _webHostEnvironment.WebRootPath;
  38. string sFileName = $"{Guid.NewGuid()}.xlsx";
  39. FileInfo file = new FileInfo(Path.Combine(sWebRootFolder, sFileName));
  40. try
  41. {
  42. using (FileStream fs = new FileStream(file.ToString(), FileMode.Create))
  43. {
  44. excelFile.CopyTo(fs);
  45. fs.Flush();
  46. }
  47. using(ExcelPackage package = new ExcelPackage(file))
  48. {
  49. StringBuilder sb = new StringBuilder();
  50. ExcelWorksheet worksheet = package.Workbook.Worksheets[0];
  51. int rowCount = worksheet.Dimension.Rows;
  52. int colCount = worksheet.Dimension.Columns;
  53. bool bheaderRow = true;
  54. for(int row = 1; row <= rowCount; row++)
  55. {
  56. for(int col = 1; col <= colCount; col++)
  57. {
  58. if (bheaderRow)
  59. {
  60. if(worksheet.Cells[row, col].Value != null)
  61. {
  62. sb.Append(worksheet.Cells[row, col].Value.ToString() + "\t");
  63. }
  64. else
  65. {
  66. sb.Append("\t");
  67. }
  68. }
  69. else
  70. {
  71. if(worksheet.Cells[row, col].Value != null)
  72. {
  73. sb.Append(worksheet.Cells[row, col].Value.ToString() + "\t");
  74. }
  75. else
  76. {
  77. sb.Append("\t");
  78. }
  79. }
  80. }
  81. sb.Append(Environment.NewLine);
  82. if (bheaderRow)
  83. {
  84. sb.Append("-----------------------------------------");
  85. sb.Append(Environment.NewLine);
  86. }
  87. bheaderRow = false;
  88. }
  89. return Content(sb.ToString());
  90. }
  91. }
  92. catch(Exception ex)
  93. {
  94. return Content(ex.Message);
  95. }
  96. }
  97.  
  98. public IActionResult OnPostExport()
  99. {
  100. string sWebRootFolder = _webHostEnvironment.WebRootPath;
  101. string sFileName = $"{Guid.NewGuid()}.xlsx";
  102. FileInfo file = new FileInfo(Path.Combine(sWebRootFolder, sFileName));
  103. ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
  104. using (ExcelPackage package=new ExcelPackage(file))
  105. {
  106. //add worksheet
  107. ExcelWorksheet workSheet = package.Workbook.Worksheets.Add("AspNetCore");
  108. //add table header
  109. workSheet.Cells[1, 1].Value = "ID";
  110. workSheet.Cells[1, 2].Value = "Name";
  111. workSheet.Cells[1, 3].Value = "Gender";
  112. workSheet.Cells[1, 4].Value = "Age";
  113. workSheet.Cells[1, 5].Value = "Remark";
  114.  
  115. //Add value
  116. workSheet.Cells["A2"].Value = 1000;
  117. workSheet.Cells["B2"].Value = "张三";
  118. workSheet.Cells["C2"].Value = "男";
  119. workSheet.Cells["D2"].Value = 25;
  120. workSheet.Cells["E2"].Value = "ABCD";
  121.  
  122. workSheet.Cells["A3"].Value = 1001;
  123. workSheet.Cells["B3"].Value = "李四";
  124. workSheet.Cells["C3"].Value = "女";
  125. workSheet.Cells["D3"].Value = 35;
  126. workSheet.Cells["D3"].Style.Font.Bold = true;
  127.  
  128. workSheet.Cells["A4"].Value = 1003;
  129. workSheet.Cells["B4"].Value = "Amy";
  130. workSheet.Cells["C4"].Value = "Female";
  131. workSheet.Cells["D4"].Value = 22;
  132. workSheet.Cells["E4"].Value = "Hello world";
  133.  
  134. workSheet.Cells["A5"].Value = 1004;
  135. workSheet.Cells["B5"].Value = "Jim";
  136. workSheet.Cells["C5"].Value = "Male";
  137. workSheet.Cells["D5"].Value = 35;
  138. workSheet.Cells["E5"].Value = 500;
  139.  
  140. package.Save();
  141. }
  142.  
  143. return File(sFileName, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
  144. }
  145. }
  146. }

5,运行项目,测试导入导出功能。

导出功能,单击导出按钮,浏览器会下载excel文件,

导入功能,点击选择文件按钮,选择刚下载的excel文件,点击导入按钮,跳转到导入结果页面。


------------------------ 完成---------------------

  1.  

ASP.NET Core导入导出Excel文件的更多相关文章

  1. ASP.NET Core 导入导出Excel xlsx 文件

    ASP.NET Core 使用EPPlus.Core导入导出Excel xlsx 文件,EPPlus.Core支持Excel 2007/2010 xlsx文件导入导出,可以运行在Windows, Li ...

  2. 【转】 (C#)利用Aspose.Cells组件导入导出excel文件

    Aspose.Cells组件可以不依赖excel来导入导出excel文件: 导入: public static System.Data.DataTable ReadExcel(String strFi ...

  3. (C#)利用Aspose.Cells组件导入导出excel文件

    Aspose.Cells组件可以不依赖excel来导入导出excel文件: 导入: public static System.Data.DataTable ReadExcel(String strFi ...

  4. 导入导出Excel文件

    搭建环境 先新建web project ,然后Add Struts Capabilties: 下载导入导出Excel所需的jar包: poi-3.8-20120326.jar包  :  http:// ...

  5. java中使用poi导入导出excel文件_并自定义日期格式

    Apache POI项目的使命是创造和保持java API操纵各种文件格式基于Office Open XML标准(OOXML)和微软的OLE复合文档格式(OLE2)2.总之,你可以读写Excel文件使 ...

  6. C# 导入导出excel文件案例

    个人总结导出excel报表的案例: //导出报表 protected void btnExport_Click(object sender, EventArgs e) { List<ProOut ...

  7. java导入导出Excel文件

    package poi.excel; import java.io.IOException; import java.io.InputStream; import java.io.OutputStre ...

  8. 简单回顾NPOI导入导出excel文件

    当前环境.net4.0 去官方下下载:  NOPI官网 关于NOPI的详细,这里就不再介绍. 在项目中,我们只需引入  NPOI.dll  就可以了. 接下来..................... ...

  9. SpringMVC 导入导出Excel文件

    /**  * 下载Excel模板 创建一个新的文件用于下载,创建的文件放在缓存中  *   * @param request  * @param response  */ /*  * @Request ...

随机推荐

  1. 所有的Java虚拟机必须实现在每个类或接口被Java程序 “ 首次主动使用 ” 时才初始化他们

    原文:https://www.cnblogs.com/fanjie/p/6916784.html Java程序对类的使用方式可分为两种– 主动使用– 被动使用 被动使用以后再讲,这里说说什么是主动使用 ...

  2. Androidmanifest.xml文件格式详解(转载)

    https://www.jianshu.com/p/eaaae96473f6 来自简书大佬的

  3. buu 达芬奇 && ROT

    一.达芬奇 百度了下电影简介,发现了斐波那契数列,同时发现密文是由斐波那契数列移动而来的,有点像base64变种 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 ...

  4. 使用 Java 和 Maven (JBake) 生成静态网站

    使用 JBake("mvn generate-resources")构建您的静态网站或博客.使用布局.宏和数据文件. 我们迁移了整个www.optaplanner.org网站(13 ...

  5. Springboot中Rest风格请求映射如何开启并使用

    问题引入 因为前端页面只能请求两种方式:GET请求和POST请求,所以就需要后台对其进行处理 解决办法:通过springmvc中提供的HiddenHttpMethodFilter过滤器来实现 而由于我 ...

  6. python 16篇 多线程和多进程

    1.概念 线程.进程 进程 一个程序,它是一组资源的集合 一个进程里面默认是有一个线程的,主线程 多进程是可以利用多核cpu的线程 最小的执行单位 线程和线程之间是互相独立的 主线程等待子线程执行结束 ...

  7. C语言:统计字符个数及种类

    #include <stdio.h> int main(){ char c; //用户输入的字符 int shu=0;//字符总数 int letters=0, // 字母数目 space ...

  8. js中 typeof 和 instanceof 的区别

    typeof 和 instanceof 都能判断数据类型,但是它们之间有什么区别呢,浅谈如下 typeof 用于判断数据类型,返回值为以下6种类型 1.string 2.boolean 3.numbe ...

  9. VirtualBox 修改Android x86虚拟机的分辨率

    首先说明一下,本人使用的是Windows下的VirtualBox,android x86使用的是9.0-r2版本 一.查看virtualbox中已有的分辨率 启动虚拟机后,连续按两次E键,进入下面页面 ...

  10. Vue 可拖拽组件 Vue Smooth DnD 详解和应用演示

    本文发布自 https://www.cnblogs.com/wenruo/p/15061907.html 转载请注明出处. 简介和 Demo 展示 最近需要有个拖拽列表的需求,发现一个简单好用的 Vu ...