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`。然后,我们将单元格的公式移除,以确保只保留数值。最后,我们保存对工作表所做的更改。

相关推荐
淡海水7 小时前
09-04-内存-Unity原生对象生命周期
unity·c#·游戏引擎·gc
吴可可12310 小时前
富怡CAD二次开发指南
c#
1-1=010 小时前
C# IO和序列化
c#·.net·.netcore
寂寞的船12 小时前
【Unity Bug挑战】第10期 SerializeReference 内存泄漏之谜
unity·c#·游戏引擎·bug
CSharp精选营12 小时前
从控制台到「会动手」的 AI:用 Semantic Kernel 搭应用(小白教程)
c#·.net·ai agent·semantickernel·functioncalling
宝桥南山1 天前
.NET 11 - 尝试一下Blazor中的新特性SupplyParameterFromTempData
microsoft·微软·c#·asp.net·.net·.netcore
1-1=01 天前
C# 中 Lambda、Linq 与 Expression
c#·linq
zhanghaha13141 天前
C# 系列教程_7 判断语句(分支)保姆级精讲
开发语言·c#
zhanghaha13142 天前
C# 系列教程_8 循环语句 保姆级精讲(面向新手)
开发语言·c#
rockey6272 天前
AScript之LINQ扩展
c#·.net·script·动态脚本