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 中显示的值而不是存储的数值。

相关推荐
2601_9498146921 小时前
如何使用C#与SQL Server数据库进行交互
数据库·c#·交互
CSharp精选营1 天前
C#事务处理最佳实践:别再让“主表存了、明细丢了”的破事发生
c#·try-catch·事务处理·transactionscope
加号31 天前
C# 基于MD5实现密码加密功能,附源码
开发语言·c#·密码加密
weixin_520649871 天前
C#闭包知识点详解
开发语言·c#
NQBJT1 天前
[特殊字符] VS Code + Markdown 从入门到精通:写论文、技术文档的超实用指南
开发语言·vscode·c#·markdown
努力长头发的程序猿1 天前
Unity2D当中的A*寻路算法
算法·unity·c#
xiaoshuaishuai82 天前
C# Codex 脚本编写
java·服务器·数据库·c#
weixin_447443252 天前
AI启蒙Lean4
python·c#
我是唐青枫2 天前
C#.NET ValueTaskSource 深入解析:零分配异步、ManualResetValueTaskSourceCore 与使用边界
c#·.net
iCxhust2 天前
C#程序,窗体1向窗体2的textbox控件写入字符串“hello”
开发语言·c#