Export DataView to Excel Spreadsheet with C#

Hello Experts,

I am using the code below to export a DataView to a CSV file.  I would prefer to export the dataview into an Excel Spreadsheet because ultimately the data is being used as a datasource for a mail merge.   It appears that I cannot use a CSV as a datasource for a mail merge so currently I have a procedure that inserts this data into a Word.doc-- however, it takes a long time to create this Word.doc.  I would like to cut out the middle step and believe performance will be better if I use an .xls as opposed to .doc for the datasource.

 How can I create a spreadsheet from a DataView?

StreamWriter outputFile = new StreamWriter("c:\\"+fileName+".csv");
           
            string delim;

            //write Header Row
            delim = "";
            foreach (DataColumn col in dv.Table.Columns)
            {
                outputFile.Write(delim);
                outputFile.Write(col.ColumnName);
                delim = ",";
            }
            outputFile.WriteLine();

            //write data into each row
            foreach (DataRowView row in dv)
            {
                delim = "";
                foreach (object item in row.Row.ItemArray)
                {
                    outputFile.Write(delim);
                    outputFile.Write(item);
                    delim = ",";
                }
                outputFile.WriteLine();
            }
            outputFile.Close();

Thanks for your help.
soapygusAsked:
Who is Participating?
 
rstomarConnect With a Mentor Commented:
use SaveAs method of Excel.WorkBook object

E.g.
// Instantiate Excel and start a new workbook.
            objApp = new Excel.Application();
            objBooks = objApp.Workbooks;
            objBook = objBooks.Add( Missing.Value );

Then use
objBook.SaveAs(@"C:\folder\Book1.xls", m_objOpt, m_objOpt,
      m_objOpt, m_objOpt, m_objOpt, Excel.XlSaveAsAccessMode.xlNoChange,
      m_objOpt, m_objOpt, m_objOpt, m_objOpt);


0
 
soapygusAuthor Commented:
Thanks rstomar --

The second link led the way here: http://support.microsoft.com/kb/302096/EN-US/

I've been able to populate an XLS with my DataView using that documentation.  However, I am struggling trying to figure out how to create an XLS with a filename that I specify.  I haven't yet found the answer.  Right now my procedure builds a spreadsheet called "Book1."

I need to pass the filename to the procedure and then save and close the XLS when it's done.  Can you point me in the right direction there?

Thanks for your help.
0
 
soapygusAuthor Commented:
Thank you.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.