使用.NET Aspose Cells生成Excel文件并尝试通过浏览器下载

时间:2018-06-22 09:35:21

标签: javascript c# excel aspose-cells

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

这种情况需要先生成Excel文件,然后再将Excel文件传递给用户的浏览器以供下载。

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

然后,我打开使用Aspose Cells创建的Excel模板,并在其中填充CSV内容。

当我将文件本地保存到我的机器上时,这种方法很好用,但是当我尝试将其传递回Javascript以通过浏览器下载文件时,这种方法就无法正常工作。

请在下面找到我的代码:

C#-生成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文件,但该文件已损坏,无法打开。

我要问的是,这真的可以首先完成吗?

如果是,那么我做错了什么吗?

1 个答案:

答案 0 :(得分:0)

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的输出 C# Excel Aspose Cells

代码

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担任开发人员推广人员