gpt4 book ai didi

c# - 使用 EPPlus 创建后下载 Excel 文件

转载 作者:行者123 更新时间:2023-12-01 16:45:29 26 4
gpt4 key购买 nike

我正在使用 EPPlus 库生成一个 Excel 文件,我已成功将其保存在服务器上的文件夹中。

如何将此文件下载到我的本地计算机?

这是我的代码

public void CreateExcelFirstTemplate()
{
var fileName = "C:\ExcelDataTest\ExcellData.xlsx";
var file = new FileInfo(fileName);
using (var package = new OfficeOpenXml.ExcelPackage(file))
{
var worksheet = package.Workbook.Worksheets.FirstOrDefault(x => x.Name == "Attempts");
worksheet = package.Workbook.Worksheets.Add("Assessment Attempts");
worksheet.Row(1).Height = 20;

worksheet.TabColor = Color.Gold;
worksheet.DefaultRowHeight = 12;
worksheet.Row(1).Height = 20;

worksheet.Cells[1, 1].Value = "Employee Number";
worksheet.Cells[1, 2].Value = "Course Code";

var cells = worksheet.Cells["A1:J1"];
var rowCounter = 2;
foreach (var v in userAssessmentsData)
{
worksheet.Cells[rowCounter, 1].Value = v.CompanyNumber;
worksheet.Cells[rowCounter, 2].Value = v.CourseCode;

rowCounter++;
}
worksheet.Column(1).AutoFit();
worksheet.Column(2).AutoFit();


package.Workbook.Properties.Title = "Attempts";
package.Save();
}
}

最佳答案

如果您在每次请求时生成此文件,则无需将其保存在服务器上:

public void CreateExcelFirstTemplate()
{
var fileName = "ExcellData.xlsx";
using (var package = new OfficeOpenXml.ExcelPackage(fileName))
{
var worksheet = package.Workbook.Worksheets.FirstOrDefault(x => x.Name == "Attempts");
worksheet = package.Workbook.Worksheets.Add("Assessment Attempts");
worksheet.Row(1).Height = 20;

worksheet.TabColor = Color.Gold;
worksheet.DefaultRowHeight = 12;
worksheet.Row(1).Height = 20;

worksheet.Cells[1, 1].Value = "Employee Number";
worksheet.Cells[1, 2].Value = "Course Code";

var cells = worksheet.Cells["A1:J1"];
var rowCounter = 2;
foreach (var v in userAssessmentsData)
{
worksheet.Cells[rowCounter, 1].Value = v.CompanyNumber;
worksheet.Cells[rowCounter, 2].Value = v.CourseCode;

rowCounter++;
}
worksheet.Column(1).AutoFit();
worksheet.Column(2).AutoFit();


package.Workbook.Properties.Title = "Attempts";
this.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
this.Response.AddHeader(
"content-disposition",
string.Format("attachment; filename={0}", "ExcellData.xlsx"));
this.Response.BinaryWrite(package.GetAsByteArray());
}
}

关于c# - 使用 EPPlus 创建后下载 Excel 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28048835/

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