分享一个 ASP.NET Web Api 上传和读取 Excel的方案

作者 : admin 本文共3365个字,预计阅读时间需要9分钟 发布时间: 2024-06-9 共2人阅读

分享一个 ASP.NET Web Api 上传和读取 Excel的方案插图

前言

许多业务场景下需要处理和分析大量的数据,而 Excel 是业务人员常用的数据表格工具,因此,将 Excel 表格中内容上传并读取到网站,是一个很常见的功能,目前有许多成熟的开源或者商业的第三方库,比如 NPOI,EPPlus,Spire.Office for .NET 等等,今天分享一个使用 Magicodes.IE.Excel 上传和读取 Excel的方案,这是近年来一个比较受欢迎的开源的第三方库,下面我们用一个 Step By Step 例子来感受它的魅力。

Step By Step 步骤

  1. 安装 nuget 包

    Magicodes.IE.Excel
    Magicodes.IE.Core

  2. 创建一个 DTO 类

    using Magicodes.ExporterAndImporter.Core;
    
    namespace ExcelSample.BusinessEntities.Dtos
    {
    	public partial class ImportDto
    	{
    		/// 
    		/// ID
    		/// 
    		[ImporterHeader(Name ="ID")]
    		public string ItemGuid { get; set; }
    		
    		/// 
    		/// 巡检编号
    		/// 
    		[ImporterHeader(Name = "巡检编号")]
    		public string InspectionNumber { get; set; }
    		
    		/// 
    		/// 详细地址
    		/// 
    		[ImporterHeader(Name = "详细位置")]
    		public string FormattedAddress { get; set; }
    		
    		/// 
    		/// 开始日期
    		/// 
    		[ImporterHeader(Name = "开始日期")]
    		public string BeginDate { get; set; }
    		
    		/// 
    		/// 截止日期
    		/// 
    		[ImporterHeader(Name = "结束日期")]
    		public string EndDate { get; set; }
    		
    		/// 
    		/// 故障描述
    		/// 
    		[ImporterHeader(Name = "故障描述")]
    		public string FaultInfo { get; set; }
    		
    		/// 
    		/// 单位名称
    		/// 
    		[ImporterHeader(Name = "单位")]
    		public string CustomerName { get; set; }
    		
    		/// 
    		/// 维修说明
    		/// 
    		[ImporterHeader(Name = "维修说明")]
    		public string HandleMeasuresOther { get; set; }
    	}
    }	
    
  3. 写公共读取 Export 文件内容方法

    using Magicodes.ExporterAndImporter.Core;
    using Magicodes.ExporterAndImporter.Core.Extension;
    using Magicodes.ExporterAndImporter.Core.Models;
    using Magicodes.ExporterAndImporter.Excel;
    using System.Collections.Generic;
    using System.IO;
    using System.Threading.Tasks;
    
    namespace ExcelSample.Common
    {
    	/// 
    	/// excel 工具类
    	/// 
    	public static class ExportHelper
    	{
    		/// 
    		/// 通用导入 excel 文件
    		/// 
    		/// Excel 文件路径
    		public static async Task<ImportResult> ImportExcel(string filePath) where T : class, new()
    		{
    			IImporter importer = new ExcelImporter();
    			var result = await importer.Import(filePath);
    			return result;
    		}
    	}
    }
    
  4. 写上传 Excel 文件的业务方法

    public string UploadFile()
    {
    	HttpFileCollection files = HttpContext.Current.Request.Files;
    	if (files == null || files.Count == 0)
    	{
    		throw new Exception("没有上传文件");
    	}
    	
    	HttpPostedFile file = files[0];
    	string fileExt = Path.GetExtension(file.FileName);
    	if (fileExt != ".xlsx" && fileExt != ".xls")
    	{
    		throw new Exception("不是Excel文件");
    	}
    	
    	string dir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "ExcelImport");
    	if (!Directory.Exists(dir))
    	{
    		Directory.CreateDirectory(dir);
    	}
    	
    	string fileName = Path.GetFileNameWithoutExtension(file.FileName);
    	string fileSaveName = string.Format("{0}{1}.xlsx", fileName, DateTime.Now.ToFlowWaterDate()); 
    	string fileSavePath = Path.Combine(dir, fileSaveName);
    	_logger.Value.Info($"上传文件:[{fileSavePath}]");
    	file.SaveAs(fileSavePath);
    	return fileSavePath;
    }
    
  5. 写具体的读取 Excel 文件内容的业务方法

    public List ReadExcel(string filePath)
    {
    	var importData = ExportHelper.ImportExcel(filePath).Result;
    	var list = importData.Data.ToList();
    	if (list.HasData())
    	{
    		return list;
    	}
    	return null;
    }
    
  6. 在控制器中写 API 向外提供上传和读取 Excel 的接口

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net;
    using System.Text;
    using System.Threading.Tasks;
    using System.Web.Http;
    using ExcelSample.Contracts.IService;
    using ExcelSample.BusinessEntities.Dtos;
    namespace ExcelSample.WebAPI.Controllers.V1
    {
    	[Authorize]
    	[RoutePrefix("api/v1/excelSample")]
    	public partial class ExcelSampleController : BaseController
    	{
    		// ......
    		
    		[HttpPost]
    		[Route("uploadExcel")]
    		public IHttpActionResult UploadExcel()
    		{
    			// 1. 上传文件
    			string fileUpload = "";
    			try
    			{
    				fileUpload = UploadFile();
    			}
    			catch (Exception ex)
    			{
    				_log.Value.Error(ex, "上传文件失败!");
    				return BadRequest(ex.Message);
    			}
    
    			// 2. 读取数据
    			var list = ReadExcel(fileUpload);
    			if (list== null || list.Count == 0)
    			{
    				return BadRequest("文件没有数据或者数据格式不正确!");
    			}
    
    			// 3. 更新数据
    			// 存储数据到数据库中
    			
    			return Ok(Success(result));
    		}
    		
    		// ......
    	}
    }
    
  7. 运行项目并在 Postman 中进行测试

总结

Magicodes.IE.Excel 功能不比 NPOI 等其他第三方库逊色,使用也相对比较简单,只需几行代码就可以读取 Excel 文件的内容,不失为一个新的读写 Excel 方案的选择,大家有兴趣可以到 GitHub 下载其源码深入了解。

本站无任何商业行为
个人在线分享 » 分享一个 ASP.NET Web Api 上传和读取 Excel的方案
E-->