我无法确定Cell是一个约会.
我注意到DataType为null所以我无法区分它是否是一个日期的数字.
我正在使用下一个代码来提取单元格:
WorksheetPart worksheetPart = (WorksheetPart)workbookPart.GetPartById(worksheetId);
SheetData sheetData = worksheetPart.Worksheet.GetFirstChild<SheetData>();
Row[] rows = worksheetPart.Worksheet.Descendants<Row>().ToArray();
for (int i = 0; i < rows.Length; i++)
{
List<Cell> cells = rows[i].Elements<Cell>().ToList();
foreach (var cell in cells)
{
if (cell.DataType != null && cell.DataType.Value == CellValues.Date)
//this line is not hit for some reason
}
}
}
Run Code Online (Sandbox Code Playgroud)
我错过了什么吗?
简而言之,它是null,因为它应该是数字和日期类型.
msdn上的 OpenXML文档
对于数字和日期类型,DataType属性的值为null.它包含字符串的值CellValues.SharedString和布尔值的CellValues.Boolean.
有一种方法可以使用CellFormat上的NumberFormatId来区分日期和数字单元格格式.诀窍是找到什么id映射到什么格式.您可以通过创建新的Excel文件并将单元格设置为相关格式(即日期)来找出要使用的格式:
然后使用7zip提取excel文件并查看xl/styles.xml文件:
在上图中,您可以看到此格式Id 14转换为短日期.有关格式的完整列表,请参阅Office Open XML格式的ECMA-376文档(表格应隐藏在第4部分的某处).
我为最常见的formatIds创建了一个枚举:
private enum Formats
{
General = 0,
Number = 1,
Decimal = 2,
Currency = 164,
Accounting = 44,
DateShort = 14,
DateLong = 165,
Time = 166,
Percentage = 10,
Fraction = 12,
Scientific = 11,
Text = 49
}
Run Code Online (Sandbox Code Playgroud)
然后,您可以创建一个帮助函数,以您希望的方式获得格式化的值:
private static string GetFormattedCellValue(WorkbookPart workbookPart, Cell cell)
{
if (cell == null)
{
return null;
}
string value = "";
if (cell.DataType == null) // number & dates
{
int styleIndex = (int)cell.StyleIndex.Value;
CellFormat cellFormat = (CellFormat)workbookPart.WorkbookStylesPart.Stylesheet.CellFormats.ElementAt(styleIndex);
uint formatId = cellFormat.NumberFormatId.Value;
if (formatId == (uint)Formats.DateShort || formatId == (uint)Formats.DateLong)
{
double oaDate;
if (double.TryParse(cell.InnerText, out oaDate))
{
value = DateTime.FromOADate(oaDate).ToShortDateString();
}
}
else
{
value = cell.InnerText;
}
}
else // Shared string or boolean
{
switch (cell.DataType.Value)
{
case CellValues.SharedString:
SharedStringItem ssi = workbookPart.SharedStringTablePart.SharedStringTable.Elements<SharedStringItem>().ElementAt(int.Parse(cell.CellValue.InnerText));
value = ssi.Text.Text;
break;
case CellValues.Boolean:
value = cell.CellValue.InnerText == "0" ? "false" : "true";
break;
default:
value = cell.CellValue.InnerText;
break;
}
}
return value;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2912 次 |
| 最近记录: |