This project has moved and is read-only. For the latest updates, please go here.

How do I set the value of a cell?

Jul 6, 2016 at 5:28 PM
Edited Jul 6, 2016 at 6:24 PM
I am trying to create a workbook and set the value of the first cell, but I get an exception.
What am I missing? (Note: I am using Office 2016).

Here is the code:
            using (var app = new Application())
            using (var wb = app.Workbooks.Add())
            {
                var sheet = (Worksheet)wb.Sheets.Add();
                sheet.Cells[0, 0].Value = "Test";
                wb.Save();
            }
        }
It throws this exception at sheet.Cells[0, 0].Value = "Test":
System.Runtime.InteropServices.COMException was unhandled by user code
  ErrorCode=-2147467259
  HResult=-2147467259
  Message=See inner exception(s) for details.
  Source=NetOffice
  StackTrace:
       at NetOffice.Invoker.PropertyGet(COMObject comObject, String name, Object[] paramsArray)
       at NetOffice.ExcelApi.Range.get_Item(Object rowIndex, Object columnIndex)
       at blah.Export.ExcelExporter.AddRow(Worksheet sheet, Int32 rowIndex, Action`1 format, String[] values) in C:\blah\Vault\blah\blahSource\blah.Export\ExcelExporter.cs:line 51
       atblah.Export(ModelContents[] modelContents, String targetFilePath) in C:\blah.Export\ExcelExporter.cs:line 27
       at MAS.RevitAddin.Export.Tests.ExportTests.ExportOneFamilyWithOneParam() in blah.Export.Tests\ExportTests.cs:line 26
  InnerException: 
       HResult=-2146232828
       Message=Exception has been thrown by the target of an invocation.
       Source=mscorlib
       StackTrace:
            at System.RuntimeType.InvokeDispMethod(String name, BindingFlags invokeAttr, Object target, Object[] args, Boolean[] byrefModifiers, Int32 culture, String[] namedParameters)
            at System.RuntimeType.InvokeMember(String name, BindingFlags bindingFlags, Binder binder, Object target, Object[] providedArgs, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParams)
            at NetOffice.Invoker.PropertyGet(COMObject comObject, String name, Object[] paramsArray)
       InnerException: 
            ErrorCode=-2146827284
            HResult=-2146827284
            Message=Exception from HRESULT: 0x800A03EC
            Source=""
            InnerException: 
Jul 6, 2016 at 6:42 PM
Edited Jul 6, 2016 at 6:42 PM
In MS-Office applications generaly, the lower index bounds for arrays/indexers is 1 for history reasons(vba).
So please try: "sheet.Cells[1, 1]" instead of "sheet.Cells[0, 0]".

Sebastian
Marked as answer by jmarr on 7/6/2016 at 12:31 PM
Jul 6, 2016 at 8:31 PM
That was the issue.

Thanks!