如何在现有Cell中插入文本?

时间:2015-10-29 04:04:12

标签: c# openxml

我试图通过OpenXml在现有单元格中插入文本,但它没有反映excel表格,请帮助我!

    static void InsertTextInCell(WorkbookPart wbPart, string sheetName)
    {
        Sheet theSheet = wbPart.Workbook.Descendants<Sheet>().
                  Where(s => s.Name == sheetName).FirstOrDefault();
        WorksheetPart wsPart =
        (WorksheetPart)(wbPart.GetPartById(theSheet.Id));
        Cell theCell = wsPart.Worksheet.Descendants<Cell>().
                  Where(c => c.CellReference == "A8").FirstOrDefault();
        CellValue cellValue2 = new CellValue();
        cellValue2.Text = "1test";
        theCell.Append(cellValue2);
    }

.yaml

谢谢,

萨兰

2 个答案:

答案 0 :(得分:0)

您可以参考以下代码段在excel中插入文本

 // Creates an SheetData instance and adds its children.
    public SheetData GenerateSheetData()
    {
        SheetData sheetData1 = new SheetData();

        Row row1 = new Row(){ RowIndex = (UInt32Value)1U, Spans = new ListValue<StringValue>() { InnerText = "1:1" } };

        Cell cell1 = new Cell(){ CellReference = "A1", DataType = CellValues.SharedString };
        CellValue cellValue1 = new CellValue();
        cellValue1.Text = "0";

        cell1.Append(cellValue1);

        row1.Append(cell1);

        Row row2 = new Row(){ RowIndex = (UInt32Value)2U, Spans = new ListValue<StringValue>() { InnerText = "1:1" } };

        Cell cell2 = new Cell(){ CellReference = "A2", DataType = CellValues.SharedString };
        CellValue cellValue2 = new CellValue();
        cellValue2.Text = "1";

        cell2.Append(cellValue2);

        row2.Append(cell2);

        sheetData1.Append(row1);
        sheetData1.Append(row2);
        return sheetData1;
    }

答案 1 :(得分:0)

    static void InsertTextInCell(WorkbookPart wbPart, string sheetName, string addressName)
    {
        Sheet theSheet = wbPart.Workbook.Descendants<Sheet>().
                  Where(s => s.Name == sheetName).FirstOrDefault();
        WorksheetPart wsPart =
        (WorksheetPart)(wbPart.GetPartById(theSheet.Id));
        Cell theCell = wsPart.Worksheet.Descendants<Cell>().
                  Where(c => c.CellReference == addressName).FirstOrDefault();

        if (theCell.DataType == null)
        {
            theCell.CellValue = new CellValue("AddString");
        }
    }
相关问题