我正在使用Open XML SDK打开Excel xlsx文件,并尝试读取每张纸上位置A1上的单元格值。我使用以下代码:
using (SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Open(openFileDialog1.FileName, false)) { var sheets = spreadsheetDocument.WorkbookPart.Workbook.Descendants<Sheet>(); foreach (Sheet sheet in sheets) { WorksheetPart worksheetPart = (WorksheetPart)spreadsheetDocument.WorkbookPart.GetPartById(sheet.Id); Worksheet worksheet = worksheetPart.Worksheet; Cell cell = GetCell(worksheet, "A", 1); Console.Writeline(cell.CellValue.Text); } } private static Cell GetCell(Worksheet worksheet, string columnName, uint rowIndex) { Row row = GetRow(worksheet, rowIndex); if (row == null) return null; return row.Elements<Cell>().Where(c => string.Compare (c.CellReference.Value, columnName + rowIndex, true) == 0).First(); } // Given a worksheet and a row index, return the row. private static Row GetRow(Worksheet worksheet, uint rowIndex) { return worksheet.GetFirstChild<SheetData>(). Elements<Row>().Where(r => r.RowIndex == rowIndex).First(); }
第一个工作表中位置A1上的文本只是“测试”,但是在我的控制台中,我看到值“ 0”为cell.CellValue.Text
有没有人有一个想法来获得正确的细胞价值?
Excel工作表中的所有字符串都存储在类似SharedStringTable的数组中。该表的目标是将所有字符串集中在基于索引的数组中,然后在文档中多次使用该字符串以仅引用此数组中的索引的情况。就是说,当您获得A1单元格的文本值时收到的0是SharedStringTable的索引。要获得真正的价值,您可以使用以下帮助函数:
public static SharedStringItem GetSharedStringItemById(WorkbookPart workbookPart, int id) { return workbookPart.SharedStringTablePart.SharedStringTable.Elements<SharedStringItem>().ElementAt(id); }
然后在您的代码中像这样调用它以获取实际价值:
Cell cell = GetCell(worksheet, "A", 1); string cellValue = string.Empty; if (cell.DataType != null) { if (cell.DataType == CellValues.SharedString) { int id = -1; if (Int32.TryParse(cell.InnerText, out id)) { SharedStringItem item = GetSharedStringItemById(workbookPart, id); if (item.Text != null) { cellValue = item.Text.Text; } else if (item.InnerText != null) { cellValue = item.InnerText; } else if (item.InnerXml != null) { cellValue = item.InnerXml; } } } }