C# 带有openxml的Excel文件,在单个工作簿中包含多个工作表

C# 带有openxml的Excel文件,在单个工作簿中包含多个工作表,c#,openxml,spreadsheetml,C#,Openxml,Spreadsheetml,我正在尝试将数据插入多个工作表。对于我的excel,我有两张表,分别是“图表”和“图表数据”。我可以更新sheet2,chartdata sheet中的数据,但无法将数据插入sheet1。下面是我试图将数据插入excel工作表的代码。这里的数据来自数据库 double ticks = DateTime.Now.Ticks; // MarketAnalysis ms = new MarketAnalysis(); //ms.Marketan

我正在尝试将数据插入多个工作表。对于我的excel,我有两张表,分别是“图表”和“图表数据”。我可以更新sheet2,chartdata sheet中的数据,但无法将数据插入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();
         }

仅更新多张图纸

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

   // Insert code here.

}

为需要更新工作表单元格值的两张工作表创建两个类。对于每个类构造函数,传递电子表格文档对象并实现。只需避免插入新工作表的代码,只尝试插入单元格代码。

您可以尝试此方法。……可能会有所帮助

专用静态单元格InsertCellInWorksheet(字符串列名称、整型行索引、工作表部件工作表部件) { 工作表=工作表零件工作表; SheetData SheetData=工作表.GetFirstChild(); 字符串cellReference=列名称+行索引

        Alignment alignment1 = new Alignment() { WrapText = true };

        // If the worksheet does not contain a row with the specified row index, insert one.
        Row row;
        row = new Row() { RowIndex = 3, StyleIndex = 1 };
        if (sheetData.Elements<Row>().Where(r => r.RowIndex == rowIndex).Count() != 0)
        {
            row = sheetData.Elements<Row>().Where(r => r.RowIndex == rowIndex).First();
        }
        else
        {
            row = new Row() { RowIndex = Convert.ToUInt32(rowIndex) };
            sheetData.Append(row);
        }

        // If there is not a cell with the specified column name, insert one.  
        if (row.Elements<Cell>().Where(c => c.CellReference.Value == columnName + rowIndex).Count() > 0)
        {
            Row row2;
            row2 = new Row() { RowIndex = 3, StyleIndex = 1 };
            Cell rCell = null;
            foreach (Cell celld in row.Elements<Cell>())
            {
                if (string.Compare(celld.CellReference.Value, "A3", true) > 0)
                {
                    rCell = celld;
                    break;
                }
            }

            // Add the cell to the cell table at A1.
            Cell newCell = new Cell() { CellReference = "C3" };
            //Cell newCell1 = new Cell() { CellReference = "D3" };
            row.InsertBefore(newCell, rCell);
            //row.InsertBefore(newCell1, rCell);

            // Set the cell value to be a numeric value of 100.
            newCell.CellValue = new CellValue("#GUIDeXactLCMS#");
            //newCell1.CellValue = new CellValue("EN");
            newCell.DataType = new EnumValue<CellValues>(CellValues.Number);

            return row.Elements<Cell>().Where(c => c.CellReference.Value == cellReference).First();
        }
        else
        {
            // Cells must be in sequential order according to CellReference. Determine where to insert the new cell.
            Cell refCell = null;
            foreach (Cell cell in row.Elements<Cell>())
            {
                if (string.Compare(cell.CellReference.Value, cellReference, true) > 0)
                {
                    //string val = cell.CellReference.Value;
                    refCell = cell;
                    break;
                }
            }

            Cell newCell = new Cell() { CellReference = cellReference };
            row.InsertBefore(newCell, refCell);


            return newCell;


        }
        worksheet.Save();
    }
