c# - 带有 openxml 的 Excel 文件,单个工作簿中有多个工作表

标签 c# openxml spreadsheetml

我正在尝试将数据插入多个工作表。对于我的 excel,我有两张纸,分别是“图表”和“ChartData”。我可以更新 sheet2、chartdata 工作表中的数据,但无法将数据插入到 sheet1 中。这是我试图将数据插入 Excel 工作表的代码。这里的数据来自数据库。

           double ticks = DateTime.Now.Ticks;
         // MarketAnalysis ms = new MarketAnalysis();
         //ms.Marketanalysis();

        File.Copy(Srcpath, @"E:\Works\OpenXML\DownloadTemplates\ExcelGenerated" + ticks + ".xlsx", true);
         using (SpreadsheetDocument myworkbok = SpreadsheetDocument.Open(@"E:\Works\OpenXML\DownloadTemplates\ExcelGenerated" + ticks + ".xlsx", true))
         {
             //Acess the main workbook which contain all the references

            WorkbookPart workbookpart = myworkbok.WorkbookPart;
             //Get sheet by name
             Sheet sheet = workbookpart.Workbook.Descendants<Sheet>().Where(s => s.Name == "ChartData").FirstOrDefault();

            //Worksheet Part by ID
             WorksheetPart worksheetpart = workbookpart.GetPartById(sheet.Id) as WorksheetPart;

            //Sheet data contains all the data
             SheetData sheetdata = worksheetpart.Worksheet.GetFirstChild<SheetData>();
             DataSet ds = db.Chart1Data();

              for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
             {
                 //  if (ds.Tables[0].Rows !=DBNull)
                 //{

                string Rowlabel = ds.Tables[0].Rows[i][0].ToString();
                 // float? FY13Actuval = Convert.ToInt32(ds.Tables[0].Rows[i][1]);

                if (!string.IsNullOrEmpty(ds.Tables[0].Rows[i][1].ToString()))
                 {
                     // string s = ds.Tables[0].Rows[i][1].ToString();
                     //FY13Actuval=float.Parse(ds.Tables[0].Rows[i][1].ToString());

                    FY13Actuval = Convert.ToDouble(ds.Tables[0].Rows[i][1].ToString());
                 }
                 else
                 {

                    FY13Actuval = null;
                 }

                double? Budget = Convert.ToDouble(ds.Tables[0].Rows[i][2].ToString());
                 double? Actuval = Convert.ToDouble(ds.Tables[0].Rows[i][3].ToString());
                 Row contentrow = CreateContentRow(index, Product, Actual, Budget, Forecast);

                index++;
                 sheetdata.AppendChild(contentrow);

                // }
             }
 .......Same code for the other 3 charts
 Sheet sheet1 = workbookpart.Workbook.Descendants<Sheet>().Where(s => s.Name == "Charts").FirstOrDefault();

            WorksheetPart worksheetpart1 = workbookpart.GetPartById(sheet1.Id) as WorksheetPart;

            //Sheet data contains all the data
             SheetData sheetdata1 = worksheetpart1.Worksheet.GetFirstChild<SheetData>();

            DataSet dsTbl = db.Table();
             int SCMTblIndex=5;
             for (int i = 0; i < dsTbl.Tables[0].Rows.Count; i++)
             {
                 Row tblRow = CreateScorecardMetricTblRow(SCMTblIndex, dsTbl.Tables[0].Rows[i][0].ToString(),
                                                                    dsTbl.Tables[0].Rows[i][1].ToString(),
                                                                    dsTbl.Tables[0].Rows[i][2].ToString());
                 SCMTblIndex++;
                 sheetdata1.AppendChild(tblRow);
             }

                myworkbok.WorkbookPart.Workbook.Save();
         }

以及创建单元格的方法:

public static string[] headerColumns = new string[]{ "A", "B", "C", "D", "E", "F", "G", "I", "J" };
public static string[] header = new string[] { "D", "E", "F" };

private static Row CreateContentRow(int index, string Product, double? Actual, double? Budget, double? Forecast)
     {

        //Create New ROw
         Row r = new Row();
         r.RowIndex = (UInt32)index;


        //Begin colums
         Cell c0 = new Cell();
         c0.CellReference = headerColumns[0] + index;
         CellValue v0 = new CellValue();
         v0.Text = Product;
         c0.AppendChild(v0);
         r.AppendChild(c0);

        Cell c1 = new Cell();
         c1.CellReference = headerColumns[1] + index;
         CellValue v1 = new CellValue();
         v1.Text = Actual.ToString();
         c1.AppendChild(v1);
         r.AppendChild(c1);

        Cell c2 = new Cell();
         c2.CellReference = headerColumns[2] + index;
         CellValue v2 = new CellValue();
         v2.Text = Budget.ToString();
         c2.AppendChild(v2);
         r.AppendChild(c2);

        Cell c3 = new Cell();
         c3.CellReference = headerColumns[3] + index;
         CellValue v3 = new CellValue();
         v3.Text = Forecast.ToString();
         c3.AppendChild(v3);
         r.AppendChild(c3);


        return r;


    }
public static Row CreateScorecardMetricTblRow(int index, string Act_Data, string Bud_Data, string VarPr_Data)
     {
         Row r = new Row();
         r.RowIndex = (UInt32)index;
         //Begin Colums

        Cell c0 = new Cell();
         c0.CellReference = header[0] + index;
         CellValue v0 = new CellValue();
         v0.Text = Act_Data;
         c0.AppendChild(v0);
         r.AppendChild(c0);

        Cell c1 = new Cell();
         c1.CellReference = header[1] + index;
         CellValue v1 = new CellValue();
         v1.Text = Bud_Data;
         c1.AppendChild(v1);
         r.AppendChild(c1);

        Cell c2 = new Cell();
         c2.CellReference = header[2] + index;
         CellValue v2 = new CellValue();
         v2.Text = VarPr_Data;
         c2.AppendChild(v2);
         r.AppendChild(c2);
          return r;
     }

最佳答案

只更新多张纸

// Open the document for editing.
using (SpreadsheetDocument spreadSheet = SpreadsheetDocument.Open(docName, true)) 
{

   // Insert code here.

}

为需要更新工作表单元格值的两个工作表创建两个类。对于每个类构造函数传递SpreadsheetDocument 对象并实现insert text into a cell in a spreadsheet document .只是避免插入新工作表的代码并尝试仅插入单元格代码。

关于c# - 带有 openxml 的 Excel 文件,单个工作簿中有多个工作表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15543313/

相关文章:

C#:数据类型与类型相同吗?

C# OpenXml 接受 .docx 中的所有修订

xml - 如何使用 Delphi/ADOM (OpenXML) 设置 xml DOCTYPE?

excel - Office Open XML 中的 <c t ="str"> 和 <c><is> 之间有什么区别?

c# - 调整旋转方面的正确方法

c# - 如何告诉 convert.todatetime 输入的格式为 dd-mm-yyyy

c# - C# lambda 是如何工作的?

c# - 使用 C# 提取 .docx 文件中的数据存储表

xml - 将 Excel 的 SUM() 添加到 XLST 结果页?