gpt4 book ai didi

c# - 在asp.net core 1.0上读取一个excel文件

转载 作者:可可西里 更新时间:2023-11-01 07:58:00 24 4
gpt4 key购买 nike

您好,我正在尝试在我的 asp.net 项目中上传和读取 excel 文件,但我找到的所有文档都是针对 ASP MVC 5 的。我的目标是读取 Excel 工作表并将值传递给对象列表。

这是我的 Controller ,它用于将文件上传到我的 wwwroot/uploads

public class HomeController : Controller
{
private IHostingEnvironment _environment;

public HomeController(IHostingEnvironment environment)
{
_environment = environment;
}

public IActionResult index()
{
return View();
}



[HttpPost]
public async Task<IActionResult> Index(ICollection<IFormFile> files)
{
var uploads = Path.Combine(_environment.WebRootPath, "uploads");
foreach (var file in files)
{
if (file.Length > 0)
{
using (var fileStream = new FileStream(Path.Combine(uploads, file.FileName), FileMode.Create))
{
await file.CopyToAsync(fileStream);
}
}
}
return View();
}

最佳答案

打开package manager console在 Visual Studio 中输入:

PM> Install-Package EPPlus.Core

写文件就这么简单:

public void WriteExcel(string fileName)
{


FileInfo file = new FileInfo(fileName);
/// overwrite old file
if (file.Exists)
{
file.Delete();
file = new FileInfo(fileName);
}
using (ExcelPackage package = new ExcelPackage(file))
{
// add a new worksheet to the empty workbook
ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Employee");
worksheet.Cells["A1"].Value = "HELLO WORLD!!!";
package.Save();
}
}

此处有更多示例:http://www.talkingdotnet.com/import-export-xlsx-asp-net-core/

关于c# - 在asp.net core 1.0上读取一个excel文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40557935/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com