ASP.Net webform generated Excel File to local PC a

2019-07-23 21:33发布

问题:

Following on from a question about generating Excel files, I need to be able to create the file locally while the webform app is located on the remote web server. This is not anything I've dealt with before, so I am finding it difficult exactly what to ask. I am using WebForms on VS2010 with c#. eanderson pointed me in the direction of Simplexcel by Michael Stum which seems to do the trick but the file is generated on the server (or should I says 'tries to' as it is not permitted!!!).

回答1:

You should be able to do something similar to this to generate and download the Excel Sheet.

protected void generateExcelSheet_click(object sender, EventArgs e)
{
    // Create Excel Sheet
    var sheet = new Worksheet("Hello, world!");
    sheet.Cells[0, 0] = "Hello,";
    sheet.Cells["B1"] = "World!";
    var workbook = new Workbook();
    workbook.Add(sheet);

    // Save
    Response.ContentType = "application/vnd.ms-excel";
    Response.AppendHeader("Content-Disposition", "attachment; filename=MyExcelSheet.xls");
    workbook.Save(Response.OutputStream, CompressionLevel.Maximum);

    Response.End();
}

In the designer.aspx:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="FileDownload.Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <asp:Button ID="btnExcel" runat="server" Text="Download Excel Sheet" onclick="generateExcelSheet_click" />
    </form>
</body>
</html>

I based this code on this tutorial.