My first approach to inserting a new row of data into an existing Excel worksheet from an executing C# assembly was to use the interop assembly generated from the COM Microsoft Excel 11.0 Object Library.
I was successful in creating an application, opening a workbook, getting a reference to the worksheet and updating values in existing cells; but I failed to find a method for inserting a new row. The documentation for the automation interface is poorly organized and I may just have missed it.
My second approach was to use System.Data.Odbc. By assigning a name to the worksheet data range I knew that I could read and write data to the worksheet. The advantage of this approach is a looser coupling to the Excel document. So long as the named range and column names are unchanged, the code should continue to work.
Here are the “issues” I ran into before getting this to work:
· The connection string must include a “ReadOnly=0” clause or you’ll get an exception with a message of “Operation must use an updateable query”. E.g.
Driver={Microsoft Excel Driver (*.xls)};DBQ=c:\Tone\Notebook\Data.xls;ReadOnly=0
· The SQL query editor accessed through the Server Explorer of the Visual Studio Enterprise and Universal editions mis-parses column names such as “[Weight in pounds]”. It adds spaces before and after the braces resulting in a syntax error when you rerun the command.
· The ODBC data type of an Excel column assigned a date format becomes OdbcType.Timestamp which isn’t convertible with a System.DateTime. Instead of using Parameters, I had to resort to String.Format with a format string of {0:yyyy-MM-dd hh:MM:ss} in single quotes for the DateTime.
· I tried using the OdbcCommandBuilder to generate an Insert command for me to see how it handled the Timestamp column but couldn’t get it to generate them. Even after filling a DataSet using an OdbcDataAdapter, changing a value and calling Update, only the original Select statement appeared to be valid. By now I’m way over budget on getting this to work, so I’m leaving this mystery for the future.