第一步:创建项目
第二步:安装依赖项EPPlus.Core
第三步:添加XlsxController控制器
第四步:编写代码
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using OfficeOpenXml;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace ExcelTest.Controllers
{
public class XlsxController : Controller
{
private IHostingEnvironment _hostingEnvironment;
public XlsxController(IHostingEnvironment hostingEnvironment)
{
_hostingEnvironment = hostingEnvironment;
}
public IActionResult Export()
{
string sWebRootFolder = _hostingEnvironment.WebRootPath;
string sFileName = "部落.xlsx";
FileInfo file = new FileInfo(Path.Combine(sWebRootFolder, sFileName));
file.Delete();
using (ExcelPackage package = new ExcelPackage(file))
{
// 添加worksheet
ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("部落");
//添加头
worksheet.Cells[1, 1].Value = "ID";
worksheet.Cells[1, 2].Value = "Name";
worksheet.Cells[1, 3].Value = "Url";
//添加值
worksheet.Cells["A2"].Value = 1000;
worksheet.Cells["B2"].Value = "For丨丶";
worksheet.Cells["C2"].Value = "网页链接";
worksheet.Cells["A3"].Value = 1001;
worksheet.Cells["B3"].Value = "For丨丶Tomorrow";
worksheet.Cells["C3"].Value = "网页链接";
worksheet.Cells["C3"].Style.Font.Bold = true;
package.Save();
}
return File(sFileName, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", sFileName);
}
}
}
完成
本文介绍如何使用EPPlus.Core库在ASP.NET Core应用中实现Excel文件的创建与导出功能。通过实例演示了创建Excel文件、添加工作表、设置单元格值等操作。
2488

被折叠的 条评论
为什么被折叠?



