Open XML SDK 2.0 - how to update a cell in a spreadsheet?

后端 未结 6 1912
我寻月下人不归
我寻月下人不归 2020-11-30 20:50

I want to update a cell in a spreadsheet that is used by a chart, using the Open XML SDK 2.0 (CTP). All the code samples I have found insert new cells. I am struggling with

6条回答
  •  春和景丽
    2020-11-30 21:18

    This is SDK 2.5 though, however, was very useful code found here: http://fczaja.blogspot.dk/2013/05/how-to-read-and-write-excel-cells-with.html

    Needed to do a slight modification for text values to add them to the SharedStringTablePart.

    // 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())
        {
            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;
    }
    

    And use it like this:

    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.SharedString);
    

提交回复
热议问题