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文件的更多相关文章

  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. shell 调用其他shell脚本中的变量、函数

    在Shell中要如何调用别的shell脚本,或别的脚本中的变量,函数呢? 方法一:   . ./subscript.sh  (两个点之间,有空格) 方法二:   source ./subscript. ...

  2. 在Xshell中文件内容显示乱码

    1.修改系统语言 支持中文 echo $LANG    查看系统语言  默认 en_US.UFT_8 vim /etc/locale.conf    修改配置文件 将LANG的值改为 zh_CN.UT ...

  3. linux命令-------find命令之exec

    p.p1 { margin: 0; font: 18px "Hannotate SC"; color: rgba(4, 51, 255, 1); -webkit-text-stro ...

  4. NSDate小结

    dateFormat用法: y - 年 2013年,yyyy=2013,yy=13 M - 月 3月,M=3,MM=03,MMM=Mar,MMMM=March D - 一年中的第几天 d - 一月中的 ...

  5. java基础---泛型机制

    从java5 开始增加泛型机制,用于明确集合中可以放入的元素类型,只在编译时期有效,运行时不区分是什么类型. 格式:<数据类型> 泛型的本质是参数化类型,让数据类型作为参数传递,E相当于形 ...

  6. LevelDB学习笔记 (3): 长文解析memtable、跳表和内存池Arena

    LevelDB学习笔记 (3): 长文解析memtable.跳表和内存池Arena 1. MemTable的基本信息 我们前面说过leveldb的所有数据都会先写入memtable中,在leveldb ...

  7. 「AGC034E」 Complete Compress

    「AGC034E」 Complete Compress 显然可以枚举根. 然后把某两棵棋子同时往深度浅的方向提,即对不存在祖先关系的两个棋子进行操作. 如果能到达那么就更新答案. 问题转化为如何判定能 ...

  8. asp.net web.config数据库连接字符串加密与解密

    在WEB网站开发过程中,如果我们将数据库连接字符串封装到.DLL文件中,将会给数据库和程序的迁移带来麻烦,因为万一服务器地址或者数据库发生变更,那么我们就不得不修改源程序并重新将其编译.最好的解决方法 ...

  9. python numpy 求数组的百位分数

    百分位数,统计学术语,如果将一组数据从小到大排序,并计算相应的累计百分位,则某一百分位所对应数据的值就称为这一百分位的百分位数.运用在教育统计学中,例如表现测验成绩时,称PR值.分位数是以概率将一批数 ...

  10. MQTT 4 ——MQTT的Spring Mvc 配置接收字节流数据

    本篇记录一下MQTT整合Spring Mvc配置直接收发字节流数据 设备方是纯C开发,并且为了交互数据的安全,将传送的数据用了AES CBC进行了加密. 接下来正常方便做法应该是 将加密后的字节流转换 ...