简体   繁体   English

C# Blazor 导出到 Excel 文件格式或文件扩展名无效

[英]C# Blazor Export To Excel File Format or File Extension is not valid

I have a list that I am trying to export to excel using the following code with the ClosedXML nuget package and following a guide online:我有一个列表,我正在尝试使用以下代码和 ClosedXML nuget package 并遵循在线指南将其导出到 excel:

 private async TaskClickExportXLS()
        {
            
            await ExportToExcel(js, selectedFlyer.DealNo+"_SKY_CAT_Report.xlsx");
        }
        public async Task ExportToExcel(IJSRuntime js, string fileName)
        {
            blockProducts = blocks.SelectMany(b => b.Products).Distinct().ToList();
            var wb = new XLWorkbook();
            

            var ws = wb.Worksheets.Add("Sku Category Report");

            ws.Cell(1, 1).Value = "SKU";
            ws.Cell(1, 2).Value = "Product EN";
            ws.Cell(1, 3).Value = "Product FR";
            ws.Cell(1, 4).Value = "Category";
           
            foreach(var item in blockProducts)
            {
                ws.Cell(1, 1).Value = item.Sku;
                ws.Cell(1, 2).Value = item.ProductEn;
                ws.Cell(1, 3).Value = item.ProductFr;
                ws.Cell(1, 4).Value = item.MainCategory;
            }

            MemoryStream XLSStream = new();
            XLSStream.Position = 0;
            wb.SaveAs(XLSStream);
            
            var XLSSArray = XLSStream.ToArray();

            await js.InvokeVoidAsync("BlazorDownloadFile", fileName, XLSSArray);
        }

I alsocopied this js runtime file from the guide as well:我也从指南中复制了这个 js 运行时文件:

function BlazorDownloadFile(filename, content) {


    // Create the URL
    const file = new File([content], filename, { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" });
    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();
    URL.revokeObjectURL(exportUrl);
}

My file downloads but when it opens I get the "Excel cannot open the file because the file format or extension is not valid".我的文件已下载,但打开时出现“Excel 无法打开文件,因为文件格式或扩展名无效”。 I have went online and did research and the things I've tried are the following - Set the Stream position to 0. Change the type of the file in my openfile.js to the following: type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" This does not seem the fix the issue and my code seems to work fine when debugging.我已经上网并进行了研究,我尝试过的事情如下 - 将 Stream position 设置为 0。将我的 openfile.js 中的文件类型更改为以下内容: type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"这似乎不能解决问题,我的代码在调试时似乎工作正常。 Any help would be appreciated!任何帮助,将不胜感激!

I had tried to follow that guide and it did not work for me.我曾尝试遵循该指南,但它对我不起作用。 What I ended up doing is streaming my workbook (wb) into a byte array and passing it as a parameter to a SaveAs function:我最终做的是将我的工作簿 (wb) 流式传输到字节数组并将其作为参数传递给 SaveAs function:

var bytes = new byte[0];
using (var ms = new MemoryStream())
{
     wb.SaveAs(ms);
     bytes = ms.ToArray();
}

await SaveAs(JSRuntime, fileName + ".xlsx", bytes);

This is the SaveAs function which is async Task like the comments were suggesting:这是 SaveAs function,它是异步任务,就像评论所建议的那样:

async Task SaveAs(IJSRuntime js, string fileName, byte[] data)
{
    await js.InvokeAsync<object>(
        "BlazorDownloadFile",
        fileName,
        Convert.ToBase64String(data)
    );
}

And here is the js:这是js:

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);
}

I believe these are the references I used: https://gist.github.com/danielplawgo/ac4d58837224dba7b6fc51de865b12da https://blazorfiddle.com/s/o8g3elz1我相信这些是我使用的参考资料: https://gist.github.com/danielplawgo/ac4d58837224dba7b6fc51de865b12da https://blazorfiddle.com/s/o8g3elz1

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 C#生成的Excel文件:文件格式或文件扩展名无效 - C# Generated Excel File: File Format or File Extension is not valid 生成 Excel C#:Excel 无法打开文件,因为文件格式或文件扩展名无效 - Generate Excel C#: Excel cannot open the file because the file format or file extension is not valid xlsx excel无法打开文件,因为文件格式或文件扩展名无效-C# - xlsx excel cannot open the file because the file format or file extension is not valid - c# excel无法打开文件,因为文件格式或文件扩展名无效c# - excel cannot open the file because the file format or file extension is not valid c# 从 C# 桌面应用程序打开以编程方式生成的 Excel 文件时出现 C# 错误:“文件格式或文件扩展名无效” - C# Error while opening programmatically generated Excel file from a C# desktop application: "File format or file extension is not valid" 无法在C#中打开Excel文件,因为格式有不同的扩展名错误 - can not open excel file in c# for different format extension error 将文件下载到用户计算机后,从网页导出到Excel按钮出现错误:“文件格式或文件扩展名无效” - Export to Excel button from web page gives an error after the file is downloaded to the users machine: “File format or file extension is not valid” 在C#中将值格式化为有效的json文件 - Format values as a valid json file in C# 文件格式无效Richtextbox c# - File format is not valid Richtextbox c# C#/-MVC:导出Excel文件的文件名 - C#/-MVC : filename for export excel file
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM