netcoreMiniExcel轻量级开源组件使用
Posted 厦门德仔
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了netcoreMiniExcel轻量级开源组件使用相关的知识,希望对你有一定的参考价值。
MiniExcel轻量级开源组件使用
开源地址
添加链接描述
通常复杂的EXCEL操作采用NPIO组件,优点:性能优越,支持各种复杂操作。缺点:比较繁琐和重量级
MiniExcel:则可以满足大部分应用场景,又是轻量级
Guget:搜MiniExcel安装组件
导入&读取Excle
文档简介;
读/导入 Excel
- Query 查询 Excel 返回强型别 IEnumerable 数据 [Try it]
public class UserAccount
public Guid ID get; set;
public string Name get; set;
public DateTime BoD get; set;
public int Age get; set;
public bool VIP get; set;
public decimal Points get; set;
var rows = MiniExcel.Query<UserAccount>(path);
// or
using (var stream = File.OpenRead(path))
var rows = stream.Query<UserAccount>();
一句代码搞定,真TMD爽。
实践
前端:
<button class="layui-btn" lay-event="download" onclick="download()"> <i class="layui-icon"></i>下载模板</button>
<button class="layui-btn" lay-event="upload" id="upload"> <i class="layui-icon"></i>上传Excel</button>
<a href="javascript:;" class="a-upload">
<input type="file" name="" id="">点击这里上传文件
</a>
<!--表格容器-->
<table class="layui-hide" id="currentTableId" lay-filter="currentTableFilter"></table>
<script>
function download()
var filename = "品号信息.xlsx";
var url = '/MinExcel/RequestDownloadFile?filename=' + filename;
window.open(url);
;
//刷新表格函数
function reloadTable()
layui.table.reload('currentTableId',
page:
curr: 1
, where:
type: "select"
);
layui.use(['form', 'table', 'layer', 'upload'], function ()
var $ = layui.jquery,
form = layui.form,
upload = layui.upload,
element = layui.element,
layer = layui.layer,
table = layui.table;
//指定允许上传的文件类型
upload.render(
elem: '#upload'
, url: '/MinExcel/SingleFileUpload' //此处配置你自己的上传接口即可
, accept: 'file' //普通文件
, exts: 'xls|xlsx' //只允许上传压缩文件
, auto: true
, done: function (res)
layer.msg('上传成功');
console.log(res.completeFilePath);
//表格数据加载
var url = "/MinExcel/GetInvmbs?&path=" + res.completeFilePath;
table.render(
elem: '#currentTableId',
url: url,
height: 650,
width: 1300,
toolbar: '#toolbarDemo', // 表头工具栏
defaultToolbar: ['filter', 'exports', 'print',
title: '提示',
layEvent: 'LAYTABLE_TIPS',
icon: 'layui-icon-tips'
],
cols: [[
field: '品号', width: 200, title: '品号' ,
field: '品名', width: 300, title: '品名' ,
field: '规格', width: 300, title: '规格' ,
]],
skin: 'line', //表格风格 line (行边框风格)row (列边框风格)nob (无边框风格)
page: true,//开启分页
limits: [5, 15, 30, 50, 100], //每页条数的选择项,默认:[10,20,30,40,50,60,70,80,90]。
limit: 15, //每页默认显示的数量
where: type: "select" , //查询时要传递的参数
parseData: function (res) //res 即为原始返回的数据
//console.log(res);
//if (this.page.curr)
// result = res.data.slice(this.limit * (this.page.curr - 1), this.limit * this.page.curr);
//
//else
// result = res.data.slice(0, this.limit);
//
return
"code": 0, //res.status, //解析接口状态
"msg": res.message, //解析提示文本
"count": res.count, //解析数据长度 res.total 改成res.count
"data": res.data //解析数据列表
;
);
, error: function ()
//请求异常回调
layer.alert(res.msg);
);
);
</script>
Controller:
public class MinExcelController : Controller
private readonly IWebHostEnvironment _webHostingEnvironment;
public MinExcelController(IWebHostEnvironment hostingEnvironment)
_webHostingEnvironment = hostingEnvironment;
public IActionResult Index()
return View();
[HttpGet]
public IActionResult RequestDownloadFile(string filename) //[FromBody] dynamic Json
var FileName = filename;
var webRootPath = _webHostingEnvironment.WebRootPath;
var FilePath = webRootPath+$"/UploadFile/Filetpl/FileName";
return new FileStreamResult(new FileStream(FilePath, FileMode.Open), "application/octet-stream") FileDownloadName = FileName ;
/// <summary>
/// 单文件上传(ajax,Form表单都适用)
/// </summary>
/// <returns></returns>
[CustomAllowAnonymous]
[HttpPost]
public IActionResult SingleFileUpload()
var formFile = Request.Form.Files[0];//获取请求发送过来的文件
var currentDate = DateTime.Now;
var webRootPath = _webHostingEnvironment.WebRootPath;//>>>相当于HttpContext.Current.Server.MapPath("")
try
var filePath = $"/UploadFile/Filetemp/";
//创建每日存储文件夹
if (!Directory.Exists(webRootPath + filePath))
Directory.CreateDirectory(webRootPath + filePath);
if (formFile != null)
//文件后缀
var fileExtension = Path.GetExtension(formFile.FileName);//获取文件格式,拓展名
//判断文件大小
var fileSize = formFile.Length;
if (fileSize > 1024 * 1024 * 10) //10M TODO:(1mb=1024X1024b)
return new JsonResult(new isSuccess = false, resultMsg = "上传的文件不能大于10M" );
//Guid.NewGuid().ToString()
//保存的文件名称(以名称和保存时间命名)
var saveName = formFile.FileName.Substring(0, formFile.FileName.LastIndexOf('.')) + "_" + currentDate.ToString("HHmmss") + fileExtension;
//文件保存
using (var fs = System.IO.File.Create(webRootPath + filePath + saveName))
formFile.CopyTo(fs);
fs.Flush();
//完整的文件路径
var completeFilePath = Path.Combine(filePath, saveName);
return new JsonResult(new isSuccess = true, returnMsg = "上传成功", completeFilePath = completeFilePath );
else
return new JsonResult(new isSuccess = false, resultMsg = "上传失败,未检测上传的文件信息~" );
catch (Exception ex)
return new JsonResult(new isSuccess = false, resultMsg = "文件保存失败,异常信息为:" + ex.Message );
/// <summary>
/// 获取excel
/// </summary>
/// <param name="path"></param>
/// <param name="page"></param>
/// <param name="limit"></param>
/// <returns></returns>
[HttpGet]
public ActionResult<TableData> GetInvmbs(string path,int page, int limit)
//page =2: 第二页 limit=5 每页5条数据
var JsonData = new TableData();
try
//"../UploadFile/Filetemp/品号信息_132013.xlsx"
var webRootPath = _webHostingEnvironment.WebRootPath;
var FilePath = webRootPath + $"path";
var rows = MiniExcel.Query<Invmb>(FilePath); //@"E:\\\\品号信息.xlsx" 本地地址测试OK
var count = rows.Count();
JsonData.code = 0;
JsonData.msg = "数据获取成功";
JsonData.count = count;
JsonData.data = rows.OrderByDescending(c => c.品号).Skip(limit * (page - 1)).Take(limit).ToList();
DeleteFile(FilePath);
return JsonData;
catch (Exception e)
JsonData.code = 0;
JsonData.msg = "数据获取失败:" + e.Message;
JsonData.data = null;
return JsonData;
/// <summary>
/// 销毁文件
/// </summary>
/// <param name="path"></param>
void DeleteFile(string path)
if (System.IO.File.Exists(path))
System.IO.File.Delete(path);
public class Invmb
public string 品号 get; set;
public string 品名 get; set;
public string 规格 get; set;
效果
以上是关于netcoreMiniExcel轻量级开源组件使用的主要内容,如果未能解决你的问题,请参考以下文章