【发布时间】:2014-12-29 19:31:25
【问题描述】:
我正在开发一个可重复使用的代码来读取 excel 单元格值。我的代码如下:
private string ReadCellValue(WorksheetPart worksheetPart, string cellAddress)
{
string value = null;
Cell theCell = worksheetPart.Worksheet.Descendants<Cell>().
Where(c => c.CellReference == cellAddress).FirstOrDefault();
// If the cell does not exist, return an empty string.
if (theCell != null)
{
value = theCell.InnerText;
if (theCell.DataType != null)
{
switch (theCell.DataType.Value)
{
case CellValues.SharedString:
var stringTable =
worksheetPart.GetPartsOfType<SharedStringTablePart>()
.FirstOrDefault();
if (stringTable != null)
{
value =
stringTable.SharedStringTable
.ElementAt(int.Parse(value)).InnerText;
}
break;
case CellValues.Boolean:
switch (value)
{
case "0":
value = "FALSE";
break;
default:
value = "TRUE";
break;
}
break;
}
}
}
return value;
}
我从下面的代码块调用这个方法:
public string IsPackingListValid()
{
// Open the spreadsheet document for read-only access.
using (SpreadsheetDocument document = SpreadsheetDocument.Open(fileName, false))
{
// Retrieve a reference to the workbook part.
WorkbookPart wbPart = document.WorkbookPart;
// Find the sheet with the supplied name, and then use that
// Sheet object to retrieve a reference to the first worksheet.
Sheet theSheet = wbPart.Workbook.Descendants<Sheet>().
Where(s => s.Name == sheetName).FirstOrDefault();
// Throw an exception if there is no sheet.
if (theSheet == null)
{
throw new ArgumentException("Could not find work sheet: " + sheetName);
}
// Retrieve a reference to the worksheet part.
WorksheetPart worksheetPart = (WorksheetPart)(wbPart.GetPartById(theSheet.Id));
return ReadCellValue(WorksheetPart worksheetPart, "B2")
}
}
该方法不返回某些单元格的实际值。对于某些单元格,它返回值,对于某些单元格,它返回内部文本。 我调试并检查了
var stringTable = worksheetPart.GetPartsOfType<SharedStringTablePart>()
.FirstOrDefault();
以上代码返回null。
我找不到为什么它对某些单元有效而对某些单元无效。任何有助于解决此问题。
【问题讨论】:
标签: excel openxml openxml-sdk