Home » excel » Some Excel cells stay unpopulated, with C#

Some Excel cells stay unpopulated, with C#

Posted by: admin April 23, 2020 Leave a comment

Questions:

I’m writing an application that opens an existing .xlsx file and writes to certain cells.

Some cells write correctly, where others just stay blank?

Any ideas?

This is a snippet of code

The same code for the cells that are and arent working, except that the index’s changed

oSheet.Cells[3, 15] = "1"; // this doesnt write to the cell 
oSheet.Cells[7, 7] = "1"; // this writes to the cell 

All that i could think is that there is a formatting issue in the Excel file?

How to&Answers:

I’ve been working in Excel for years and find quirks like this all the time. If you are in .NET 4.0 try this:

using Excel = Microsoft.Office.Interop.Excel    

//Other Class code
var range = oSheet.Cells[3, 15];
range.Value2 = "1";

Otherwise, try this:

using Excel = Microsoft.Office.Interop.Excel    

//Other Class code

Excel.Range range = (Excel.Rang)oSheet.Cells[3, 15];
range.Value2 = "1";

Value2 seems to work more consistently, so I generally recommend using it.

Cheers!

Answer:

Anthony was right, I had my columns and rows switched.