Question : 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.

Answer : Export DataView to Excel Spreadsheet with C#

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);


Random Solutions  
 
programming4us programming4us