动态创建excel文件并自动下载

时间:2014-01-26 05:48:10

标签: asp.net c#-4.0

Microsoft.Office.Interop.Excel.Application xlApp;
Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
xlApp = new Microsoft.Office.Interop.Excel.ApplicationClass();
xlWorkBook = xlApp.Workbooks.Add(misValue);

xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
xlWorkSheet.Cells[1, 1] = "http://csharp.net-informations.com";

xlWorkBook.SaveAs("csharp-Excel.xls", Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();

这是我的C#按钮代码。我只是想按钮点击自动执行此excel文件下载。此代码仅生成excel文件。以及如何添加下载代码。我不知道。例如,我们在谷歌浏览器中下载任何内容,然后单击项目开始下载。和浏览器下载文件底部显示。怎么做,请帮帮我 谢谢 预先

1 个答案:

答案 0 :(得分:3)

在下面的代码中,您知道要保存Excel文件的Excel文件路径

    xlWorkBook.SaveAs("csharp-Excel.xls"

现在你知道你已经创建了excel文件并保存在服务器上的位置(〜/ csharp-Excel.xls) 创建生成Excel文件的对象的实例

    string path = Server.MapPath("~/csharp-Excel.xls");
    System.IO.FileInfo file = new System.IO.FileInfo(path);
    string Outgoingfile = "FileName.xlsx";
    if (file.Exists)
        {
            Response.Clear();
            Response.ClearContent();
            Response.ClearHeaders();
            Response.AddHeader("Content-Disposition", "attachment; filename=" + Outgoingfile);
            Response.AddHeader("Content-Length", file.Length.ToString());
            Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            Response.WriteFile(file.FullName);
            Response.Flush();
            Response.Close();

        }
     else
        {
            Response.Write("This file does not exist.");
        }