Userexcel 单元格中序号,但是通过openxml获取的不是序号是数字?

OpenXML 是一种用于读写 Office 文件(包括 Excel)的开放式标准。如果你通过 OpenXML 获取到的 Excel 单元格中的内容是数字而不是序号,可能是因为 Excel 中的序号实际上是一种显示格式,而不是存储的数值。OpenXML 读取的是实际存储的数值,而不会执行 Excel 中的格式化。

如果你想获取 Excel 单元格中的显示值,可以考虑使用 Cell.CellValue 属性。以下是一个示例代码,演示如何通过 OpenXML 获取 Excel 单元格的显示值:

cs 复制代码
using (SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Open("YourExcelFile.xlsx", false))
{
    WorkbookPart workbookPart = spreadsheetDocument.WorkbookPart;
    WorksheetPart worksheetPart = workbookPart.WorksheetParts.First(); // 假设只有一个工作表

    // 选择要读取的单元格
    Cell cell = worksheetPart.Worksheet.Descendants<Cell>().FirstOrDefault(c => c.CellReference == "A1");

    if (cell != null)
    {
        string displayValue = cell.InnerText;

        // 如果单元格具有共享字符串,则进一步处理
        if (cell.DataType != null && cell.DataType.Value == CellValues.SharedString)
        {
            int sharedStringIndex = int.Parse(displayValue);
            SharedStringTablePart sharedStringTablePart = workbookPart.SharedStringTablePart;
            string sharedStringValue = sharedStringTablePart.SharedStringTable.Elements<SharedStringItem>().ElementAt(sharedStringIndex).InnerText;
            Console.WriteLine("Display Value (Shared String): " + sharedStringValue);
        }
        else
        {
            Console.WriteLine("Display Value (Number): " + displayValue);
        }
    }
}

在上述代码中,我们通过 cell.InnerText 获取了单元格的显示值。如果这是一个共享字符串,我们还从共享字符串表中获取了实际的字符串值。这样,你可以确保获取到的是 Excel 中显示的值而不是存储的数值。

相关推荐
2401_885885045 小时前
国际语音C#接口怎么写?.NET环境下实现国际语音验证码批量下发
开发语言·c#·.net
淡海水11 小时前
07-03-源码-.NET Core GC标记与扫描
unity·c#·.netcore·gc
波力海苔夹心脆67511 小时前
C# string 字符串方法大全:判空、查找、截取、分割、替换一篇讲透
经验分享·c#·.net·字符串·string·入门教程
阿松爱学习1 天前
【Unity开发】Unity长截图功能实现
unity·c#·游戏引擎
_oP_i1 天前
Windows 11 家庭中文版 25H2
c#
unicrom_深圳市由你创科技1 天前
电池化成曲线MES追溯:关键点提取与验证
c#
老王IT1 天前
C#语言基础语法介绍
开发语言·c#
人丰1 天前
一次生产卡顿复盘:BI 数据抽取引发 PostgreSQL 长事务事故
数据库·c#
淡海水1 天前
07-01-源码-.NET Core GC总览与架构
unity·架构·c#·.netcore·gc
weixin_416660071 天前
Mermaid流程图导出到Word:SVG、PNG与清晰度如何选择?
开发语言·c#