【问题标题】:transfer from c# to excel with multiple sheets使用多张工作表从 c# 转移到 excel
【发布时间】:2025-12-06 23:35:01
【问题描述】:

我有几个包含不同类别信息的不同字典,我需要将它们全部输出到包含多个电子表格的 xls 或 csv 文件中。目前,我必须分别下载特定日期范围的每个 excel 文件,然后将它们复制并粘贴在一起,以便它们位于同一文件的不同工作表上。有没有办法将它们全部下载到一个文档中?目前,我使用以下代码输出他们的文件:

 writeCsvToStream(
     organize.ToDictionary(k => k.Key, v => v.Value as IacTransmittal), writer
 );
 ms.Seek(0, SeekOrigin.Begin);
 Response.Clear();
 Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
 Response.AddHeader("Content-Length", ms.Length.ToString());
 Response.ContentType = "application/octet-stream";
 ms.CopyTo(Response.OutputStream);

 Response.End();

writeCsvToStream 只是为单个文件创建文本。

【问题讨论】:

    标签: c# csv dictionary export xls


    【解决方案1】:

    您可以使用一些不同的选项。

    • ADO.NET Excel 驱动程序 - 使用此 API,您可以使用 SQL 样式语法将数据填充到 Excel 文档中。工作簿中的每个工作表都是一个表格,工作表中的每个列标题都是该表格中的一列等等。

    这是一篇关于使用 ADO.NET 导出到 Excel 的代码项目文章: http://www.codeproject.com/Articles/567155/Work-with-MS-Excel-and-ADO-NET

    ADO.NET 方法在多用户网络应用环境中使用是安全的。

    • 使用 OpenXML 导出数据 OpenXML 是不同类型文档的架构定义,而更高版本的 Excel(使用 .xlsx、.xlsm 等而不只是 .xls 的版本)对文档使用这种格式。 OpenXML 模式庞大且有些笨重,但是您几乎可以用它做任何事情。

    这是一篇关于使用 OpenXML 将数据导出到 Excel 的代码项目文章: http://www.codeproject.com/Articles/692121/Csharp-Export-data-to-Excel-using-OpenXML-librarie

    OpenXML 方法可以安全地用于多用户 Web 应用程序环境。

    • 第三种方法是使用 COM 自动化,这与以编程方式运行 Excel 桌面应用程序实例并使用 COM 控制该实例的操作相同。

    这是一篇关于该主题的文章: http://support.microsoft.com/kb/302084

    请注意,这第三种方法(办公自动化)在多用户网络应用环境中安全。 IE。它不应该在服务器上使用,只能从独立的桌面应用程序中使用。

    【讨论】:

      【解决方案2】:

      如果你愿意学习一个新的库,我强烈推荐EPPlus

      我在这里做了一些假设,因为您没有发布太多要翻译的代码,但使用示例可能如下所示:

      using OfficeOpenXml;
      using OfficeOpenXml.Style;
      
      public static void WriteXlsOutput(Dictionary<string, IacTransmittal> collection) //accepting one dictionary as a parameter
      {
          using (FileStream outFile = new FileStream("Example.xlsx", FileMode.Create))
          {
              using (ExcelPackage ePackage = new ExcelPackage(outFile))
              {
                  //group the collection by date property on your class
                  foreach (IGrouping<DateTime, IacTransmittal> collectionByDate in collection
                      .OrderBy(i => i.Value.Date.Date)
                      .GroupBy(i => i.Value.Date.Date)) //assuming the property is named Date, using Date property of DateTIme so we only create new worksheets for individual days
                  {
                      ExcelWorksheet eWorksheet = ePackage.Workbook.Worksheets.Add(collectionByDate.Key.Date.ToString("yyyyMMdd")); //add a new worksheet for each unique day
      
                      Type iacType = typeof(IacTransmittal);
                      PropertyInfo[] iacProperties = iacType.GetProperties();
                      int colCount = iacProperties.Count(); //number of properties determines how many columns we need
                      //set column headers based on properties on your class
                      for (int col = 1; col <= colCount; col++)
                      {
                          eWorksheet.Cells[1, col].Value = iacProperties[col - 1].Name ; //assign the value of the cell to the name of the property
                      }
      
                      int rowCounter = 2;
      
                      foreach (IacTransmittal iacInfo in collectionByDate) //iterate over each instance of this class in this igrouping
                      {
                          int interiorColCount = 1;
                          foreach (PropertyInfo iacProp in iacProperties) //iterate over properties on the class
                          {
                              eWorksheet.Cells[rowCounter, interiorColCount].Value = iacProp.GetValue(iacInfo, null); //assign cell values by getting the value of each property in the class
                              interiorColCount++;
                          }
                          rowCounter++;
                      }
                  }
                  ePackage.Save();
              }
          }
      }
      

      【讨论】:

        【解决方案3】:

        感谢您的想法!我最终能够弄清楚以下内容

        using Excel = Microsoft.Office.Interop.Excel;
        
        
        Excel.Application ExcelApp = new Excel.Application();
        Excel.Workbook ExcelWorkBook = null;
        Excel.Worksheet ExcelWorkSheet = null;
        
        ExcelApp.Visible = true;
        ExcelWorkBook = ExcelApp.Workbooks.Add(Excel.XlWBATemplate.xlWBATWorksheet);
        
        List<string> SheetNames = new List<string>() 
            { "Sheet1", "Sheet2", "Sheet3", "Sheet4", "Sheet5", "Sheet6", "Sheet7"};
        
        string [] headers = new string [] 
            { "Field 1", "Field 2", "Field 3", "Field 4", "Field 5" };
        
        for (int i = 0; i < SheetNames.Count; i++)
            ExcelWorkBook.Worksheets.Add(); //Adding New sheet in Excel Workbook
        
        for (int k = 0; k < SheetNames.Count; k++ )
        {
            int r = 1; // Initialize Excel Row Start Position  = 1
        
            ExcelWorkSheet = ExcelWorkBook.Worksheets[k + 1];
            //Writing Columns Name in Excel Sheet
            for (int col = 1; col < headers.Length + 1; col++)
                ExcelWorkSheet.Cells[r, col] = headers[col - 1];
            r++;
            switch (k)
            {
                case 0:
                    foreach (var kvp in Sheet1)
                    {
                        ExcelWorkSheet.Cells[r, 1] = kvp.Value.Field1;
                        ExcelWorkSheet.Cells[r, 2] = kvp.Value.Field2;
                        ExcelWorkSheet.Cells[r, 3] = kvp.Value.Field3;
                        ExcelWorkSheet.Cells[r, 4] = kvp.Value.Field4;
                        ExcelWorkSheet.Cells[r, 5] = kvp.Value.Field5;
                        r++;
                    }
                    break;
        
            }
            ExcelWorkSheet.Name = SheetNames[k];//Renaming the ExcelSheets
        }
        
        //Activate the first worksheet by default.
        ((Excel.Worksheet)ExcelApp.ActiveWorkbook.Sheets[1]).Activate();
        
        //Save As the excel file.
        ExcelApp.ActiveWorkbook.SaveCopyAs(@"out_My_Book1.xls");
        

        【讨论】: