2013-03-07 48 views
0

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

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"); 
+0

请仔细阅读[这个问题](http://stackoverflow.com/questions/974079/setting-mime-type-for-excel -document)为di对使用正确的MIME类型进行修改 - 对于Excel文档,“text/plain”不正确。 – 2013-03-07 09:24:01

回答

0

由于是在保存ç一个Excel文档:\ TEMP \ excelDoc.xls并考虑到您具有这样

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

在您的代码隐藏链接一个WebForm你可以从磁盘读取该文件,并通过东西向用户发送这样的

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(); 
     } 
    }