C# 打开XML SDK 2.0-如何更新电子表格中的单元格?

C# 打开XML SDK 2.0-如何更新电子表格中的单元格?,c#,xml,excel,sdk,C#,Xml,Excel,Sdk,我想使用OpenXMLSDK2.0(CTP)更新图表使用的电子表格中的单元格。我找到的所有代码示例都插入了新的单元格。我正在努力检索正确的工作表 public static void InsertText(string docName, string text, uint rowIndex, string columnName) { // Open the document for editing. using (SpreadsheetDocument spreadSheet =

我想使用OpenXMLSDK2.0(CTP)更新图表使用的电子表格中的单元格。我找到的所有代码示例都插入了新的单元格。我正在努力检索正确的工作表

public static void InsertText(string docName, string text, uint rowIndex, 
  string columnName)
{
  // Open the document for editing.
  using (SpreadsheetDocument spreadSheet = 
    SpreadsheetDocument.Open(docName, true))
  {
    Workbook workBook = spreadSheet.WorkbookPart.Workbook;

    WorksheetPart worksheetPart = workBook.WorkbookPart.
      WorksheetParts.First();

    SheetData sheetData = worksheetPart.Worksheet.
      GetFirstChild<SheetData>();

    // If the worksheet does not contain a row with the specified
    // row index, insert one.
    Row row;

    if (sheetData.Elements<Row>().Where(
      r => r.RowIndex == rowIndex).Count() != 0)
      // At this point I am expecting a match for a row that exists
      // in sheet1 but I am not getting one
公共静态void InsertText(字符串docName、字符串text、uint rowIndex、,
字符串(列名称)
{
//打开文档进行编辑。
使用(电子表格文档电子表格=
电子表格文档。打开(docName,true))
{
工作簿=电子表格.WorkbookPart.Workbook;
工作表部件工作表部件=工作簿.WorkbookPart。
WorksheetParts.First();
SheetData SheetData=工作表部分。工作表。
GetFirstChild();
//如果工作表不包含具有指定
//行索引,插入一个。
行行;
如果(sheetData.Elements(),其中(
r=>r.RowIndex==RowIndex).Count()!=0)
//此时,我希望与存在的行匹配
//在表1中,但我没有得到一个

当我在Visual Studio中浏览树时,我看到了三个工作表,但没有一个有任何子项。我缺少了什么?

这是工作代码。这是一个原型。对于大量更改,可能只打开文档一次。此外,还有一些硬编码的内容,如工作表名称和单元格类型,必须参数化在这之前可以称为生产就绪。 非常有帮助

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using System.Xml;
using System.IO;
using System.Diagnostics;

namespace OpenXMLWindowsApp
{
    public class OpenXMLWindowsApp
    {
        public void UpdateSheet()
        {
            UpdateCell("Chart.xlsx", "20", 2, "B");
            UpdateCell("Chart.xlsx", "80", 3, "B");
            UpdateCell("Chart.xlsx", "80", 2, "C");
            UpdateCell("Chart.xlsx", "20", 3, "C");

            ProcessStartInfo startInfo = new ProcessStartInfo("Chart.xlsx");
            startInfo.WindowStyle = ProcessWindowStyle.Normal;
            Process.Start(startInfo);
        }

        public static void UpdateCell(string docName, string text,
            uint rowIndex, string columnName)
        {
            // Open the document for editing.
            using (SpreadsheetDocument spreadSheet = 
                     SpreadsheetDocument.Open(docName, true))
            {
                WorksheetPart worksheetPart = 
                      GetWorksheetPartByName(spreadSheet, "Sheet1");

                if (worksheetPart != null)
                {
                    Cell cell = GetCell(worksheetPart.Worksheet, 
                                             columnName, rowIndex);

                    cell.CellValue = new CellValue(text);
                    cell.DataType = 
                        new EnumValue<CellValues>(CellValues.Number);

                    // Save the worksheet.
                    worksheetPart.Worksheet.Save();
                }
            }

        }

        private static WorksheetPart 
             GetWorksheetPartByName(SpreadsheetDocument document, 
             string sheetName)
        {
            IEnumerable<Sheet> sheets =
               document.WorkbookPart.Workbook.GetFirstChild<Sheets>().
               Elements<Sheet>().Where(s => s.Name == sheetName);

            if (sheets.Count() == 0)
            {
                // The specified worksheet does not exist.

                return null;
            }

            string relationshipId = sheets.First().Id.Value;
            WorksheetPart worksheetPart = (WorksheetPart)
                 document.WorkbookPart.GetPartById(relationshipId);
            return worksheetPart;

        }

        // Given a worksheet, a column name, and a row index, 
        // gets the cell at the specified column and 
        private static Cell GetCell(Worksheet worksheet, 
                  string columnName, uint rowIndex)
        {
            Row row = GetRow(worksheet, rowIndex);

            if (row == null)
                return null;

            return row.Elements<Cell>().Where(c => string.Compare
                   (c.CellReference.Value, columnName + 
                   rowIndex, true) == 0).First();
        }


        // Given a worksheet and a row index, return the row.
        private static Row GetRow(Worksheet worksheet, uint rowIndex)
        {
            return worksheet.GetFirstChild<SheetData>().
              Elements<Row>().Where(r => r.RowIndex == rowIndex).First();
        } 
    }
}
使用系统;
使用System.Collections.Generic;
使用系统数据;
使用System.Linq;
使用系统文本;
使用DocumentFormat.OpenXml;
使用DocumentFormat.OpenXml.Packaging;
使用DocumentFormat.OpenXml.Spreadsheet;
使用System.Xml;
使用System.IO;
使用系统诊断;
命名空间OpenXMLWindowsApp
{
公共类OpenXMLWindowsApp
{
public void UpdateSheet()
{
UpdateCell(“Chart.xlsx”、“20”、2、“B”);
UpdateCell(“Chart.xlsx”,“80”,3,“B”);
UpdateCell(“Chart.xlsx”、“80”、2、“C”);
UpdateCell(“Chart.xlsx”、“20”、3、“C”);
ProcessStartInfo-startInfo=新的ProcessStartInfo(“Chart.xlsx”);
startInfo.WindowStyle=ProcessWindowStyle.Normal;
进程启动(startInfo);
}
公共静态void UpdateCell(字符串docName、字符串文本、,
uint行索引,字符串列名称)
{
//打开文档进行编辑。
使用(电子表格文档电子表格=
电子表格文档。打开(docName,true))
{
工作表部件工作表部件=
GetWorksheetPartByName(电子表格,“表1”);
如果(工作表部件!=null)
{
Cell Cell=GetCell(worksheetPart.Worksheet,
列名称、行索引);
cell.CellValue=新的CellValue(文本);
cell.DataType=
新的枚举值(CellValues.Number);
//保存工作表。
worksheetPart.Worksheet.Save();
}
}
}
专用静态工作表部件
GetWorksheetPartByName(电子表格文档、,
字符串(名称)
{
可数床单=
document.WorkbookPart.Workbook.GetFirstChild()。
元素(),其中(s=>s.Name==sheetName);
如果(sheets.Count()==0)
{
//指定的工作表不存在。
返回null;
}
string relationshipId=sheets.First().Id.Value;
工作表部件工作表部件=(工作表部件)
document.WorkbookPart.GetPartById(relationshipId);
返回工作表部件;
}
//给定工作表、列名和行索引,
//获取指定列处的单元格,并
专用静态单元格GetCell(工作表,
字符串列名称,uint行索引)
{
行=GetRow(工作表,行索引);
if(行==null)
返回null;
返回row.Elements(),其中(c=>string.Compare
(c.CellReference.Value,columnName+
rowIndex,true)==0.First();
}
//给定工作表和行索引,返回该行。
私有静态行GetRow(工作表工作表,uint行索引)
{
返回工作表。GetFirstChild()。
元素(),其中(r=>r.RowIndex==RowIndex).First();
} 
}
}

我一直在使用excel,发现这个帮助程序库非常有用(我为word创建了自己的帮助程序,如果我知道这一点,至少可以节省2周时间):

这就是更新单元格(writer.PasteText(…)所需的内容:


@CDonner发布的代码抛出了一些异常,我已经添加了一些代码来处理代码,它抛出了一个异常,这里就是

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using System.Xml;
using System.IO;
using System.Diagnostics;

namespace Application.Model{
public class TempCode
{
    public TempCode()
    {
        UpdateCell("E:/Visual Studio Code/Book1.xlsx", "120", 1, "A");
        UpdateCell("E:/Visual Studio Code/Book1.xlsx", "220", 2, "B");
        UpdateCell("E:/Visual Studio Code/Book1.xlsx", "320", 3, "C");
        UpdateCell("E:/Visual Studio Code/Book1.xlsx", "420", 4, "D");
        UpdateCell("E:/Visual Studio Code/Book1.xlsx", "520", 5, "E");

        ProcessStartInfo startInfo = new ProcessStartInfo("E:/Visual Studio Code/Book1.xlsx");
        startInfo.WindowStyle = ProcessWindowStyle.Normal;
        Process.Start(startInfo);



    }

    public static void UpdateCell(string docName, string text,uint rowIndex, string columnName){
        // Open the document for editing.
        using (SpreadsheetDocument spreadSheet = SpreadsheetDocument.Open(docName, true))
        {
            WorksheetPart worksheetPart = GetWorksheetPartByName(spreadSheet, "Sheet2");
            if (worksheetPart != null)
            {
                Cell cell = GetCell(worksheetPart.Worksheet, columnName, rowIndex);
                cell.CellValue = new CellValue(text);
                cell.DataType = new EnumValue<CellValues>(CellValues.Number);
                // Save the worksheet.
                worksheetPart.Worksheet.Save();
            }
        }

    }

    private static WorksheetPart GetWorksheetPartByName(SpreadsheetDocument document, string sheetName){
        IEnumerable<Sheet> sheets =document.WorkbookPart.Workbook.GetFirstChild<Sheets>().
                        Elements<Sheet>().Where(s => s.Name == sheetName);
        if (sheets.Count() == 0){
            return null;
        }
        string relationshipId = sheets.First().Id.Value;
        WorksheetPart worksheetPart = (WorksheetPart)document.WorkbookPart.GetPartById(relationshipId);
        return worksheetPart;
    }


    private static Cell GetCell(Worksheet worksheet, string columnName, uint rowIndex)
    {
        Row row;
        string cellReference = columnName + rowIndex;
        if (worksheet.Elements<Row>().Where(r => r.RowIndex == rowIndex).Count() != 0)
            row = worksheet.GetFirstChild<SheetData>().Elements<Row>().Where(r => r.RowIndex == rowIndex).FirstOrDefault();
        else{
            row = new Row() { RowIndex = rowIndex };
            worksheet.Append(row);
        }

        if (row == null)
            return null;

        if (row.Elements<Cell>().Where(c => c.CellReference.Value == cellReference).Count() > 0) {
            return row.Elements<Cell>().Where(c => c.CellReference.Value == cellReference).First();
        }
        else{
            Cell refCell = null;
            foreach (Cell cell in row.Elements<Cell>()){
                if (string.Compare(cell.CellReference.Value, cellReference, true) > 0){
                    refCell = cell;
                    break;
                }
            }
            Cell newCell = new Cell() {
                CellReference = cellReference, 
                StyleIndex = (UInt32Value)1U

            };
            row.InsertBefore(newCell, refCell);
            worksheet.Save();
            return newCell;
        }
    }
}
使用系统;
使用System.Collections.Generic;
使用系统数据;
使用System.Linq;
使用系统文本;
使用DocumentFormat.OpenXml;
使用DocumentFormat.OpenXml.Packaging;
使用DocumentFormat.OpenXml.Spreadsheet;
使用System.Xml;
使用System.IO;
使用系统诊断;
名称空间应用程序.Model{
公共类临时代码
{
公共密码()
{
UpdateCell(“E:/Visual Studio代码/Book1.xlsx”,“120”,1,“A”);
UpdateCell(“E:/Visual Studio代码/Book1.xlsx”、“220”、2、“B”);
UpdateCell(“E:/Visual Studio代码/Book1.xlsx”、“320”、3、“C”);
UpdateCell(“E:/Visual Studio代码/Book1.xlsx”,“420”,4,“D”);
UpdateCell(“E:/Visual Studio代码/Book1.xlsx”、“520”、“5”、“E”);
ProcessStartInfo startInfo=新的ProcessStartInfo(“E:/visualstudio代码/Book1.xlsx”);
startInfo.WindowStyle=ProcessWindowStyle.Normal;
进程启动(startInfo);
}
公共静态无效更新
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using System.Xml;
using System.IO;
using System.Diagnostics;

namespace Application.Model{
public class TempCode
{
    public TempCode()
    {
        UpdateCell("E:/Visual Studio Code/Book1.xlsx", "120", 1, "A");
        UpdateCell("E:/Visual Studio Code/Book1.xlsx", "220", 2, "B");
        UpdateCell("E:/Visual Studio Code/Book1.xlsx", "320", 3, "C");
        UpdateCell("E:/Visual Studio Code/Book1.xlsx", "420", 4, "D");
        UpdateCell("E:/Visual Studio Code/Book1.xlsx", "520", 5, "E");

        ProcessStartInfo startInfo = new ProcessStartInfo("E:/Visual Studio Code/Book1.xlsx");
        startInfo.WindowStyle = ProcessWindowStyle.Normal;
        Process.Start(startInfo);



    }

    public static void UpdateCell(string docName, string text,uint rowIndex, string columnName){
        // Open the document for editing.
        using (SpreadsheetDocument spreadSheet = SpreadsheetDocument.Open(docName, true))
        {
            WorksheetPart worksheetPart = GetWorksheetPartByName(spreadSheet, "Sheet2");
            if (worksheetPart != null)
            {
                Cell cell = GetCell(worksheetPart.Worksheet, columnName, rowIndex);
                cell.CellValue = new CellValue(text);
                cell.DataType = new EnumValue<CellValues>(CellValues.Number);
                // Save the worksheet.
                worksheetPart.Worksheet.Save();
            }
        }

    }

    private static WorksheetPart GetWorksheetPartByName(SpreadsheetDocument document, string sheetName){
        IEnumerable<Sheet> sheets =document.WorkbookPart.Workbook.GetFirstChild<Sheets>().
                        Elements<Sheet>().Where(s => s.Name == sheetName);
        if (sheets.Count() == 0){
            return null;
        }
        string relationshipId = sheets.First().Id.Value;
        WorksheetPart worksheetPart = (WorksheetPart)document.WorkbookPart.GetPartById(relationshipId);
        return worksheetPart;
    }


    private static Cell GetCell(Worksheet worksheet, string columnName, uint rowIndex)
    {
        Row row;
        string cellReference = columnName + rowIndex;
        if (worksheet.Elements<Row>().Where(r => r.RowIndex == rowIndex).Count() != 0)
            row = worksheet.GetFirstChild<SheetData>().Elements<Row>().Where(r => r.RowIndex == rowIndex).FirstOrDefault();
        else{
            row = new Row() { RowIndex = rowIndex };
            worksheet.Append(row);
        }

        if (row == null)
            return null;

        if (row.Elements<Cell>().Where(c => c.CellReference.Value == cellReference).Count() > 0) {
            return row.Elements<Cell>().Where(c => c.CellReference.Value == cellReference).First();
        }
        else{
            Cell refCell = null;
            foreach (Cell cell in row.Elements<Cell>()){
                if (string.Compare(cell.CellReference.Value, cellReference, true) > 0){
                    refCell = cell;
                    break;
                }
            }
            Cell newCell = new Cell() {
                CellReference = cellReference, 
                StyleIndex = (UInt32Value)1U

            };
            row.InsertBefore(newCell, refCell);
            worksheet.Save();
            return newCell;
        }
    }
}
// Given text and a SharedStringTablePart, creates a SharedStringItem with the specified text 
// and inserts it into the SharedStringTablePart. If the item already exists, returns its index.
private static int InsertSharedStringItem(string text, SharedStringTablePart shareStringPart)
{
    // If the part does not contain a SharedStringTable, create one.
    if (shareStringPart.SharedStringTable == null)
    {
        shareStringPart.SharedStringTable = new SharedStringTable();
    }

    int i = 0;

    // Iterate through all the items in the SharedStringTable. If the text already exists, return its index.
    foreach (SharedStringItem item in shareStringPart.SharedStringTable.Elements<SharedStringItem>())
    {
        if (item.InnerText == text)
        {
            return i;
        }

        i++;
    }

    // The text does not exist in the part. Create the SharedStringItem and return its index.
    shareStringPart.SharedStringTable.AppendChild(new SharedStringItem(new Text(text)));
    shareStringPart.SharedStringTable.Save();

    return i;
}
SharedStringTablePart shareStringPart = GetSharedStringTablePart(excelDoc);

// Insert the text into the SharedStringTablePart.
int index = InsertSharedStringItem(cellValue, shareStringPart);

// Set the value of cell A1.
cell.CellValue = new CellValue(index.ToString());
cell.DataType = new EnumValue<CellValues>(CellValues.SharedString);
if (worksheet.GetFirstChild<SheetData>().Elements<Row>().Where(r => r.RowIndex == rowIndex).Count() != 0)
if (worksheet.Elements<Row>().Where(r => r.RowIndex == rowIndex).Count() != 0)
if (string.Compare(cell.CellReference.Value, cellReference, true) > 0)
private static int ColumnIndex(string reference)
    {
        int ci = 0;
        reference = reference.ToUpper();
        for (int ix = 0; ix < reference.Length && reference[ix] >= 'A'; ix++)
            ci = (ci * 26) + ((int)reference[ix] - 64);
        return ci;
    }
string columnNew = new String(cellReference.Where(c => c != '-' && (c < '0' || c > '9')).ToArray());
            foreach (Cell cell in row.Elements<Cell>())
            {
                string columnBase = new String(cell.CellReference.Value.Where(c => c != '-' && (c < '0' || c > '9')).ToArray());

                if (ColumnIndex(columnBase) > ColumnIndex(columnNew))
                {
                    refCell = cell;
                    break;
                }
            }
var sheetData = new SheetData();
var row = UpdateCell("A","Hello World", 5);
sheetData.Append(row);
worksheet.Append(sheetData);

private static Row UpdateCell(string columnName, string value, int rowIndex)
{
       Row row = new Row { RowIndex = (uint)rowIndex };
       Cell  c1 = new TextCell(columnName, value, rowIndex);
       row.Append(c1);
       return row;            
}


public class TextCell : Cell
{
    public TextCell(string header, string text, int index)
    {
        this.DataType = CellValues.InlineString;
        this.CellReference = header + index;
        //Add text to the text cell.
        this.InlineString = new InlineString { Text = new Text { Text = text } };
    }
}