Alignment Alignment 1=new Alignment(){WrapText=true};
//如果工作表不包含具有指定行索引的行,请插入一行。
行行;
row=newrow(){RowIndex=3,StyleIndex=1};
if(sheetData.Elements().Where(r=>r.RowIndex==RowIndex).Count()!=0)
{
row=sheetData.Elements()。其中(r=>r.RowIndex==RowIndex)。First();
}
其他的
{
row=newrow(){RowIndex=Convert.ToUInt32(RowIndex)};
sheetData.Append(行);
}
//如果没有具有指定列名的单元格,请插入一个。
if(row.Elements().Where(c=>c.CellReference.Value==columnName+rowIndex).Count()>0)
{
第2排;
row2=新行(){RowIndex=3,StyleIndex=1};
单元格rCell=null;
foreach(row.Elements()中的单元格)
{
if(string.Compare(celld.CellReference.Value,“A3”,true)>0)
{
rCell=celld;
打破
}
}
//将单元格添加到A1处的单元格表中。
Cell newCell=newCell(){CellReference=“C3”};
//Cell newCell1=newcell(){CellReference=“D3”};
插入之前的行(newCell,rCell);
//插入前一行(newCell1,rCell);
//将单元格值设置为100的数值。
newCell.CellValue=新的CellValue(“#GUIDeXactLCMS#”);
//newCell1.CellValue=新的CellValue(“EN”);
newCell.DataType=新的枚举值(CellValues.Number);
返回row.Elements(),其中(c=>c.CellReference.Value==CellReference.First();
}
其他的
{
//单元格必须按照CellReference的顺序排列。确定在何处插入新单元格。
Cell refCell=null;
foreach(row.Elements()中的单元格)
{
if(string.Compare(cell.CellReference.Value,CellReference,true)>0)
{
//字符串val=cell.CellReference.Value;
refCell=单元格;
打破
}
}
Cell newCell=newCell(){CellReference=CellReference};
row.InsertBefore(newCell、refCell);
返回newCell;
}
工作表。保存();
}

编写这些代码而不是声明Sheet Sheet=Workbookpart.workbook…..等,编写这些var Sheet=Workbookpart.workbook.subjections()。其中(s=>s.Name.Value.Contains(“Sheet”);foreach(工作表中的var sheetname){if(sheetname.Name==“Sheet1”){}
        Alignment alignment1 = new Alignment() { WrapText = true };

        // If the worksheet does not contain a row with the specified row index, insert one.
        Row row;
        row = new Row() { RowIndex = 3, StyleIndex = 1 };
        if (sheetData.Elements<Row>().Where(r => r.RowIndex == rowIndex).Count() != 0)
        {
            row = sheetData.Elements<Row>().Where(r => r.RowIndex == rowIndex).First();
        }
        else
        {
            row = new Row() { RowIndex = Convert.ToUInt32(rowIndex) };
            sheetData.Append(row);
        }

        // If there is not a cell with the specified column name, insert one.  
        if (row.Elements<Cell>().Where(c => c.CellReference.Value == columnName + rowIndex).Count() > 0)
        {
            Row row2;
            row2 = new Row() { RowIndex = 3, StyleIndex = 1 };
            Cell rCell = null;
            foreach (Cell celld in row.Elements<Cell>())
            {
                if (string.Compare(celld.CellReference.Value, "A3", true) > 0)
                {
                    rCell = celld;
                    break;
                }
            }

            // Add the cell to the cell table at A1.
            Cell newCell = new Cell() { CellReference = "C3" };
            //Cell newCell1 = new Cell() { CellReference = "D3" };
            row.InsertBefore(newCell, rCell);
            //row.InsertBefore(newCell1, rCell);

            // Set the cell value to be a numeric value of 100.
            newCell.CellValue = new CellValue("#GUIDeXactLCMS#");
            //newCell1.CellValue = new CellValue("EN");
            newCell.DataType = new EnumValue<CellValues>(CellValues.Number);

            return row.Elements<Cell>().Where(c => c.CellReference.Value == cellReference).First();
        }
        else
        {
            // Cells must be in sequential order according to CellReference. Determine where to insert the new cell.
            Cell refCell = null;
            foreach (Cell cell in row.Elements<Cell>())
            {
                if (string.Compare(cell.CellReference.Value, cellReference, true) > 0)
                {
                    //string val = cell.CellReference.Value;
                    refCell = cell;
                    break;
                }
            }

            Cell newCell = new Cell() { CellReference = cellReference };
            row.InsertBefore(newCell, refCell);


            return newCell;


        }
        worksheet.Save();
    }