第一步:创建项目
第二步:安装依赖项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);
}
}
}
完成