导入Excel表格的插件叫做EPPlus
只需要在NuGet引用,然后如数以下代码:
using Microsoft.AspNetCore.Http; using OfficeOpenXml; using System.Data; using System.IO; using System.Linq; namespace Import { public class EPPlusHelper { /// <summary> /// Exlce转datatable /// </summary> /// <param name="file"></param> /// <returns></returns> public static DataTable ExcelTransformationDataTable(IFormFile file) { using (var memoryStream = new MemoryStream()) { DataTable dt = null; file.CopyToAsync(memoryStream).ConfigureAwait(false); using (var package = new ExcelPackage(memoryStream)) { ExcelWorkbook workbook = package.Workbook; if (workbook != null) { if (workbook.Worksheets.Count > 0) { ExcelWorksheet worksheet = workbook.Worksheets.First(); dt = ExlceToTable(worksheet); } } } return dt; } } private static DataTable? ExlceToTable(ExcelWorksheet worksheet) { //获取表格有多少行 int rows = worksheet.Dimension.End.Row; //获取表格有多少列 int cols = worksheet.Dimension.End.Column; //创建一个datatable DataTable data = new DataTable(worksheet.Name); //创建一行 DataRow row = null; //循环行数 for (int i = 1; i <= rows; i++) { if (i > 1) { row = data.Rows.Add(); } for (int j = 1; j <= cols; j++) { //把第一行设置为DataTable的标题 if (i == 1) { data.Columns.Add(worksheet.Cells[i, j].Value?.ToString()); } else { row[j - 1] = worksheet.Cells[i, j].Value?.ToString(); } } } return data; } } }
最后需要在appsettings.json中输入以下配置信息:
{ "EPPlus": { "ExcelPackage": { "LicenseContext": "Commercial" //The license context used } }, "AllowedHosts": "*" }