【问题标题】:Create excel file and download it without saving it into the server, is it possible?创建excel文件并下载它而不将其保存到服务器中,可以吗?
【发布时间】:2014-10-27 13:01:39
【问题描述】:

我已经成功创建了一个带有互操作的 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:

【问题讨论】:

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


    【解决方案1】:

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

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

    我不知道你使用的是什么网络服务器,但如果你使用的是 MVC,你会做这样的事情来在你的控制器中提供文件

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

    【讨论】:

    • 我很想知道这是否适用于 Microsoft Azure 的应用服务?
    【解决方案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");
    }
    

    像这样你不会将任何东西保存到文件系统中。

    【讨论】:

    • 我已经用屏幕截图编辑了我的帖子,我考虑使用其他库,但我担心我需要创建自定义 excel 文件,你之前提到的库是否可以用于创建自定义像我的SS一样的excel文件?
    • 我知道我改变了背景颜色,调整了列宽,设置了边框,我发现你可以插入图像(我没有这样做)。您也可以阅读我刚刚想到的其他答案。
    【解决方案3】:

    结合你的工作和我使用 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");
        }
    }
    

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

    【讨论】:

      【解决方案4】:

      在Marshal.ReleaseComObject(xlApp);这一行下粘贴这个sn-p代码自己的项目。
      在您的文件保存在系统中的设置路径之后。
      我希望这段代码能正常工作。

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-02-04
        • 1970-01-01
        • 1970-01-01
        • 2019-07-31
        • 1970-01-01
        相关资源
        最近更新 更多