Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace text in textbox in Excel using openXML

Tags:

c#

openxml

I want to edit/change the text in an excel sheet which is in a textbox. I iterate through all entries in the sharedstringtable but I cannot find it.

var sharedStringTablePart = spreadSheet.WorkbookPart.GetPartsOfType<SharedStringTablePart>().First();
foreach (SharedStringItem ss in sharedStringTablePart.SharedStringTable.Elements<SharedStringItem>())
{
    if (ss.InnerText == text)
    {
        //Do somethinhg
    }
}

Can someone help?

like image 717
Andrej Zima Avatar asked Jul 30 '26 12:07

Andrej Zima


1 Answers

Text contained within a textbox is not stored under a sharedstringtable (I know it is confusing). Hope this helps:

using (SpreadsheetDocument document = SpreadsheetDocument.Open(excelFile, true))
{
    string sheetName = "Sheet1";
    Sheet sheet = document.WorkbookPart.Workbook.GetFirstChild<Sheets>().Elements<Sheet>().Where(s => s.Name == sheetName).FirstOrDefault();

    if (sheet == null)
    {
        // The specified worksheet does not exist.
        return null;
    }

    string relationshipId = sheet.Id.Value;

    WorksheetPart worksheetPart = (WorksheetPart)document.WorkbookPart.GetPartById(relationshipId);
    var ocaElems = worksheetPart.DrawingsPart.WorksheetDrawing.Elements<OneCellAnchor>();

    foreach (OneCellAnchor oneCellAnchor in ocaElems)
    {
        var shapes = oneCellAnchor.Elements<A.Shape>();
        foreach (var shape in shapes)
        {
            var text = shape.TextBody.InnerText;
            if(text == mytext)
            {
                //You found the text
            }
        }
    }
}
like image 105
FortyTwo Avatar answered Aug 02 '26 04:08

FortyTwo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!