【问题标题】:ASP.NET MVC: C# Download file and save as dialog [duplicate]ASP.NET MVC:C# 下载文件并另存为对话框 [重复]
【发布时间】:2013-02-22 09:57:36
【问题描述】:

我已经编写了这段代码,它将生成一个 Excel 电子表格并将其保存到指定位置。然后我想通过从存储位置读取文件然后询问用户他们想要存储它的位置来显示一个“另存为”对话框。

Excel.Application excelApp = null;
            Excel.Workbook wb = null;
            Excel.Worksheet ws = null;
            Excel.Range range = null;

excelApp = new Excel.Application();
            wb = excelApp.Workbooks.Add();
            ws = wb.Worksheets.get_Item(1) as Excel.Worksheet;

for(int i = 0; i< 10;++i) {
    ws.Cells[i, 1] = i+
}

wb.SaveAs(@"C:\test.xls", Excel.XlFileFormat.xlWorkbookNormal);
wb.Close(true);
excelApp.Quit();

以下格式如何下载?

string str = "Hello, world"; 

byte[] bytes = System.Text.Encoding.UTF8.GetBytes(str); 

return File(bytes, "text/plain"); 

【问题讨论】:

  • 请阅读 this question 以讨论要使用的正确 MIME 类型 - text/plain 不适用于 Excel 文档。

标签: asp.net


【解决方案1】:

假设这是一个保存在 c:\temp\excelDoc.xls 的 Excel 文档,并且假设您有一个包含这样的链接的 WebForm

<asp:LinkButton runat="server" ID="GetExcel" OnClick="GetExcel_Click">Download</asp:LinkButton>

在您的代码隐藏中,您可以从磁盘读取文件并通过类似这样的方式发送给用户

    protected void GetExcel_Click(object sender, EventArgs e)
    {
        var fileName = "excelDoc.xls";
        using (var cs = new FileStream(@"c:\temp\" + fileName, FileMode.Open))
        {
            Response.Clear();
            Response.AddHeader("content-disposition", "attachment; filename=" + fileName);
            Response.ContentType = "application/vnd.ms-excel";


            byte[] buffer = new byte[32768];
            int read;
            while ((read = cs.Read(buffer, 0, buffer.Length)) > 0)
            {
                Response.OutputStream.Write(buffer, 0, read);
            }

            Response.End();
            Response.Flush();
        }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-20
    • 2021-12-13
    • 2011-02-20
    相关资源
    最近更新 更多