簡體   English   中英

如何在C#中使用OpenXML讀取Excel的空白單元格列值

[英]How to read blank cell column value of excel using OpenXML in C#

在我的Execl工作表中,有一些空白值列單元格,因此當我使用此代碼時,出現錯誤“對象引用未設置為對象的實例”。

foreach (Row row in rows)
{
   DataRow dataRow = dataTable.NewRow();
   for (int i = 0; i < row.Descendants<Cell>().Count(); i++)
   {
        dataRow[i] = GetCellValue(spreadSheetDocument, row.Descendants<Cell>().ElementAt(i));
   }

   dataTable.Rows.Add(dataRow);
}

private static string GetCellValue(SpreadsheetDocument document, Cell cell)
{
    SharedStringTablePart stringTablePart = document.WorkbookPart.SharedStringTablePart;

    string value = cell.CellValue.InnerXml;

    if (cell.DataType != null && cell.DataType.Value == CellValues.SharedString)
    {
        return stringTablePart.SharedStringTable.ChildElements[Int32.Parse(value)].InnerText;
    }
    else
    {
        return value;
    }
}

“ CellValue”不一定存在。 在您的情況下,它為“ null”,因此會出現錯誤。 讀取空白單元格:

如果您不想根據單元格包含的內容格式化結果,請嘗試

private static string GetCellValue(Cell cell)
{
    return cell.InnerText;
}

如果要在返回值之前格式化單元格

private static string GetCellValue(SpreadsheetDocument doc, Cell cell)
{
    // if no dataType, return the value of the innerText of the cell
    if (cell.DataType == null) return cell.InnerText;

    // depending type of the cell
    switch (cell.DataType.Value)
    {
        // string => search for CellValue
        case CellValues.String:
            return cell.CellValue != null ? cell.CellValue.Text : string.Empty;

        // inlineString => search of InlineString
        case CellValues.InlineString:
            return cell.InlineString != null ? cell.InlineString.Text.Text : string.Empty;

        // sharedString => search for the SharedString
        case CellValues.SharedString:
            // is sharedPart exist ?
            if (doc.WorkbookPart.SharedStringTablePart == null) doc.WorkbookPart.SharedStringTablePart = new SharedStringTablePart();
            // is the text exist ?
            foreach (SharedStringItem item in doc.WorkbookPart.SharedStringTablePart.SharedStringTable.Elements<SharedStringItem>())
            {
                // the text exist, return it from SharedStringTable
                if (item.InnerText == cell.InnerText) return cell.InnerText;
            }
            // no text in sharedStringTable, create it and return it
            doc.WorkbookPart.SharedStringTablePart.SharedStringTable.Append(new SharedStringItem(new DocumentFormat.OpenXml.Spreadsheet.Text(cell.InnerText)));
            doc.WorkbookPart.SharedStringTablePart.SharedStringTable.Save();
            return cell.InnerText;

        // default case : bool / number / date
        // return the value of the cell in plain text
        // you can parse types depending your needs
        default:
            return cell.InnerText;
    }
}

兩個有用的文檔:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM