使用Open XML读取Excel带百分号数值异常:100%读出为1求助
问题原因
Excel中百分比格式的单元格实际存储的是数值:比如显示为100%的单元格,背后存储的原始值是1;显示50%的单元格存储的是0.5。你当前的代码读取的是单元格的原始存储值,而非Excel格式化后的显示文本,所以得到1。
解决方案
要获取格式化后的100%,需要读取单元格的格式信息,判断是否为百分比格式,再将原始数值转换为百分比字符串。
步骤1:添加获取单元格格式代码的辅助方法
private static string GetCellFormatCode(SpreadsheetDocument doc, Cell cell) { if (cell.StyleIndex == null) return null; var stylesPart = doc.WorkbookPart.WorkbookStylesPart; var cellStyle = stylesPart.Stylesheet.CellStyles.ChildElements[(int)cell.StyleIndex.Value] as CellStyle; if (cellStyle == null) return null; var formatId = cellStyle.FormatId.Value; var numberingFormats = stylesPart.Stylesheet.NumberingFormats?.ChildElements.OfType<NumberingFormat>(); if (numberingFormats == null) return null; var numberingFormat = numberingFormats.FirstOrDefault(nf => nf.NumberFormatId.Value == formatId); return numberingFormat?.FormatCode; }
步骤2:修改GetCellValue方法,加入百分比格式处理
public static string GetCellValue(SpreadsheetDocument doc, Cell cell) { if (cell.CellValue == null) return string.Empty; string value = cell.CellValue.InnerText; // 处理共享字符串类型 if (cell.DataType != null && cell.DataType.Value == CellValues.SharedString) { return doc.WorkbookPart.SharedStringTablePart.SharedStringTable.ChildElements.ElementAt(int.Parse(value)).InnerText; } // 处理数值类型(含百分比) if (cell.DataType == null || cell.DataType.Value == CellValues.Number) { var formatCode = GetCellFormatCode(doc, cell); // 判断是否为百分比格式 if (!string.IsNullOrEmpty(formatCode) && formatCode.Contains("%")) { if (double.TryParse(value, out double numValue)) { // 根据格式调整小数位数:比如N0对应无小数,N2对应两位小数 return $"{numValue * 100:N0}%"; } } // 非百分比数值直接返回原始值 return value; } // 其他数据类型直接返回 return value; }
注意事项
- 上述代码针对常见的百分比格式(如
0%、0.00%)做了处理,若需要适配更多自定义百分比格式,可以解析FormatCode字符串来调整格式化逻辑。 - 如果需要处理更多Excel格式(如货币、日期),可以扩展该方法的格式判断和转换逻辑。
内容的提问来源于stack exchange,提问作者Niranjan
相关产品推荐
相关产品推荐

