Skip to content

fomula bug #860

Closed as duplicate
Closed as duplicate

Description

@k1k-xxsc

Excel Type

  • XLSX

MiniExcel Version

latest

Description

template is like $={{f.PurchasRule_AdditionalDeposit}}/10000
gen file is like $=10000000/10000,not =10000000/10000,can you move $ automatic

Activity

  1. k1k-xxsc commented on Aug 26, 2025

    @k1k-xxsc
    ContributorAuthor

    This is a temporary alternative solution.

    public class XlsxFormulaConverter
    {
    public static void MakeFormula(string xlsxPath)
    {
    if (string.IsNullOrEmpty(xlsxPath) || !File.Exists(xlsxPath))
    {
    throw new ArgumentException("Invalid XLSX file path");
    }

        string tempDir = Path.Combine(Path.GetTempPath(), "XlsxConverter_" + Guid.NewGuid().ToString());
    
        try
        {
            // 解压XLSX文件
            ZipFile.ExtractToDirectory(xlsxPath, tempDir);
    
            // 处理所有工作表
            string worksheetsDir = Path.Combine(tempDir, "xl", "worksheets");
            if (Directory.Exists(worksheetsDir))
            {
                foreach (string file in Directory.GetFiles(worksheetsDir, "*.xml"))
                {
                    ProcessWorksheetFile(file);
                }
            }
    
            // 修改工作簿设置,确保Excel打开时重新计算公式
            UpdateWorkbookForRecalculation(tempDir);
    
            // 创建输出文件名
            string outputFile = Path.Combine(
                Path.GetDirectoryName(xlsxPath)!,
                Path.GetFileNameWithoutExtension(xlsxPath) +
                "_converted" +
                Path.GetExtension(xlsxPath));
    
            // 删除已存在的输出文件
            if (File.Exists(outputFile))
            {
                File.Delete(outputFile);
            }
    
            // 重新压缩为XLSX文件
            ZipFile.CreateFromDirectory(tempDir, outputFile);
    
            Console.WriteLine($"Conversion completed. Output file: {outputFile}");
        }
        finally
        {
            // 清理临时文件
            if (Directory.Exists(tempDir))
            {
                Directory.Delete(tempDir, true);
            }
        }
    }
    
    private static void ProcessWorksheetFile(string filePath)
    {
        try
        {
            // 读取XML内容
            XNamespace ns = "http://schemas.openxmlformats.org/spreadsheetml/2006/main";
            XDocument doc = XDocument.Load(filePath);
    
            // 查找所有包含$=的单元格
            var cells = doc.Descendants(ns + "c");
            bool modified = false;
    
            foreach (var cell in cells)
            {
                // 获取单元格的值
                var valueElement = cell.Element(ns + "v");
                var formulaElement = cell.Element(ns + "f");
    
                // 处理情况1: 单元格有值且以$=开头
                if (valueElement != null && valueElement.Value.StartsWith("$="))
                {
                    // 提取公式部分
                    string formula = valueElement.Value.Substring(1); // 去掉$符号,保留=开头
    
                    // 移除原有的值元素
                    valueElement.Remove();
    
                    // 添加公式元素
                    cell.Add(new XElement(ns + "f", formula));
    
                    // 添加特殊计算值,使Excel重新计算
                    cell.Add(new XElement(ns + "v", "#CALC!"));
    
                    modified = true;
                }
              
            }
    
            // 只有当内容确实发生变化时才保存文件
            if (modified)
            {
                doc.Save(filePath);
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error processing worksheet {Path.GetFileName(filePath)}: {ex.Message}");
            throw; // 重新抛出异常以便上层处理
        }
    }
    
    private static void UpdateWorkbookForRecalculation(string tempDir)
    {
        try
        {
            string workbookPath = Path.Combine(tempDir, "xl", "workbook.xml");
            if (!File.Exists(workbookPath))
            {
                Console.WriteLine("Workbook.xml not found, skipping recalculation settings.");
                return;
            }
    
            // 读取workbook.xml
            XNamespace ns = "http://schemas.openxmlformats.org/spreadsheetml/2006/main";
            XDocument doc = XDocument.Load(workbookPath);
    
            // 查找或创建calcPr元素
            var calcPr = doc.Root?.Element(ns + "calcPr");
            if (calcPr is null)
            {
                calcPr = new XElement(ns + "calcPr");
                doc.Root?.Add(calcPr);
            }
    
            // 设置强制重新计算的属性
            calcPr.SetAttributeValue("fullCalcOnLoad", "1");
            calcPr.SetAttributeValue("calcMode", "auto");
            calcPr.SetAttributeValue("calcCompleted", "0"); // 0表示计算未完成
    
            // 保存修改
            doc.Save(workbookPath);
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error updating workbook for recalculation: {ex.Message}");
            // 不抛出异常,因为这不是关键功能
        }
    }
    

    }

  2. michelebastione commented on Aug 26, 2025

    @michelebastione
    Collaborator

    This issue has been fixed and will be shipped with the next update.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions