use*_*569 2 excel openxml openxml-sdk
我正在开发一个可重用的代码来读取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;
}
Run Code Online (Sandbox Code Playgroud)
我从下面的代码块调用此方法:
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")
}
}
Run Code Online (Sandbox Code Playgroud)
该方法不返回某些单元格的实际值.对于某些单元格,它返回值,对于某些单元格,它返回内部文本.我进行了调查并检查了一下
var stringTable = worksheetPart.GetPartsOfType<SharedStringTablePart>()
.FirstOrDefault();
Run Code Online (Sandbox Code Playgroud)
上面的代码返回null.
我无法找到为什么它适用于某些细胞而不适用于某些细胞.任何有助于解决此问题.
根据我的理解(至少,对于我已经检查过的文档,它是真的),SharedStringTablePart是WorkbookPart的后代而不是WorksheetPart.因此,修复代码的方法是从IsPackingListValid()方法中获取wbPart中的共享字符串列表:
List<SharedStringItem> sharedStrings = wbPart.SharedStringTablePart.SharedStringTable.ChildElements.OfType<SharedStringItem>().ToList();
Run Code Online (Sandbox Code Playgroud)
然后将其作为附加参数传递给ReadCellValue方法:
return ReadCellValue(worksheetPart, "B2", sharedStrings);
Run Code Online (Sandbox Code Playgroud)
之后,您可以在ReadCellValue()方法中获取交换机内部共享字符串的实际值:
value = cell.InnerText;
int sharedStringIndex;
if (int.TryParse(cell.InnerText, out sharedStringIndex) && sharedStrings.Count > sharedStringIndex
&& sharedStrings[sharedStringIndex].Text != null)
{
value = sharedStrings[sharedStringIndex].Text.Text;
}
Run Code Online (Sandbox Code Playgroud)