【问题标题】:Generating Excel File using .NET Aspose Cells and trying to download via browser使用 .NET Aspose Cells 生成 Excel 文件并尝试通过浏览器下载
【发布时间】:2018-06-22 09:35:20
【问题描述】:

我正在尝试使用 .NET Aspose Cells 动态生成 HTML 报告的 Excel 版本。

这种情况需要生成Excel文件,然后将Excel文件传给用户的浏览器进行下载。

我使用 HTML 报告中所需的数据创建了一个 csv 文件。

然后我打开一个使用 Aspose Cells 创建的 Excel 模板,并用 CSV 内容填充它。

当我将文件本地保存到我的机器时,这工作正常,但当我尝试将它传递回 Javascript 以通过浏览器下载它时,它永远不会。

请在下面找到我的代码:

C# - Aspose Excel 工作簿生成

Workbook temp = new Workbook(System.Web.Hosting.HostingEnvironment.MapPath($"~/templates/") + @"excel_template.xlsx");
Worksheet ws = temp.Worksheets[0];
ws.Cells.ImportCSV(csvFile, ",", false, 1, 0);

// Used to test the excel populates correctly
temp.Save("Path_to_file" + fileName + ".xlsx", SaveFormat.Xlsx);

然后我尝试通过 HttpResponseMessage 将该工作簿传递给浏览器。

经过大量搜索,这是我想出的(注意:可能完全错误)

 MemoryStream ms = new MemoryStream();
 temp.Save(ms, SaveFormat.Xlsx);
 byte[] bytes = ms.ToArray();

 HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
 response.Content = new ByteArrayContent(bytes);
 response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
 response.Content.Headers.ContentDisposition.FileName = fileName + ".xlsx";
 response.Content.Headers.ContentType = new MediaTypeHeaderValue("Application/x-msexcel");

 return response;

然后我尝试使用 Javascript 与响应交互,以生成通过浏览器可见的 excel 文件的下载。

JavaScript 代码

$.get(ROOT + 'api_route', { 'csv': csv }, function (data) {
     var byteArray = new Uint8Array(data);
     var link = document.createElement('a');
     var blob = new Blob(byteArray, { type: "application/octet-stream" });
     link.href = window.URL.createObjectURL(blob);
     link.download = "sample_excel_" + new Date(Date.now()).toLocaleDateString() + '_' + new Date(Date.now()).toLocaleTimeString() + ".xlsx";
     link.click();
});

这会通过浏览器下载excel文件,但文件已损坏,无法打开。

我要问的是,这实际上可以先完成吗?

如果是这样,有什么明显的我做错了吗?

【问题讨论】:

    标签: javascript c# excel aspose-cells


    【解决方案1】:

    Update-1

    请尝试以下代码,它可能会解决您的问题。请注意,

    • 对于 XLS - 您应该使用 XlsSaveOptions
    • 对于 XLSX - 您应该使用 OoxmlSaveOptions

    您还需要使用 End() 方法结束 响应流。


    C#

    // Save file and send to client browser using selected format
    if (yourFileFormat == "XLS")
    {
        workbook.Save(HttpContext.Current.Response, "output.xls", ContentDisposition.Attachment, new XlsSaveOptions(SaveFormat.Excel97To2003));
    }
    else
    {
        workbook.Save(HttpContext.Current.Response, "output.xlsx", ContentDisposition.Attachment, new OoxmlSaveOptions(SaveFormat.Xlsx));
    }
    
    HttpContext.Current.Response.End();
    

    Update-2

    不涉及 JavaScript。请看代码

    • Default.aspx
    • Default.aspx.cs

    如下所示。以下屏幕截图显示了当您单击其中一个按钮时如何下载 Excel 文件。

    在 Chrome 中显示 Default.aspx 输出的屏幕截图

    代码

    Default.aspx

    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
    
    <!DOCTYPE html>
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
    
            <asp:Button ID="btnSaveToXLS" runat="server" Text="Save to XLS" OnClick="btnSaveToXLS_Click" /> <br /><br />
            <asp:Button ID="btnSaveToXLSX" runat="server" Text="Save to XLSX" OnClick="btnSaveToXLSX_Click" />
    
        </div>
        </form>
    </body>
    </html>
    

    Default.aspx.cs

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    
    using Aspose.Cells;
    
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
    
        }
    
        protected void btnSaveToXLS_Click(object sender, EventArgs e)
        {
            //Create empty workbook.
            Workbook workbook = new Workbook();
    
            // Access first worksheet
            Worksheet worksheet = workbook.Worksheets[0];
    
            // Put some value in cell C4
            Cell cell = worksheet.Cells["C4"];
            cell.PutValue("This is XLS format generated by Aspose.Cells API.");
    
            // Save file and send to client browser using selected format
            workbook.Save(HttpContext.Current.Response, "outputSaveToXLS.xls", ContentDisposition.Attachment, new XlsSaveOptions(SaveFormat.Excel97To2003));
    
            HttpContext.Current.Response.End();
        }
    
        protected void btnSaveToXLSX_Click(object sender, EventArgs e)
        {
            //Create empty workbook.
            Workbook workbook = new Workbook();
    
            // Access first worksheet
            Worksheet worksheet = workbook.Worksheets[0];
    
            // Put some value in cell C4
            Cell cell = worksheet.Cells["C4"];
            cell.PutValue("This is XLSX format generated by Aspose.Cells API.");
    
            // Save file and send to client browser using selected format
            workbook.Save(HttpContext.Current.Response, "outputSaveToXLSX.xlsx", ContentDisposition.Attachment, new OoxmlSaveOptions(SaveFormat.Xlsx));
    
            HttpContext.Current.Response.End();
        }
    }
    

    注意:我在 Aspose 担任开发人员宣传员

    【讨论】:

    • 首先感谢您的回复。我试图实现这一点,但我的 excel 输出文件仍在下载为损坏的文件。你的 JavaScript 是什么样的?
    • 不涉及 JavaScript。请查看我现有回复中的 Update-2 以获取可运行的示例代码和屏幕截图。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多