zoukankan      html  css  js  c++  java
  • .Net Core Excel导出和导入

    项目中Excel导入和导出算是常用的功能,以下记录和总结:

    1.Excel导入
    导入功能从之前的附件上传功能( https://www.cnblogs.com/ywkcode/p/11703523.html)进行了修改,原理是通过CopyToAsync生成Excel文件,通过EPPlus.Core操作Excel文件,读取文件内容,解析成集合进行业务操作,使用前需要引用:EPPlus.Core
     
    前端页面:
     1 <form class="layui-form" id="uploadForm">  
     2    <input type="file" name="file" multiple value="选择" onchange="doUpload()" id="ajaxfile"  />
     3 </form>
     4 <script type="text/javascript">
     5   function doUpload() {
     6               var formData = new FormData($("#uploadForm")[0]);
     7               var  url = '@Url.Action("ImportEquip", "FileUpload")';
     8               
     9               $.ajax({
    10                 url: url,
    11                 type: 'POST',
    12                 data: formData,
    13                 async: false,
    14                 cache: false,
    15                 contentType: false,
    16                 processData: false,
    17                 success: function (returndata) {
    18                     layer.msg('上传成功!');
    19                     location.reload();
    20                 },
    21                 error: function (returndata) {
    22                     console.log(returndata);
    23                     layer.msg('上传失败!');
    24                 }
    25             });
    26         }
    27 </script>

    后端页面:

     1   private readonly IHostingEnvironment _hostingEnvironment;
     2         private readonly GradeSettingsService _service;
     3         public FileUploadController(IHostingEnvironment hostingEnvironment,  GradeSettingsService  service)
     4         {
     5             _hostingEnvironment = hostingEnvironment;
     6             _service = service;
     7         }        
     8 
     9         [AllowAnonymous]
    10         [HttpPost]
    11         public async Task<IActionResult> ImportEquip()
    12         {
    13             //获取Form提交的文件
    14             var files = Request.Form.Files;
    15             long size = files.Sum(f => f.Length);
    16             string webRootPath = _hostingEnvironment.WebRootPath; //物理路径
    17             string contentRootPath = _hostingEnvironment.ContentRootPath;
    18             string showfilePath = "";
    19             bool IsSuccess = true;
    20             foreach (var formFile in files)
    21             {
    22                 if (formFile.Length > 0)
    23                 {
    24                     int count = formFile.FileName.Split('.').Length;
    25                     string fileExt = formFile.FileName.Split('.')[count - 1]; //文件扩展名,不含“.”
    26                     long fileSize = formFile.Length; //获得文件大小,以字节为单位
    27                     string newFileName = System.Guid.NewGuid().ToString() + "." + fileExt;  //随机生成新的文件名
    28                     #region 文件夹不存在则创建
    29                     var filePath = webRootPath + "/upload";
    30                     if (!Directory.Exists(filePath))
    31                     {
    32                         Directory.CreateDirectory(filePath);
    33                     }
    34                     #endregion
    35                     #region 文件不存在则新建
    36                     filePath = webRootPath + "/upload/" + newFileName;
    37                     showfilePath = "upload/" + newFileName;
    38                     FileHelper.CreateFile(filePath);
    39                     #endregion
    40                     //把上传的图片复制到指定的文件中
    41                     using (var stream = new FileStream(filePath, FileMode.Create))
    42                     {
    43                         await formFile.CopyToAsync(stream);
    44                     }
    45                     FileInfo file = new FileInfo(filePath);
    46                     using (ExcelPackage package = new ExcelPackage(file))
    47                     {
    48                         StringBuilder sb = new StringBuilder();
    49                         try
    50                         {
    51                             ExcelWorksheet worksheet = package.Workbook.Worksheets[1];
    52                             List<Import_Equip> resultlist =  worksheet.ConvertSheetToObjects<Import_Equip>().ToList();
    53                             _service.ImportEquip(resultlist);
    54                         }
    55                         catch (Exception ex)
    56                         {
    57                             IsSuccess = false;
    58                         }
    59                     }
    60                 }
    61             }
    62             return Ok(new { count = files.Count, savepath = showfilePath, status =  IsSuccess });
    63         }

    附Epplus扩展类:

     1 public static class EppLusExtensions
     2     {
     3         /// <summary>
     4         /// 获取标签对应excel的Index
     5         /// </summary>
     6         /// <param name="ws"></param>
     7         /// <param name="columnName"></param>
     8         /// <returns></returns>
     9         /// <exception cref="ArgumentNullException"></exception>
    10         public static int GetColumnByName(this OfficeOpenXml.ExcelWorksheet ws, string  columnName)
    11         {
    12             if (ws == null) throw new ArgumentNullException(nameof(ws));
    13             return ws.Cells["1:1"].First(c => c.Value.ToString() ==  columnName).Start.Column;
    14         }
    15         /// <summary>
    16         /// 扩展方法
    17         /// </summary>
    18         /// <param name="worksheet"></param>
    19         /// <typeparam name="T"></typeparam>
    20         /// <returns></returns>
    21         public static IEnumerable<T> ConvertSheetToObjects<T>(this  OfficeOpenXml.ExcelWorksheet worksheet) where T : new()
    22         {
    23             Func<CustomAttributeData, bool> columnOnly = y => y.AttributeType ==  typeof(ExcelColumn);
    24             var columns = typeof(T)
    25                 .GetProperties()
    26                 .Where(x => x.CustomAttributes.Any(columnOnly))
    27                 .Select(p => new
    28                 {
    29                     Property = p,
    30                     Column = p.GetCustomAttributes<ExcelColumn>().First().ColumnName
    31                 }).ToList();
    32             var rows = worksheet.Cells
    33                 .Select(cell => cell.Start.Row)
    34                 .Distinct()
    35                 .OrderBy(x => x);
    36             var collection = rows.Skip(1)
    37                 .Select(row =>
    38                 {
    39                     var tnew = new T();
    40                     columns.ForEach(col =>
    41                     {
    42                         var val = worksheet.Cells[row, GetColumnByName(worksheet,  col.Column)];
    43                         if (val.Value == null)
    44                         {
    45                             col.Property.SetValue(tnew, null);
    46                             return;
    47                         }
    48                       
    49                         if (col.Property.PropertyType == typeof(int))
    50                         {
    51                             col.Property.SetValue(tnew, val.GetValue<int>());
    52                             return;
    53                         }
    54                         
    55                         if (col.Property.PropertyType == typeof(double))
    56                         {
    57                             col.Property.SetValue(tnew, val.GetValue<double>());
    58                             return;
    59                         }
    60                      
    61                         if (col.Property.PropertyType == typeof(DateTime?))
    62                         {
    63                             col.Property.SetValue(tnew, val.GetValue<DateTime?>());
    64                             return;
    65                         }
    66                      
    67                         if (col.Property.PropertyType == typeof(DateTime))
    68                         {
    69                             col.Property.SetValue(tnew, val.GetValue<DateTime>());
    70                             return;
    71                         }
    72                       
    73                         if (col.Property.PropertyType == typeof(bool))
    74                         {
    75                             col.Property.SetValue(tnew, val.GetValue<bool>());
    76                             return;
    77                         }
    78                         col.Property.SetValue(tnew, val.GetValue<string>());
    79                     });
    80                     return tnew;
    81                 });
    82             return collection;
    83         }
    84     }

    2.Excel导出

    前端:

    1   <a asp-action="ExportSun"  class="layui-btn layui-btn-sm" id="btnexcel">导出</a>

    后端:

     1    public IActionResult ExportSun()
     2         {
     3             string sWebRootFolder = _hostingEnvironment.WebRootPath;
     4             //获取数据集
     5             var datalist = _service.GetExportSunData();
     6             string sFileName = $"{Guid.NewGuid()}.xlsx";
     7             FileInfo file = new FileInfo(Path.Combine(sWebRootFolder, sFileName));   //Path.Combine把多个字符串组成一个路径
     8             using (ExcelPackage package = new ExcelPackage(file))   //ExcelPackage 操作excel的主要对象
     9             {
    10                 // 添加worksheet
    11                 ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("aspnetcore");
    12                 //添加头
    13                 worksheet.Cells[1, 1].Value = "班级ID";
    14                 worksheet.Cells[1, 2].Value = "学校名称";
    15                 worksheet.Cells[1, 3].Value = "年级类型"; 
    16                  
    17                 int Count = 2;
    18                 foreach (var model in datalist)
    19                 {
    20                     worksheet.Cells["A" + Count.ToString()].Value = model.ClassID;
    21                     worksheet.Cells["B" + Count.ToString()].Value = model.DeptName;
    22                     worksheet.Cells["C" + Count.ToString()].Value = model.GradeTypeName;
    23                     
    24                     Count++;
    25                 }
    26                 package.Save();
    27             }
    28             return File(sFileName,  "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
    29         }
     
     
    以上仅用于学习和记录
  • 相关阅读:
    【python】变量定义及全局局部变量
    【python】重要的内置函数
    【python】迭代器iterator
    Java序列化与反序列化
    java中的IO操作总结
    Java中List Set Map 是否有序等总结
    java.lang.Class.getDeclaredMethod()方法详解
    一个servlet处理多个请求(使用Method的反射机制)
    java类的访问权限
    java中的基本数据类型存放位置
  • 原文地址:https://www.cnblogs.com/ywkcode/p/12890201.html
Copyright © 2011-2022 走看看