0

我已经编写了这段代码,它将生成一个 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"); 
4

1 回答 1

0

假设这是一个保存在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();
        }
    }
于 2013-03-07T14:58:17.167 回答