.NET Core6.0使用NPOI导入导出Excel

一、使用NPOI导出Excel
//引入NPOI包
在这里插入图片描述

  • HTML
<input type="button" class="layui-btn layui-btn-blue2 layui-btn-sm" id="ExportExcel" onclick="ExportExcel()" value="导出" />
  • JS
    //导出Excelfunction ExportExcel() {window.location.href = "@Url.Action("ExportFile")";}
  • C#
 private readonly Microsoft.AspNetCore.Hosting.IHostingEnvironment _hostingEnvironment;public HomeController(Microsoft.AspNetCore.Hosting.IHostingEnvironment hostingEnvironment){_hostingEnvironment = hostingEnvironment;}[HttpGet("ExportFile")]//导出文件public async Task<IActionResult> ExportFile(){//获取数据库数据var result = await _AnsweringQuestion.GetTeacherName();string filePath = "";//获取文件路径和名称var wwwroot = _hostingEnvironment.WebRootPath;var filename = "Table.xlsx";filePath = Path.Combine(wwwroot, filename);//创建一个工作簿和工作表NPOI.XSSF.UserModel.XSSFWorkbook book = new NPOI.XSSF.UserModel.XSSFWorkbook();var sheet = book.CreateSheet();//创建表头行var headerRow = sheet.CreateRow(0);headerRow.CreateCell(0).SetCellValue("姓名");headerRow.CreateCell(1).SetCellValue("科目");headerRow.CreateCell(2).SetCellValue("说明");//创建数据行var data = result.DataList;for (int i = 0; i < data.Count(); i++){var dataRow = sheet.CreateRow(i + 1);dataRow.CreateCell(0).SetCellValue(data[i].TeacherName);dataRow.CreateCell(1).SetCellValue(data[i].TeachSubject); dataRow.CreateCell(2).SetCellValue(data[i].TeacherDesc);}//将Execel 文件写入磁盘using (var f = System.IO.File.OpenWrite(filePath)){book.Write(f);}//将Excel 文件作为下载返回给客户端var bytes = System.IO.File.ReadAllBytes(filePath);return File(bytes, "application/octet-stream", $"{System.DateTime.Now.ToString("yyyyMMdd")}.xlsx");}

