From Excel to DataTable in C# with Open XML

前端 未结 7 2173
暖寄归人
暖寄归人 2020-11-29 00:29

I\'m using Visual Studio 2008 and I need create a DataTable from a Excel Sheet using the Open XML SDK 2.0. I need to create it with the DataTable columns with t

7条回答
  •  时光取名叫无心
    2020-11-29 01:07

    This solution works for spreadsheets without empty cells.

    To handle empty cells, you will need to replace this line:

    tempRow[i] = GetCellValue(spreadSheetDocument, row.Descendants().ElementAt(i-1));
    

    with something like this:

    Cell cell = row.Descendants().ElementAt(i);
    int index = CellReferenceToIndex(cell);
    tempRow[index] = GetCellValue(spreadSheetDocument, cell);
    

    And add this method:

    private static int CellReferenceToIndex(Cell cell)
    {
        int index = -1;
        string reference = cell.CellReference.ToString().ToUpper();
        foreach (char ch in reference)
        {
            if (Char.IsLetter(ch))
            {
                int value = (int)ch - (int)'A';
                index = (index + 1) * 26 + value;
            }
            else
                return index;
        }
        return index;
    }
    

提交回复
热议问题