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

相关推荐
csdn_aspnet1 小时前
C# DataGridView 选中所有复选框
c#·winform·datagridview
qq_297908013 小时前
c#车检车构客户管理系统软件车辆年审短信提醒软件
sqlserver·c#·开源软件
酷炫码神4 小时前
C#数组与集合
开发语言·c#
钢铁男儿5 小时前
C# 深入理解类(静态函数成员)
java·开发语言·c#
CoderIsArt13 小时前
参数系统的基类Parameter抽象类
c#
盛夏绽放15 小时前
Python字符串常用方法详解
开发语言·python·c#
Tummer836319 小时前
C#+WPF+prism+materialdesign创建工具主界面框架
开发语言·c#·wpf
ghost14319 小时前
C#学习第23天:面向对象设计模式
开发语言·学习·设计模式·c#
yngsqq20 小时前
(for 循环) VS (LINQ) 性能比拼 ——c#
c#·solr·linq
想做后端的小C21 小时前
C# 面向对象 构造函数带参无参细节解析
开发语言·c#·面向对象