二、使用NPOI导入Excel

  • HTML
 <input type="button" class="layui-btn layui-btn-blue2 layui-btn-sm" id="Excel" value="导入" />
  • JS
    <script>/*从本地添加excel文件方法*/layui.use('upload', function () {var $ = layui.jquery, upload = layui.upload, form = layui.form;upload.render({elem: '#Excel'//附件上传按钮ID, url: '/Home/ImportFile'//附件上传后台地址, multiple: true, accept: 'file', exts: 'xls|xlsx'//(允许的类别), before: function (obj) {/*上传前执行的部分*/ }, done: function excel(res) {console.log(res);}, allDone: function (res) {console.log(res);}});});//上传事件结束
</script>
  • C#
  • 控制器代码
        //注入依赖private readonly Microsoft.AspNetCore.Hosting.IHostingEnvironment _hostingEnvironment;public HomeController(Microsoft.AspNetCore.Hosting.IHostingEnvironment hostingEnvironment){_hostingEnvironment = hostingEnvironment;}//控制器/// <summary>/// 导入/// </summary>/// <param name="file"></param>/// <returns></returns>[RequestSizeLimit(524288000)]  //文件大小限制[HttpPost]public async Task<IActionResult> ImportFile(IFormFile file){//把文件保存到文件夹下var path = "wwwroot/" + file.FileName;using (FileStream files = new FileStream(path, FileMode.OpenOrCreate)){file.CopyTo(files);}var wwwroot = _hostingEnvironment.WebRootPath;var fileSrc = wwwroot+"\\"+ file.FileName;List<UserEntity> list = new ExcelHelper<UserEntity>().ImportFromExcel(fileSrc);//取到数据后,接下来写你的业务逻辑就可以了for (int i = 0; i < list.Count; i++){var Name = string.IsNullOrEmpty(list[i].Name.ToString())? "" : list[i].Name.ToString();var Age = string.IsNullOrEmpty(list[i].Age.ToString()) ? "" : list[i].Age.ToString();var Gender = string.IsNullOrEmpty(list[i].Gender.ToString()) ? "" : list[i].Gender.ToString();var Tel = string.IsNullOrEmpty(list[i].Tel.ToString()) ? "" : list[i].Tel.ToString();}return Ok(new { Msg = "导入成功", Code = 200});}
  • 添加ExcelHelper类
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System.Collections.Concurrent;
using System.ComponentModel;
using System.Reflection;namespace NetCore6Demo.Models
{public class ExcelHelper<T> where T : new(){#region Excel导入/// <summary>/// Excel导入/// </summary>/// <param name="filePath"></param>/// <returns></returns>public List<T> ImportFromExcel(string FilePath){List<T> list = new List<T>();HSSFWorkbook hssfWorkbook = null;XSSFWorkbook xssWorkbook = null;ISheet sheet = null;using (FileStream file = new FileStream(FilePath, FileMode.Open, FileAccess.Read)){switch (Path.GetExtension(FilePath)){case ".xls":hssfWorkbook = new HSSFWorkbook(file);sheet = hssfWorkbook.GetSheetAt(0);break;case ".xlsx":xssWorkbook = new XSSFWorkbook(file);sheet = xssWorkbook.GetSheetAt(0);break;default:throw new Exception("不支持的文件格式");}}IRow columnRow = sheet.GetRow(0); //第1行为字段名Dictionary<int, PropertyInfo> mapPropertyInfoDict = new Dictionary<int, PropertyInfo>();for (int j = 0; j < columnRow.LastCellNum; j++){ICell cell = columnRow.GetCell(j);PropertyInfo propertyInfo = MapPropertyInfo(cell.ParseToString());if (propertyInfo != null){mapPropertyInfoDict.Add(j, propertyInfo);}}for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++){IRow row = sheet.GetRow(i);T entity = new T();for (int j = row.FirstCellNum; j < columnRow.LastCellNum; j++){if (mapPropertyInfoDict.ContainsKey(j)){if (row.GetCell(j) != null){PropertyInfo propertyInfo = mapPropertyInfoDict[j];switch (propertyInfo.PropertyType.ToString()){case "System.DateTime":case "System.Nullable`1[System.DateTime]":mapPropertyInfoDict[j].SetValue(entity, row.GetCell(j).ParseToString().ParseToDateTime());break;case "System.Boolean":case "System.Nullable`1[System.Boolean]":mapPropertyInfoDict[j].SetValue(entity, row.GetCell(j).ParseToString().ParseToBool());break;case "System.Byte":case "System.Nullable`1[System.Byte]":mapPropertyInfoDict[j].SetValue(entity, Byte.Parse(row.GetCell(j).ParseToString()));break;case "System.Int16":case "System.Nullable`1[System.Int16]":mapPropertyInfoDict[j].SetValue(entity, Int16.Parse(row.GetCell(j).ParseToString()));break;case "System.Int32":case "System.Nullable`1[System.Int32]":mapPropertyInfoDict[j].SetValue(entity, row.GetCell(j).ParseToString().ParseToInt());break;case "System.Int64":case "System.Nullable`1[System.Int64]":mapPropertyInfoDict[j].SetValue(entity, row.GetCell(j).ParseToString().ParseToLong());break;case "System.Double":case "System.Nullable`1[System.Double]":mapPropertyInfoDict[j].SetValue(entity, row.GetCell(j).ParseToString().ParseToDouble());break;case "System.Single":case "System.Nullable`1[System.Single]":mapPropertyInfoDict[j].SetValue(entity, row.GetCell(j).ParseToString().ParseToDouble());break;case "System.Decimal":case "System.Nullable`1[System.Decimal]":mapPropertyInfoDict[j].SetValue(entity, row.GetCell(j).ParseToString().ParseToDecimal());break;default:case "System.String":mapPropertyInfoDict[j].SetValue(entity, row.GetCell(j).ParseToString());break;}}}}list.Add(entity);}hssfWorkbook?.Close();xssWorkbook?.Close();return list;}/// <summary>/// 查找Excel列名对应的实体属性/// </summary>/// <param name="columnName"></param>/// <returns></returns>private PropertyInfo MapPropertyInfo(string columnName){PropertyInfo[] propertyList = GetProperties(typeof(T));PropertyInfo propertyInfo = propertyList.Where(p => p.Name == columnName).FirstOrDefault();if (propertyInfo != null){return propertyInfo;}else{foreach (PropertyInfo tempPropertyInfo in propertyList){DescriptionAttribute[] attributes = (DescriptionAttribute[])tempPropertyInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);if (attributes.Length > 0){if (attributes[0].Description == columnName){return tempPropertyInfo;}}}}return null;}private static ConcurrentDictionary<string, object> dictCache = new ConcurrentDictionary<string, object>();#region 得到类里面的属性集合/// <summary>/// 得到类里面的属性集合/// </summary>/// <param name="type"></param>/// <param name="columns"></param>/// <returns></returns>public static PropertyInfo[] GetProperties(Type type, string[] columns = null){PropertyInfo[] properties = null;if (dictCache.ContainsKey(type.FullName)){properties = dictCache[type.FullName] as PropertyInfo[];}else{properties = type.GetProperties();dictCache.TryAdd(type.FullName, properties);}if (columns != null && columns.Length > 0){//  按columns顺序返回属性var columnPropertyList = new List<PropertyInfo>();foreach (var column in columns){var columnProperty = properties.Where(p => p.Name == column).FirstOrDefault();if (columnProperty != null){columnPropertyList.Add(columnProperty);}}return columnPropertyList.ToArray();}else{return properties;}}#endregion#endregion}
}
  • 添加Extensions类
 public static partial class Extensions{#region 转换为long/// <summary>/// 将object转换为long,若转换失败,则返回0。不抛出异常。  /// </summary>/// <param name="str"></param>/// <returns></returns>public static long ParseToLong(this object obj){try{return long.Parse(obj.ToString());}catch{return 0L;}}/// <summary>/// 将object转换为long,若转换失败,则返回指定值。不抛出异常。  /// </summary>/// <param name="str"></param>/// <param name="defaultValue"></param>/// <returns></returns>public static long ParseToLong(this string str, long defaultValue){try{return long.Parse(str);}catch{return defaultValue;}}#endregion#region 转换为int/// <summary>/// 将object转换为int,若转换失败,则返回0。不抛出异常。  /// </summary>/// <param name="str"></param>/// <returns></returns>public static int ParseToInt(this object str){try{return Convert.ToInt32(str);}catch{return 0;}}/// <summary>/// 将object转换为int,若转换失败,则返回指定值。不抛出异常。 /// null返回默认值/// </summary>/// <param name="str"></param>/// <param name="defaultValue"></param>/// <returns></returns>public static int ParseToInt(this object str, int defaultValue){if (str == null){return defaultValue;}try{return Convert.ToInt32(str);}catch{return defaultValue;}}#endregion#region 转换为short/// <summary>/// 将object转换为short,若转换失败,则返回0。不抛出异常。  /// </summary>/// <param name="str"></param>/// <returns></returns>public static short ParseToShort(this object obj){try{return short.Parse(obj.ToString());}catch{return 0;}}/// <summary>/// 将object转换为short,若转换失败,则返回指定值。不抛出异常。  /// </summary>/// <param name="str"></param>/// <returns></returns>public static short ParseToShort(this object str, short defaultValue){try{return short.Parse(str.ToString());}catch{return defaultValue;}}#endregion#region 转换为demical/// <summary>/// 将object转换为demical,若转换失败,则返回指定值。不抛出异常。  /// </summary>/// <param name="str"></param>/// <returns></returns>public static decimal ParseToDecimal(this object str, decimal defaultValue){try{return decimal.Parse(str.ToString());}catch{return defaultValue;}}/// <summary>/// 将object转换为demical,若转换失败,则返回0。不抛出异常。  /// </summary>/// <param name="str"></param>/// <returns></returns>public static decimal ParseToDecimal(this object str){try{return decimal.Parse(str.ToString());}catch{return 0;}}#endregion#region 转化为bool/// <summary>/// 将object转换为bool,若转换失败,则返回false。不抛出异常。  /// </summary>/// <param name="str"></param>/// <returns></returns>public static bool ParseToBool(this object str){try{return bool.Parse(str.ToString());}catch{return false;}}/// <summary>/// 将object转换为bool,若转换失败,则返回指定值。不抛出异常。  /// </summary>/// <param name="str"></param>/// <returns></returns>public static bool ParseToBool(this object str, bool result){try{return bool.Parse(str.ToString());}catch{return result;}}#endregion#region 转换为float/// <summary>/// 将object转换为float,若转换失败,则返回0。不抛出异常。  /// </summary>/// <param name="str"></param>/// <returns></returns>public static float ParseToFloat(this object str){try{return float.Parse(str.ToString());}catch{return 0;}}/// <summary>/// 将object转换为float,若转换失败,则返回指定值。不抛出异常。  /// </summary>/// <param name="str"></param>/// <returns></returns>public static float ParseToFloat(this object str, float result){try{return float.Parse(str.ToString());}catch{return result;}}#endregion#region 转换为Guid/// <summary>/// 将string转换为Guid,若转换失败,则返回Guid.Empty。不抛出异常。  /// </summary>/// <param name="str"></param>/// <returns></returns>public static Guid ParseToGuid(this string str){try{return new Guid(str);}catch{return Guid.Empty;}}#endregion#region 转换为DateTime/// <summary>/// 将string转换为DateTime,若转换失败,则返回日期最小值。不抛出异常。  /// </summary>/// <param name="str"></param>/// <returns></returns>public static DateTime ParseToDateTime(this string str){try{if (string.IsNullOrWhiteSpace(str)){return DateTime.MinValue;}if (str.Contains("-") || str.Contains("/")){return DateTime.Parse(str);}else{int length = str.Length;switch (length){case 4:return DateTime.ParseExact(str, "yyyy", System.Globalization.CultureInfo.CurrentCulture);case 6:return DateTime.ParseExact(str, "yyyyMM", System.Globalization.CultureInfo.CurrentCulture);case 8:return DateTime.ParseExact(str, "yyyyMMdd", System.Globalization.CultureInfo.CurrentCulture);case 10:return DateTime.ParseExact(str, "yyyyMMddHH", System.Globalization.CultureInfo.CurrentCulture);case 12:return DateTime.ParseExact(str, "yyyyMMddHHmm", System.Globalization.CultureInfo.CurrentCulture);case 14:return DateTime.ParseExact(str, "yyyyMMddHHmmss", System.Globalization.CultureInfo.CurrentCulture);default:return DateTime.ParseExact(str, "yyyyMMddHHmmss", System.Globalization.CultureInfo.CurrentCulture);}}}catch{return DateTime.MinValue;}}/// <summary>/// 将string转换为DateTime,若转换失败,则返回默认值。  /// </summary>/// <param name="str"></param>/// <param name="defaultValue"></param>/// <returns></returns>public static DateTime ParseToDateTime(this string str, DateTime? defaultValue){try{if (string.IsNullOrWhiteSpace(str)){return defaultValue.GetValueOrDefault();}if (str.Contains("-") || str.Contains("/")){return DateTime.Parse(str);}else{int length = str.Length;switch (length){case 4:return DateTime.ParseExact(str, "yyyy", System.Globalization.CultureInfo.CurrentCulture);case 6:return DateTime.ParseExact(str, "yyyyMM", System.Globalization.CultureInfo.CurrentCulture);case 8:return DateTime.ParseExact(str, "yyyyMMdd", System.Globalization.CultureInfo.CurrentCulture);case 10:return DateTime.ParseExact(str, "yyyyMMddHH", System.Globalization.CultureInfo.CurrentCulture);case 12:return DateTime.ParseExact(str, "yyyyMMddHHmm", System.Globalization.CultureInfo.CurrentCulture);case 14:return DateTime.ParseExact(str, "yyyyMMddHHmmss", System.Globalization.CultureInfo.CurrentCulture);default:return DateTime.ParseExact(str, "yyyyMMddHHmmss", System.Globalization.CultureInfo.CurrentCulture);}}}catch{return defaultValue.GetValueOrDefault();}}#endregion#region 转换为string/// <summary>/// 将object转换为string,若转换失败,则返回""。不抛出异常。  /// </summary>/// <param name="str"></param>/// <returns></returns>public static string ParseToString(this object obj){try{if (obj == null){return string.Empty;}else{return obj.ToString();}}catch{return string.Empty;}}public static string ParseToStrings<T>(this object obj){try{var list = obj as IEnumerable<T>;if (list != null){return string.Join(",", list);}else{return obj.ToString();}}catch{return string.Empty;}}#endregion#region 转换为double/// <summary>/// 将object转换为double,若转换失败,则返回0。不抛出异常。  /// </summary>/// <param name="obj"></param>/// <returns></returns>public static double ParseToDouble(this object obj){try{return double.Parse(obj.ToString());}catch{return 0;}}/// <summary>/// 将object转换为double,若转换失败,则返回指定值。不抛出异常。  /// </summary>/// <param name="str"></param>/// <param name="defaultValue"></param>/// <returns></returns>public static double ParseToDouble(this object str, double defaultValue){try{return double.Parse(str.ToString());}catch{return defaultValue;}}#endregion}
  • 添加实体类UserEntity,要跟Excel的列名一致
 public class UserEntity{[Description("名称")]public string Name { get; set; }[Description("年龄")]public string Age { get; set; }[Description("性别")]public string Gender { get; set; }[Description("手机号")]public string Tel { get; set; }}
  • Excel模板
    !https://img-blog.csdnimg.cn/5a79394d772c4c9ab0d28972f09f2f67.png)
  • 实现效果
    在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/73917.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Jenkins 监控dist.zip文件内容发生变化 触发自动部署

为Jenkins添加plugin http://xx:xx/manage 创建一个任务 构建触发器 每3分钟扫描一次&#xff0c;发现指定文件build.zip文件的MD5发生变化后 触发任务

vscode搭建java开发环境

一、配置extensions环境变量VSCODE_EXTENSIONS 该环境变量路径下的存放安装组件&#xff1a; 二、setting配置文件 {"java.jdt.ls.java.home": "e:\\software\\jdk\\jdk17",// java运行环境"java.configuration.runtimes": [{"name":…

CMake语法复习

前言 此文总结了库的制作和一些CMake常用的一些语法。 一&#xff1a;创建静态库和动态库 静态库的生成和使用 动态库的生成和使用 二&#xff1a;使用CMake来生成Makefile&#xff0c;生成可执行文件 顶层目录下的CMakeLists.txt project(HELLO) add_subdirectory(libhell…

零基础自学:2023 年的今天,请谨慎进入网络安全行业

前言 2023 年的今天&#xff0c;慎重进入网安行业吧&#xff0c;目前来说信息安全方向的就业对于学历的容忍度比软件开发要大得多&#xff0c;还有很多高中被挖过来的大佬。 理由很简单&#xff0c;目前来说&#xff0c;信息安全的圈子人少&#xff0c;985、211 院校很多都才…

Docker碎碎念

docker和虚拟机的区别 虚拟机&#xff08;VM&#xff09;是通过在物理硬件上运行一个完整的操作系统来实现的。 每个虚拟机都有自己的内核、设备驱动程序和用户空间&#xff0c;它们是相互独立且完全隔离的。 虚拟机可以在不同的物理服务器之间迁移&#xff0c;因为它们是以整…

【刷题笔记8.17】LeetCode:最长公共前缀

LeetCode&#xff1a;最长公共前缀 &#xff08;一&#xff09;题目描述 编写一个函数来查找字符串数组中的最长公共前缀。 如果不存在公共前缀&#xff0c;返回空字符串 “”。 &#xff08;二&#xff09;分析 纵向扫描时&#xff0c;从前往后遍历所有字符串的每一列&am…

港科夜闻|香港科大校长叶玉如教授、香港科大(广州)校长倪明选教授等两校领导共同出席香港科大(广州)首批本科新生见面会...

关注并星标 每周阅读港科夜闻 建立新视野 开启新思维 1、香港科大校长叶玉如教授、香港科大(广州)校长倪明选教授等两校领导共同出席香港科大(广州)首批本科新生见面会。8月16日&#xff0c;香港科大(广州)首批本科新生参加了一次具有特殊意义的见面会。香港科大、香港科大(广州…

使用拦截器+Redis实现接口幂等

文章目录 使用拦截器Redis实现接口幂等1.思路分析2.具体实现2.1 创建redis工具类2.2 自定义幂等注解2.2 自定义幂等拦截器2.3 注入拦截器到容器 3.测试 使用拦截器Redis实现接口幂等 1.思路分析 接口幂等有很多种实现方式&#xff0c;拦截器/AOPRedis&#xff0c;拦截器/AOP本…

NLP的tokenization

GPT3.5的tokenization流程如上图所示&#xff0c;以下是chatGPT对BPE算法的解释&#xff1a; BPE&#xff08;Byte Pair Encoding&#xff09;编码算法是一种基于统计的无监督分词方法&#xff0c;用于将文本分解为子词单元。它的原理如下&#xff1a; 1. 初始化&#xff1a;将…

Docker vs. Kubernetes:选择合适的场景

在决定使用 Docker 还是 Kubernetes 之前&#xff0c;让我们看看一些实际的场景&#xff0c;以便更好地理解它们的适用性。 使用 Docker 的场景 假设您正在开发一个微服务应用程序&#xff0c;其中每个微服务都需要一些特定的依赖项和环境。在这种情况下&#xff0c;Docker 是一…

CSS 背景属性

前言 背景属性 属性说明background-color背景颜色background-image背景图background-repeat背景图平铺方式background-position背景图位置background-size背景图缩放background-attachment背景图固定background背景复合属性 背景颜色 可以使用background-color属性来设置背景…

opencv直方图与模板匹配

import cv2 #opencv读取的格式是BGR import numpy as np import matplotlib.pyplot as plt#Matplotlib是RGB %matplotlib inline def cv_show(img,name):cv2.imshow(name,img)cv2.waitKey()cv2.destroyAllWindows() 直方图 cv2.calcHist(images,channels,mask,histSize,ran…