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

后端 未结 6 1796
我寻月下人不归
我寻月下人不归 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:32

    I made some changes on @AZ code.

    First, on GetCell function there is a problem on selecting the current row. Just change:

    if (worksheet.GetFirstChild().Elements().Where(r => r.RowIndex == rowIndex).Count() != 0)
    

    instead of:

    if (worksheet.Elements().Where(r => r.RowIndex == rowIndex).Count() != 0)
    

    And in the section:

    if (string.Compare(cell.CellReference.Value, cellReference, true) > 0)
    

    If you are using Columns above Z Column (as AA column, for example) will not work properly. To some this, I'm using the column numbers to determinate where insert the Cell.

    For this, I created a function ColumnIndex, with convert the column letters to numbers:

    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;
        }
    

    So I changed the string compare function for this:

    string columnNew = new String(cellReference.Where(c => c != '-' && (c < '0' || c > '9')).ToArray());
                foreach (Cell cell in row.Elements())
                {
                    string columnBase = new String(cell.CellReference.Value.Where(c => c != '-' && (c < '0' || c > '9')).ToArray());
    
                    if (ColumnIndex(columnBase) > ColumnIndex(columnNew))
                    {
                        refCell = cell;
                        break;
                    }
                }
    

    Best Regards.

提交回复
热议问题