创建excel文件并下载它而不将其保存到服务器中,是否可能?

时间:2014-10-27 13:01:40

标签: c# asp.net visual-studio-2012 interop

我设法用interop创建一个excel文件,现在我想要下载这个excel文件 在网络浏览器中,而不是保存在驱动器中。

     var xlApp = new Excel.Application();
     Excel.Workbook xlWorkBook = xlApp.Workbooks.Add();
     Excel.Worksheet xlWorkSheet = xlWorkBook.Sheets[1];
     Excel.Range chartRange;

      var attendance_list = CTX.schedules.Where(s => s.event_id == Convert.ToInt32(param));
      if (attendance_list.Count() > 0)
      {
             xlWorkSheet.Cells[1, 1] = "PIC : ";
             xlWorkSheet.Cells[2, 1] = "Tempat : ";

             xlWorkSheet.Cells[1, 2] = attendance_list.FirstOrDefault().calendar_event.PIC;
             xlWorkSheet.Cells[2, 2] = attendance_list.FirstOrDefault().calendar_event.sched_loc;

             xlWorkSheet.Shapes.AddPicture(@Server.MapPath("~/Images/" + "oto_group2.png"), MsoTriState.msoFalse, MsoTriState.msoCTrue, 50, 50, 100, 45);

             xlWorkSheet.Shapes.AddPicture(@Server.MapPath("~/Images/" + "oto_group3.png"), MsoTriState.msoFalse, MsoTriState.msoCTrue, 280, 50, 100, 45);

             int row = 10;
             int idx = 0;

             xlWorkSheet.Cells[9, 1] = "No";
             xlWorkSheet.Cells[9, 2] = "Name";
             xlWorkSheet.Cells[9, 3] = "Phone";
             xlWorkSheet.Cells[9, 4] = "Time";
             xlWorkSheet.Cells[9, 5] = "Branch";
             xlWorkSheet.Cells[9, 6] = "Sign";
             xlWorkSheet.Cells[9, 7] = "Note";

             chartRange = (xlWorkSheet.get_Range("b9"));
             chartRange.ColumnWidth = 40;

             chartRange = (xlWorkSheet.get_Range("c9"));
             chartRange.ColumnWidth = 20;

             chartRange = (xlWorkSheet.get_Range("g9"));
             chartRange.ColumnWidth = 20;

             var key = CTX.translate_value_ms.Where(t => t.PSF_type == "HRS_PHONE_TYPE"
                                                                     && t.value == "CELL").FirstOrDefault().translate_value_id;

             foreach (var item in attendance_list)
              {
                 idx++;

                  var hp = item.user_list.user_phones.Where(p => p.phone_type_id == key).FirstOrDefault();

                  xlWorkSheet.Cells[row, 1] = idx;
                  xlWorkSheet.Cells[row, 2] = displayFullName(item.user_list.fname, item.user_list.mname, item.user_list.lname);
                  xlWorkSheet.Cells[row, 3] = hp.phone_number;
                  xlWorkSheet.Cells[row, 4] = item.calendar_event.time_range;
                  xlWorkSheet.Cells[row, 5] = item.calendar_event.branch;
                  xlWorkSheet.Cells[row, 6] = "";
                  xlWorkSheet.Cells[row, 7] = "";

                     row++;
             }

             chartRange = xlWorkSheet.get_Range("a9", "g9");
             chartRange.Font.Bold = true;
             chartRange.Interior.Color = System.Drawing.Color.Gray;

             chartRange = xlWorkSheet.get_Range("a9",  "g" + (row - 1));
             chartRange.BorderAround(Excel.XlLineStyle.xlContinuous, Excel.XlBorderWeight.xlMedium, Excel.XlColorIndex.xlColorIndexAutomatic, Excel.XlColorIndex.xlColorIndexAutomatic);

             xlWorkBook.SaveAs("csharp.net-informations.xls", Excel.XlFileFormat.xlWorkbookNormal);

             xlWorkBook.Close(true);
             xlApp.Quit();

             Marshal.ReleaseComObject(xlApp);
     }

这是我到目前为止创建的excel文件。需要一些启发。 “这段代码将excel文件保存到驱动器中,这不是我想要实现的结果。”

这是我生成的Excel:enter image description here

4 个答案:

答案 0 :(得分:2)

我使用https://npoi.codeplex.com/创建excel并在我的控制器操作上返回了FileStereamResult。 我认为你不能使用你正在使用的Excel库

How to write an Excel workbook to a MemoryStream in .NET?

但是看看npoi真的很简单,他们甚至有一个关于你正在寻找的例子,这是这样的

public FileStreamResult MyAction(parameters)
{
    var workBook = CreateWorkbook(parameters);
    var stream = new MemoryStream();
    workBook.Write(stream);
    stream.Position = 0;   
    return File(stream, "attachment;filename=myfile.xls", "myfile.xls");
}

像这样你不要把任何东西保存到文件系统。

答案 1 :(得分:1)

您需要暂时将文件保存在服务器上,以便将其提供给客户端。

您可以使用System.IO.Path中的实用程序(例如GetTempPath())将其保存在临时路径中,以便将文件放在操作系统将在不需要时自动清理文件的位置。

我不知道您使用的是哪种网络服务器,但如果您使用MVC,则可以执行此类操作来为控制器中的文件提供服务

var filePath = System.IO.Path.GetTempFileName();
//then save the file to the filePath
return File(filePath);

答案 2 :(得分:0)

使用你的作品和我使用NPOI制作的例子,你可以做这样的事情

public FileStreamResult MyAction(parameters)
{
   //Here you create a workBook with your actual code
    var workBook = CreateWorkbook(parameters);
    var fileName = "routeToFileWhereYourAppCanWrite.xls"
    //Here you save the file to the file system
    workbook.SaveToFile(fileName);
    using (MemoryStream ms = new MemoryStream())
    {
        using (FileStream fileStream = new FileStream("file.bin", FileMode.Open, FileAccess.Read))
        {
            fileStream.CopyTo(ms);
        }
       //Here you delete the saved file
        File.Delete(fileName);
        ms.Position = 0;   
        return File(stream, "attachment;filename=myfile.xls", "myfile.xls");
    }
}

总之,像现在一样创建文件,保存文件,将其加载到内存中,删除它并返回流

答案 3 :(得分:0)

将此代码段自带项目粘贴到Marshal.ReleaseComObject(xlApp);此行下。
之后设置文件保存在系统中的路径 我希望这段代码能够运作。

    string fileName = "";
    Response.ContentType = "application/vnd.ms-excel";
    fileName = Server.MapPath("~/WriteReadData/Excelfiles/Excelfile.xls");  
   //Give path name\file name.

    Response.AppendHeader("Content-Disposition", "attachment; filename="Excelfile.xls");

    //Specify the file name which needs to be displayed while prompting

    Response.TransmitFile(fileName);

    Response.End();