我想添加一個公式,如第三個組件所示。 當我刪除「=」時,一切正常。但是,爲了增加一個公式來優化,你需要「=」... 當我添加「=」,程序不再工作了... 然後我收到錯誤:System.Runtime.InteropServices.COMException未處理HResult = -2146827284消息= HRESULT的異常:0x800A03EC使用對象向Excel中添加公式c#
任何想法?
謝謝
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();
}
您是否在使用逗號作爲小數點分隔符的文化中?嘗試使用一段時間而不是逗號的公式。如果你需要一個逗號,你應該研究如何使這種文化背景。 – Crowcoder 2015-02-07 14:08:37
感謝您的幫助,@Crowcoder。這確實是一個文化背景的問題。實際上,它不檢查文化設置並使用標準值。 ( 「。「 代替 」,」)。 – Deschuytterp 2015-02-07 16:06:40