我编写了这段代码,它会生成一个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");
答案 0 :(得分: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();
}
}