Writing to excel using C#
I know there is a simple answer to this, but I just can't find it.
I am able to create an excel file and write to it, but I can only write to the first column. I would like to be able to write data to the second column in excel as well.
Is this possible?
When you're writing to the file you can also specify the column not just the row...
| |
rowIndex = 1; columnIndex = 2; excelAPP.Cells(rowIndex, columnIndex) = "Blah"
|
That would place the word Blah into Range "B1" in excel.
mEt at 2007-9-3 >

There are several options you can use to manipulate an excel file.
The first and possibly simplest is to use COM integration to manipulate an excel spreadsheet programmatically. I have a co-worker who does this with Visio.
I also found a library on CodeProject that does excel exporting for you (you hand it a DataTable and it exports it to Excel). I haven't tried it myself, but it will likely work.
Finally, you can find the Excel format on the internet and code your own library to read and write from/to Excel.
If the codeproject library works like it says, it will probably be the easiest method to use.
In references, right click, add reference
Choose the COM tab
Choose Microsoft Excel 10.0 Object Library
It doesn't get much simpler than this:
| |
Excel.Application excelApp = new Excel.Application(); string myPath = @"C:\Excel.xls"; excelApp.Workbooks.Open(myPath); int rowIndex = 1; int colIndex = 1; excelApp.Cells[rowIndex, colIndex] = "First"; excelApp.Visible = true; |
That will open the workbook named Excel.xls located in your C:\ directory. rowIndex controls which row you're in and assumingly so, colIndex controls the column you are in. The code will place the word "First" into the workbook in cell "A1". The visible method tells your program to make "excelApp" visible. You can of course save/close the workbook without displaying it first.
mEt at 2007-9-3 >
