以前 Asp.Net MVC 有这个第三方库,可以轻松上传和读取名为 Excel Data Reader 的 Excel 文件。我们不需要将文件保存在本地磁盘上,这很好,因为我的应用程序需要在 Azure 上运行。
但是,我们现在正在将此功能移植到 asp.net core 2 中,从搜索结果来看,这似乎是不可能的。有人知道任何允许我这样做的图书馆吗?请注意,我不是在寻找从磁盘读取的解决方案。我想上传一个excel文件并直接从流中读取数据。
以前 Asp.Net MVC 有这个第三方库,可以轻松上传和读取名为 Excel Data Reader 的 Excel 文件。我们不需要将文件保存在本地磁盘上,这很好,因为我的应用程序需要在 Azure 上运行。
但是,我们现在正在将此功能移植到 asp.net core 2 中,从搜索结果来看,这似乎是不可能的。有人知道任何允许我这样做的图书馆吗?请注意,我不是在寻找从磁盘读取的解决方案。我想上传一个excel文件并直接从流中读取数据。
我可以通过此代码在“Asp .Net Core”中读取 Excel 文件。
使用EPPlus.Core导入和导出数据。
[HttpPost]
public IActionResult ReadExcelFileAsync(IFormFile file)
{
if (file == null || file.Length == 0)
return Content("File Not Selected");
string fileExtension = Path.GetExtension(file.FileName);
if (fileExtension != ".xls" && fileExtension != ".xlsx")
return Content("File Not Selected");
var rootFolder = @"D:\Files";
var fileName = file.FileName;
var filePath = Path.Combine(rootFolder, fileName);
var fileLocation = new FileInfo(filePath);
using (var fileStream = new FileStream(filePath, FileMode.Create))
{
await file.CopyToAsync(fileStream);
}
if (file.Length <= 0)
return BadRequest(GlobalValidationMessage.FileNotFound);
using (ExcelPackage package = new ExcelPackage(fileLocation))
{
ExcelWorksheet workSheet = package.Workbook.Worksheets["Table1"];
//var workSheet = package.Workbook.Worksheets.First();
int totalRows = workSheet.Dimension.Rows;
var DataList = new List<Customers>();
for (int i = 2; i <= totalRows; i++)
{
DataList.Add(new Customers
{
CustomerName = workSheet.Cells[i, 1].Value.ToString(),
CustomerEmail = workSheet.Cells[i, 2].Value.ToString(),
CustomerCountry = workSheet.Cells[i, 3].Value.ToString()
});
}
_db.Customers.AddRange(customerList);
_db.SaveChanges();
}
return Ok();
}
如果我们谈论的是 Razor Pages,这是我今天测试的一个简单示例。
环境:.NET Core 3.1, VS 2019
一个简单的类
public class UserModel
{
public string Name { get; set; }
public string City { get; set; }
}
索引.cshtml.cs
usings..
using ExcelDataReader;
public void OnPost(IFormFile file)
{
List<UserModel> users = new List<UserModel>();
System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
using (var stream = new MemoryStream())
{
file.CopyTo(stream);
stream.Position = 0;
using (var reader = ExcelReaderFactory.CreateReader(stream))
{
while (reader.Read()) //Each row of the file
{
users.Add(new UserModel { Name = reader.GetValue(0).ToString(), City = reader.GetValue(1).ToString()});
}
}
}
//users // you got the values here
}
在视图中标记
<form id="form1" method="post" enctype="multipart/form-data">
<div class="text-center">
<input type="file" id="file1" name="file" />
</div>
<script>
document.getElementById('file1').onchange = function () {
document.getElementById('form1').submit();
};
</script>
您需要ExcelDataReader nuget 包,我使用的是3.6.0
版本
我在下面为 ASP.NET Core 尝试了这段代码(不使用库),它工作正常:
public ActionResult OnPostUpload(List<IFormFile> files)
{
try
{
var file = files.FirstOrDefault();
var inputstream = file.OpenReadStream();
XSSFWorkbook workbook = new XSSFWorkbook(stream);
var FIRST_ROW_NUMBER = {{firstRowWithValue}};
ISheet sheet = workbook.GetSheetAt(0);
// Example: var firstCellRow = (int)sheet.GetRow(0).GetCell(0).NumericCellValue;
for (int rowIdx = 2; rowIdx <= sheet.LastRowNum; rowIdx++)
{
IRow currentRow = sheet.GetRow(rowIdx);
if (currentRow == null || currentRow.Cells == null || currentRow.Cells.Count() < FIRST_ROW_NUMBER) break;
var df = new DataFormatter();
for (int cellNumber = {{firstCellWithValue}}; cellNumber < {{lastCellWithValue}}; cellNumber++)
{
//business logic & saving data to DB
}
}
}
catch(Exception ex)
{
throw new FileFormatException($"Error on file processing - {ex.Message}");
}
}
最新版本的 ExcelDataReader 支持 netstandard2.0,因此适用于 ASP.NET Core 2。它还针对 netstandard1.3,因此也适用于 ASP.NET Core 1.x。
(不确定您搜索的内容是不可能的,但这显然是错误的)
首先上传你的excel文件,使用asp.net core 3.1读取excel文件记录。
using System;
using Microsoft.AspNetCore.Mvc;
using ExcelFileRead.Models;
using Microsoft.AspNetCore.Hosting;
using System.IO;
using OfficeOpenXml;
using System.Linq;
namespace ExcelFileRead.Controllers
{
public class HomeController : Controller
{
private readonly IHostingEnvironment _hostingEnvironment;
public HomeController(IHostingEnvironment hostingEnvironment)
{
_hostingEnvironment = hostingEnvironment;
}
public ActionResult File()
{
FileUploadViewModel model = new FileUploadViewModel();
return View(model);
}
[HttpPost]
public ActionResult File(FileUploadViewModel model)
{
string rootFolder = _hostingEnvironment.WebRootPath;
string fileName = Guid.NewGuid().ToString() + model.XlsFile.FileName;
FileInfo file = new FileInfo(Path.Combine(rootFolder, fileName));
using (var stream = new MemoryStream())
{
model.XlsFile.CopyToAsync(stream);
using (var package = new ExcelPackage(stream))
{
package.SaveAs(file);
}
}
using (ExcelPackage package = new ExcelPackage(file))
{
ExcelWorksheet worksheet = package.Workbook.Worksheets.FirstOrDefault();
if (worksheet == null)
{
//return or alert message here
}
else
{
var rowCount = worksheet.Dimension.Rows;
for (int row = 2; row <= rowCount; row++)
{
model.StaffInfoViewModel.StaffList.Add(new StaffInfoViewModel
{
FirstName = (worksheet.Cells[row, 1].Value ?? string.Empty).ToString().Trim(),
LastName = (worksheet.Cells[row, 2].Value ?? string.Empty).ToString().Trim(),
Email = (worksheet.Cells[row, 3].Value ?? string.Empty).ToString().Trim(),
});
}
}
}
return View(model);
}
}
}
了解更多详情(一步一步)