【发布时间】:2023-01-19 23:35:57
【问题描述】:
我正在尝试将一些数据从我的 blazor 页面下载到 excel 工作簿。 但是,当我尝试打开文件时,出现以下错误消息:
excel 无法打开文件,因为文件格式或扩展名无效
当我在记事本++中打开文件时,我看到一堆字母和符号,但没有有效数据。
这是我的代码:
public byte[] SaveSearchToExcel(List<EquipmentForm> EquipmentForms)
{
var wb = new XLWorkbook();
var ws = wb.Worksheets.Add("Search Results");
ws.Cell(1, 1).Value = "TLV Number";
ws.Cell(1, 2).Value = "Descirption";
for(int row = 0; row < EquipmentForms.Count; row++)
{
ws.Cell(row + 1, 1).Value = EquipmentForms[row].TLVNumber;
ws.Cell(row+1, 2).Value = EquipmentForms[row].Description;
}
MemoryStream XLSStream = new();
wb.SaveAs(XLSStream);
XLSStream.Position = 0;
return XLSStream.ToArray();
}
private async void SaveToExcel(){
var XLSStream= _saveToExcel.SaveSearchToExcel(EquipmentForms);
await js.InvokeVoidAsync("BlazorDownloadFile", "export.xlsx",Convert.ToBase64String(XLSStream));
}
function BlazorDownloadFile(filename, content) {
// thanks to Geral Barre : https://www.meziantou.net/generating-and-downloading-a-file-in-a-blazor-webassembly-application.htm
// Create the URL
const file = new File([content], filename, { type: "application/octet-stream" });
const exportUrl = URL.createObjectURL(file);
// Create the <a> element and click on it
const a = document.createElement("a");
document.body.appendChild(a);
a.href = exportUrl;
a.download = filename;
a.target = "_self";
a.click();
// We don't need to keep the object url, let's release the memory
// On Safari it seems you need to comment this line... (please let me know if you know why)
URL.revokeObjectURL(exportUrl);
}
我不确定我在这里做错了什么?
感谢您的帮助! 莎拉
编辑: 更改了以下代码:现在可以使用了。
function BlazorDownloadFile(filename, bytesBase64) {
var link = document.createElement('a');
link.download = filename;
link.href = "data:application/octet-stream;base64," + bytesBase64;
document.body.appendChild(link); // Needed for Firefox
link.click();
document.body.removeChild(link);
}
【问题讨论】:
-
您应该下载
byte[]而不是 Base64 编码的字符串 ;) -
尝试了以下方法: private async void SaveToExcel(){ byte[] XLSStream= _saveToExcel.SaveSearchToExcel(EquipmentForms);等待 js.InvokeVoidAsync("BlazorDownloadFile", "export.xlsx",XLSStream); } 仍然没有运气..
标签: excel blazor blazor-server-side closedxml