gpt4 book ai didi

c# - 使用 epplus 创建 .xlsm 文件

转载 作者:行者123 更新时间:2023-12-04 20:11:37 28 4
gpt4 key购买 nike

我试图让一个网站导出一个 .xlsm 文件,但我似乎找不到任何有帮助的东西。这是我用来测试构建 .xlsx 文件(有效)的简单示例。

@using OfficeOpenXml;
<html>
<body>
<div id="page-wrapper">
@{
// Change file extension to xlsm to test
string fileExtension = "xlsm";
ExcelPackage p = new ExcelPackage();
p.Workbook.Worksheets.Add("Worksheet Name");
int LatestWorksheetNumber = p.Workbook.Worksheets.Count;
ExcelWorksheet ws = p.Workbook.Worksheets[LatestWorksheetNumber];

ws.Cells[1, 1].Value = "Test";

//Generate A File
Byte[] bin = p.GetAsByteArray();
string filename = "filename";
try
{
//Download the file as an attachment
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.Cookies.Clear();

string ContentType = "";
if (fileExtension == "xlsx")
{
ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
}
else
{
ContentType = "application/vnd.ms-excel.sheet.macroEnabled.12";
}
Response.GetType();
Response.ContentType = ContentType;
Response.AddHeader("content-disposition", "attachment; filename=" + filename + "." + fileExtension);
Response.BinaryWrite(bin);
Response.End();
<p>File Created</p>
}
catch (Exception e)
{
<p>@e.Message</p>
}

}
</div>
</body>
</html>

将文件扩展名更改为 .xlsm 后,会生成文件,但是当我尝试在 Excel 中打开文件时,我收到一条错误消息,指出扩展名不正确。我认为我唯一需要更改的是内容类型标题,但这显然不是问题。我还缺什么???任何指导将不胜感激!

最佳答案

Xiaoy312 解决了这个问题!添加 p.Workbook.CreateVBAProject();之前 Byte[] bin = p.GetAsByteArray();解决了我的问题!其他一切都保持不变,但 Excel 现在将实际打开文件!这是我为遇到相同问题的任何人提供的最终代码:

@using OfficeOpenXml;
<html>
<body>
<div id="page-wrapper">
@{
// Change file extension to xlsm to test
string FileExtension = "xlsm";
ExcelPackage p = new ExcelPackage();
p.Workbook.Worksheets.Add("Worksheet Name");
int LatestWorksheetNumber = p.Workbook.Worksheets.Count;
ExcelWorksheet ws = p.Workbook.Worksheets[LatestWorksheetNumber];
ws.Cells[1, 1].Value = "Test";

p.Workbook.CreateVBAProject();

//Generate A File
Byte[] bin = p.GetAsByteArray();
string filename = "filename";
try
{
//Download the file as an attachment
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.Cookies.Clear();

string ContentType = "";
if (FileExtension == "xlsx")
{
ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
}
else
{
ContentType = "application/vnd.ms-excel.sheet.macroEnabled.12";
}
Response.GetType();
Response.ContentType = ContentType;
Response.AddHeader("content-disposition", "attachment; filename=" + filename + "." + FileExtension);
Response.BinaryWrite(bin);
Response.End();
<p>File Created</p>
}
catch (Exception e)
{
<p>@e.Message</p>
}
}
</div>
</body>
</html>

关于c# - 使用 epplus 创建 .xlsm 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41250111/

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