openxml对worksheet数值化

如果您想要将单元格中的公式直接替换为其计算后的数值,可以使用 OpenXML SDK 的 `CellValue` 属性来获取计算后的数值。以下是修改后的代码:

cs 复制代码
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using System;

public class ExcelParser
{
    public static void ParseExcel(string filePath)
    {
        using (SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Open(filePath, true))
        {
            WorkbookPart workbookPart = spreadsheetDocument.WorkbookPart;
            WorksheetPart worksheetPart = workbookPart.WorksheetParts.FirstOrDefault();

            if (worksheetPart != null)
            {
                Worksheet worksheet = worksheetPart.Worksheet;
                SharedStringTable sharedStringTable = workbookPart.SharedStringTablePart.SharedStringTable;

                foreach (var cell in worksheet.Descendants<Cell>())
                {
                    if (cell.CellFormula != null)
                    {
                        // 计算单元格公式并将计算结果设置为单元格的值
                        cell.CellValue = new CellValue(ComputeCellValue(cell, sharedStringTable).ToString());
                        cell.CellFormula.Remove();
                    }
                }

                worksheetPart.Worksheet.Save();
            }
        }
    }

    private static object ComputeCellValue(Cell cell, SharedStringTable sharedStringTable)
    {
        if (cell.DataType != null && cell.DataType.Value == CellValues.SharedString)
        {
            int index = int.Parse(cell.InnerText);
            return sharedStringTable.ChildElements[index].InnerText;
        }
        else
        {
            return cell.InnerText;
        }
    }
}

在此代码中,我们检查单元格是否包含公式 (`cell.CellFormula != null`)。如果是,则调用 `ComputeCellValue` 方法来计算公式的值,并将其设置为单元格的 `CellValue`。然后,我们将单元格的公式移除,以确保只保留数值。最后,我们保存对工作表所做的更改。

相关推荐
晨星shine3 天前
GC、Dispose、Unmanaged Resource 和 Managed Resource
后端·c#
用户298698530144 天前
.NET 文档自动化:Spire.Doc 设置奇偶页页眉/页脚的最佳实践
后端·c#·.net
用户3667462526744 天前
接口文档汇总 - 2.设备状态管理
c#
用户3667462526744 天前
接口文档汇总 - 3.PLC通信管理
c#
Ray Liang5 天前
用六边形架构与整洁架构对比是伪命题?
java·python·c#·架构设计
Scout-leaf8 天前
WPF新手村教程(三)—— 路由事件
c#·wpf
用户298698530148 天前
程序员效率工具:Spire.Doc如何助你一键搞定Word表格排版
后端·c#·.net
mudtools9 天前
搭建一套.net下能落地的飞书考勤系统
后端·c#·.net
玩泥巴的9 天前
搭建一套.net下能落地的飞书考勤系统
c#·.net·二次开发·飞书
唐宋元明清21889 天前
.NET 本地Db数据库-技术方案选型
windows·c#