使用对象将公式添加到 Excel c#

use object for adding formula to Excel c#

我想添加一个公式,如第三个组件所示。 当我删除“=”时,一切正常。但是要向 excel 添加公式,您需要“=”... 当我添加“=”时,程序不再运行... 然后我收到错误:System.Runtime.InteropServices.COMException 未处理 HResult=-2146827284 Message=HRESULT 异常:0x800A03EC

有什么想法吗?

谢谢

        static void Main(string[] args)
    {
        //seed
        var listComponents = new List<Component>
        {
            new Component() {Name = "Vc1", Cell = "A1"},
            new Component() {Name = "Vc2", Cell="B1"},
            new Component() {Name = "Nv", Cell="A2",Calculation = "=((A1+B1)/2)/0,1"}
        };


        //program
        //create excel object, workbook and worksheet
        object misValue = System.Reflection.Missing.Value;
        var excelapp = new Excel.Application();
        Excel.Workbook newWorkbook = excelapp.Workbooks.Add();
        Excel._Worksheet worksheet = (Excel.Worksheet) excelapp.ActiveSheet;

        excelapp.Visible = false;

        //cycle through components
        foreach (var component in listComponents)
        {
            if (component.Calculation != null)
            {
                Excel.Range rng = worksheet.Range[component.Cell];
                rng.Formula = component.Calculation;
                String formula = rng.Formula;
                Console.WriteLine(formula);
            }
        }

        newWorkbook.Close(false, misValue, misValue);
        excelapp.Quit();

        Console.ReadLine();

    }

我认为您需要将 "=((A1+B1)/2)/0,1" 替换为 @"=((A1+B1)/2)/0,1"

我遇到过这样的案例,这对我有用。

我需要将公式中的逗号“,”更改为点“.”。 尽管在我的本地设置中,excel 在对象中使用了“,”,但它仅使用标准值“.”。 再次感谢您的帮助!