ASP.NET Core导入导出Excel文件
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文件,创建基本导入导出页面。
@page
@model IndexModel
@{
ViewData["Title"] = "Home page";
} <div class="text-center">
<h1 class="display-4">ASP.NET Core导入导出Excel文件</h1>
</div> <h2></h2>
<hr />
<div>
<h4>导入Excel</h4>
<hr />
<form enctype="multipart/form-data" method="post" asp-page-handler="Import">
<input type="file" name="excelFile"/>
<input type="submit" value="导入"/>
</form>
<hr /> </div>
<hr />
<div>
<h4>导出Excel</h4>
<form enctype="multipart/form-data" method="post"asp-page-handler="Export">
<input type="submit" value="导出"/>
</form>
</div>
<hr />

4,修改Index.cshtml.cs文件中的代码,增加OnPostImport 和OnPostExport方法,分别用于导入、导出文件。
首先在构造函数中注入webHostEnvironment
private readonly IWebHostEnvironment _webHostEnvironment;
public IndexModel(IWebHostEnvironment webHostEnvironment)
{
_webHostEnvironment = webHostEnvironment;
}
OnPostImport代码:
public IActionResult OnPostImport(IFormFile excelFile)
{
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
string sWebRootFolder = _webHostEnvironment.WebRootPath;
string sFileName = $"{Guid.NewGuid()}.xlsx";
FileInfo file = new FileInfo(Path.Combine(sWebRootFolder, sFileName));
try
{
using (FileStream fs = new FileStream(file.ToString(), FileMode.Create))
{
excelFile.CopyTo(fs);
fs.Flush();
}
using(ExcelPackage package = new ExcelPackage(file))
{
StringBuilder sb = new StringBuilder();
ExcelWorksheet worksheet = package.Workbook.Worksheets[0];
int rowCount = worksheet.Dimension.Rows;
int colCount = worksheet.Dimension.Columns;
bool bheaderRow = true;
for(int row = 1; row <= rowCount; row++)
{
for(int col = 1; col <= colCount; col++)
{
if (bheaderRow)
{
if(worksheet.Cells[row, col].Value != null)
{
sb.Append(worksheet.Cells[row, col].Value.ToString() + "\t");
}
else
{
sb.Append("\t");
}
}
else
{
if(worksheet.Cells[row, col].Value != null)
{
sb.Append(worksheet.Cells[row, col].Value.ToString() + "\t");
}
else
{
sb.Append("\t");
}
}
}
sb.Append(Environment.NewLine);
if (bheaderRow)
{
sb.Append("-----------------------------------------");
sb.Append(Environment.NewLine);
}
bheaderRow = false;
}
return Content(sb.ToString());
}
}
catch(Exception ex)
{
return Content(ex.Message);
}
}
其中必须添加
ExcelPackage.LicenseContext = LicenseContext.NonCommercial 用于指定EPPlus的使用授权为非商用。缺少会报错。
OnPostExport代码:
public IActionResult OnPostExport()
{
string sWebRootFolder = _webHostEnvironment.WebRootPath;
string sFileName = $"{Guid.NewGuid()}.xlsx";
FileInfo file = new FileInfo(Path.Combine(sWebRootFolder, sFileName));
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
using (ExcelPackage package=new ExcelPackage(file))
{
//add worksheet
ExcelWorksheet workSheet = package.Workbook.Worksheets.Add("AspNetCore");
//add table header
workSheet.Cells[1, 1].Value = "ID";
workSheet.Cells[1, 2].Value = "Name";
workSheet.Cells[1, 3].Value = "Gender";
workSheet.Cells[1, 4].Value = "Age";
workSheet.Cells[1, 5].Value = "Remark"; //Add value
workSheet.Cells["A2"].Value = 1000;
workSheet.Cells["B2"].Value = "张三";
workSheet.Cells["C2"].Value = "男";
workSheet.Cells["D2"].Value = 25;
workSheet.Cells["E2"].Value = "ABCD"; workSheet.Cells["A3"].Value = 1001;
workSheet.Cells["B3"].Value = "李四";
workSheet.Cells["C3"].Value = "女";
workSheet.Cells["D3"].Value = 35;
workSheet.Cells["D3"].Style.Font.Bold = true; workSheet.Cells["A4"].Value = 1003;
workSheet.Cells["B4"].Value = "Amy";
workSheet.Cells["C4"].Value = "Female";
workSheet.Cells["D4"].Value = 22;
workSheet.Cells["E4"].Value = "Hello world"; workSheet.Cells["A5"].Value = 1004;
workSheet.Cells["B5"].Value = "Jim";
workSheet.Cells["C5"].Value = "Male";
workSheet.Cells["D5"].Value = 35;
workSheet.Cells["E5"].Value = 500; package.Save();
} return File(sFileName, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
}
Index.cshtml.cs的完整代码如下:
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
using OfficeOpenXml;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WebAppTest.Models; namespace WebAppTest.Pages
{
public class IndexModel : PageModel
{
private readonly ILogger<IndexModel> _logger;
private readonly IWebHostEnvironment _webHostEnvironment; public IndexModel(ILogger<IndexModel> logger,IWebHostEnvironment webHostEnvironment)
{
_logger = logger;
_context = context;
_webHostEnvironment = webHostEnvironment;
} public void OnGet()
{ } public IActionResult OnPostImport(IFormFile excelFile)
{
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
string sWebRootFolder = _webHostEnvironment.WebRootPath;
string sFileName = $"{Guid.NewGuid()}.xlsx";
FileInfo file = new FileInfo(Path.Combine(sWebRootFolder, sFileName));
try
{
using (FileStream fs = new FileStream(file.ToString(), FileMode.Create))
{
excelFile.CopyTo(fs);
fs.Flush();
}
using(ExcelPackage package = new ExcelPackage(file))
{
StringBuilder sb = new StringBuilder();
ExcelWorksheet worksheet = package.Workbook.Worksheets[0];
int rowCount = worksheet.Dimension.Rows;
int colCount = worksheet.Dimension.Columns;
bool bheaderRow = true;
for(int row = 1; row <= rowCount; row++)
{
for(int col = 1; col <= colCount; col++)
{
if (bheaderRow)
{
if(worksheet.Cells[row, col].Value != null)
{
sb.Append(worksheet.Cells[row, col].Value.ToString() + "\t");
}
else
{
sb.Append("\t");
}
}
else
{
if(worksheet.Cells[row, col].Value != null)
{
sb.Append(worksheet.Cells[row, col].Value.ToString() + "\t");
}
else
{
sb.Append("\t");
}
}
}
sb.Append(Environment.NewLine);
if (bheaderRow)
{
sb.Append("-----------------------------------------");
sb.Append(Environment.NewLine);
}
bheaderRow = false;
}
return Content(sb.ToString());
}
}
catch(Exception ex)
{
return Content(ex.Message);
}
} public IActionResult OnPostExport()
{
string sWebRootFolder = _webHostEnvironment.WebRootPath;
string sFileName = $"{Guid.NewGuid()}.xlsx";
FileInfo file = new FileInfo(Path.Combine(sWebRootFolder, sFileName));
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
using (ExcelPackage package=new ExcelPackage(file))
{
//add worksheet
ExcelWorksheet workSheet = package.Workbook.Worksheets.Add("AspNetCore");
//add table header
workSheet.Cells[1, 1].Value = "ID";
workSheet.Cells[1, 2].Value = "Name";
workSheet.Cells[1, 3].Value = "Gender";
workSheet.Cells[1, 4].Value = "Age";
workSheet.Cells[1, 5].Value = "Remark"; //Add value
workSheet.Cells["A2"].Value = 1000;
workSheet.Cells["B2"].Value = "张三";
workSheet.Cells["C2"].Value = "男";
workSheet.Cells["D2"].Value = 25;
workSheet.Cells["E2"].Value = "ABCD"; workSheet.Cells["A3"].Value = 1001;
workSheet.Cells["B3"].Value = "李四";
workSheet.Cells["C3"].Value = "女";
workSheet.Cells["D3"].Value = 35;
workSheet.Cells["D3"].Style.Font.Bold = true; workSheet.Cells["A4"].Value = 1003;
workSheet.Cells["B4"].Value = "Amy";
workSheet.Cells["C4"].Value = "Female";
workSheet.Cells["D4"].Value = 22;
workSheet.Cells["E4"].Value = "Hello world"; workSheet.Cells["A5"].Value = 1004;
workSheet.Cells["B5"].Value = "Jim";
workSheet.Cells["C5"].Value = "Male";
workSheet.Cells["D5"].Value = 35;
workSheet.Cells["E5"].Value = 500; package.Save();
} return File(sFileName, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
}
}
}
5,运行项目,测试导入导出功能。
导出功能,单击导出按钮,浏览器会下载excel文件,


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


------------------------ 完成---------------------
ASP.NET Core导入导出Excel文件的更多相关文章
- ASP.NET Core 导入导出Excel xlsx 文件
ASP.NET Core 使用EPPlus.Core导入导出Excel xlsx 文件,EPPlus.Core支持Excel 2007/2010 xlsx文件导入导出,可以运行在Windows, Li ...
- 【转】 (C#)利用Aspose.Cells组件导入导出excel文件
Aspose.Cells组件可以不依赖excel来导入导出excel文件: 导入: public static System.Data.DataTable ReadExcel(String strFi ...
- (C#)利用Aspose.Cells组件导入导出excel文件
Aspose.Cells组件可以不依赖excel来导入导出excel文件: 导入: public static System.Data.DataTable ReadExcel(String strFi ...
- 导入导出Excel文件
搭建环境 先新建web project ,然后Add Struts Capabilties: 下载导入导出Excel所需的jar包: poi-3.8-20120326.jar包 : http:// ...
- java中使用poi导入导出excel文件_并自定义日期格式
Apache POI项目的使命是创造和保持java API操纵各种文件格式基于Office Open XML标准(OOXML)和微软的OLE复合文档格式(OLE2)2.总之,你可以读写Excel文件使 ...
- C# 导入导出excel文件案例
个人总结导出excel报表的案例: //导出报表 protected void btnExport_Click(object sender, EventArgs e) { List<ProOut ...
- java导入导出Excel文件
package poi.excel; import java.io.IOException; import java.io.InputStream; import java.io.OutputStre ...
- 简单回顾NPOI导入导出excel文件
当前环境.net4.0 去官方下下载: NOPI官网 关于NOPI的详细,这里就不再介绍. 在项目中,我们只需引入 NPOI.dll 就可以了. 接下来..................... ...
- SpringMVC 导入导出Excel文件
/** * 下载Excel模板 创建一个新的文件用于下载,创建的文件放在缓存中 * * @param request * @param response */ /* * @Request ...
随机推荐
- 详解 MD5 信息摘要算法
对于软件研发人员来说 MD5 不是一个陌生的词汇,平时的软件研发中,经常使用 MD5 校验消息是否被篡改.验证文件完整性,甚至将MD5当作加密算法使用. MD5虽不陌生,但不是所有研发人员都了解其算法 ...
- SpringBoot:SpringCloud与SpringBoot兼容版本参(其它组件兼容情况)
SpringCloud --- Springboot 版本兼容 SpringCloud SpringBoot Edgware.SR5 >=1.5.0.RELEASE and <=1.5.2 ...
- Java:Java的~取反运算符详解
例: ~15 先变成二进制:15:0000 1111 这个其实挺简单的,就是把1变0,0变1 注意:二进制中,最高位是符号位 1表示负数,0表示正数
- Game游戏分析
1.鲁棒图分析 2.系统上下文及交互方式 3.用例 4.逻辑拓扑图 5.物理拓扑图 6.时序图 7.状态图 8.物理数据模型 9.类图 10.技术选型 11.框架搭建 12.工具及通用服务 13.架构 ...
- ARTS第四周
补第四周 1.Algorithm:每周至少做一个 leetcode 的算法题2.Review:阅读并点评至少一篇英文技术文章3.Tip:学习至少一个技术技巧4.Share:分享一篇有观点和思考的技术文 ...
- java基础---数组的基本概念(1)
学习资源来自尚硅谷java基础学习 1. 数组的概念 数组(Array), 是多个相同类型数据按一定顺序排列的集合, 并使用一个名字命名, 并通过编号的方式对这些数据进行统一管理. 数组属于引用数据类 ...
- ffiddler抓取手机(app)https包
很多同学有看过原文,但是按照原文还是没有设置成功(我就是其中一个)然后查了网上资料,在某些选项上进行增加,填写,配置通过.(和原文略有不同) 安装Fiddler,我们正常的流程在feiddler中设置 ...
- session过期跳转到登陆页面并解决跳出iframe问题
首先,先转载如下这篇博主写的关于后台系统使用iframe不能跳出的问题,地址:https://blog.csdn.net/xiaocen99/article/details/38521649 在ifr ...
- UI作品评审总结:切忌过度设计,注意设计闭环
本期,我们一起看看学长认证模块--UI同学的作品评审. 拿好小板凳,做好笔记,我们开始吧! 我们拿了两个典型的作品进行了一个讲解,做的特色都还不错,但是都有些小问题. 先来看一下第一位 ...
- Redux-基本概念
相关文档 1) 英文文档: https://redux.js.org/ 2) 中文文档: http://www.redux.org.cn/ 3) Git ...