Writing Data from a DataTable to Excel

Posted Thu, Jul 23 2009 13:24 by Deborah Kurata

As with most things in Visual Studio, there are many ways to export data from your .NET application to an Excel spreadsheet. This post covers one straightforward technique.

First, set a reference to the desired version of the Microsoft Excel Object Library from the COM tab of the Add Reference dialog. The resulting reference appears as Microsoft.Office.Interop.Excel.

Import the Microsoft.Office.Interop.Excel library in your code file. To keep the namespaces clear, consider using an alias.

In C#:

using Excel = Microsoft.Office.Interop.Excel;
using System.Reflection;

NOTE: C# also requires a reference to System.Reflection to use the Missing.Value field. This is required because C# 3.0 does not support optional parameters. Every parameter must have a value, so Missing.Value is used to provide a value for all unspecified optional parameters.

In VB:

Imports Excel = Microsoft.Office.Interop.Excel

The rest of the code is presented in VB and C# and then discussed below. It is provided in one big chunk to make it easier to copy/paste into your application.

In C#:

Excel.Application oXL;
Excel.Workbook oWB;
Excel.Worksheet oSheet;
Excel.Range oRange;

// Start Excel and get Application object.
oXL = new Excel.Application();

// Set some properties
oXL.Visible = true;
oXL.DisplayAlerts = false;

// Get a new workbook.
oWB = oXL.Workbooks.Add(Missing.Value);

// Get the active sheet
oSheet = (Excel.Worksheet)oWB.ActiveSheet ;
oSheet.Name = "Customers";

// Process the DataTable

// BE SURE TO CHANGE THIS LINE TO USE *YOUR* DATATABLE

DataTable dt = Customers.RetrieveAsDataTable();

int rowCount = 1;
foreach (DataRow dr in dt.Rows)
{
    rowCount += 1;
    for (int i = 1; i < dt.Columns.Count+1; i++)
    {
        // Add the header the first time through
        if (rowCount==2)
        {
            oSheet.Cells[1, i] = dt.Columns[i - 1].ColumnName;
        }
        oSheet.Cells[rowCount, i] = dr[i - 1].ToString();
    }
}

// Resize the columns
oRange = oSheet.get_Range(oSheet.Cells[1, 1],
              oSheet.Cells[rowCount, dt.Columns.Count]);
oRange.EntireColumn.AutoFit();

// Save the sheet and close
oSheet = null;
oRange = null;
oWB.SaveAs("test.xls", Excel.XlFileFormat.xlWorkbookNormal,
    Missing.Value, Missing.Value, Missing.Value, Missing.Value,
    Excel.XlSaveAsAccessMode.xlExclusive,
    Missing.Value, Missing.Value, Missing.Value,
    Missing.Value, Missing.Value);
oWB.Close(Missing.Value, Missing.Value, Missing.Value);
oWB = null;
oXL.Quit();

// Clean up
// NOTE: When in release mode, this does the trick
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();

In VB:

Dim oXL As Excel.Application
Dim oWB As Excel.Workbook
Dim oSheet As Excel.Worksheet
Dim oRange As Excel.Range

' Start Excel and get Application object.
oXL = New Excel.Application

' Set some properties
oXL.Visible = True
oXL.DisplayAlerts = False

' Get a new workbook.
oWB = oXL.Workbooks.Add

' Get the active sheet
oSheet = DirectCast(oWB.ActiveSheet, Excel.Worksheet)
oSheet.Name = "Customers"

' Process the DataTable
'
BE SURE TO CHANGE THIS LINE TO USE *YOUR* DATATABLE
Dim dt As Data.DataTable = Customers.RetrieveAsDataTable

' Create the data rows
Dim rowCount As Integer = 1
For Each dr As DataRow In dt.Rows
    rowCount += 1
    For i As Integer = 1 To dt.Columns.Count
        ' Add the header the first time through
        If rowCount = 2 Then
            oSheet.Cells(1, i) = dt.Columns(i - 1).ColumnName
        End If
        oSheet.Cells(rowCount, i) = dr.Item(i - 1).ToString
    Next
Next

' Resize the columns
oRange = oSheet.Range(oSheet.Cells(1, 1), _
          oSheet.Cells(rowCount, dt.Columns.Count))
oRange.EntireColumn.AutoFit()

' Save the sheet and close
oSheet = Nothing
oRange = Nothing
oWB.SaveAs("test.xls")
oWB.Close()
oWB = Nothing
oXL.Quit()

' Clean up
' NOTE: When in release mode, this does the trick
GC.WaitForPendingFinalizers()
GC.Collect()
GC.WaitForPendingFinalizers()
GC.Collect()

NOTE: The VB code code above is set up to run with Option Strict ON.

The code begins by declaring the variables used in the code. Notice that in both C# and in VB this makes use of the namespace alias as shown at the very beginning of this post.

The code then starts Excel and makes it visible. If you want to create the spreadsheet without making Excel visible to the user, you could set the Visible to false instead.

A workbook is added, the active sheet of the workbook is referenced, and the sheet is given a name.

The DataTable is then processed. You can use any DataTable here. The code loops through the rows of the DataTable and for each row it loops through the columns. The first time through the columns it adds column headings.

To make the spreadsheet easier to read, the columns are then resized to show the contents of the cells. If you have lots of data in a cell, you may want to skip this step.

The workbook is then saved. Since no directory was specified, Excel will save the file to your My Documents folder. Notice the massive number of parameters in the C# code when calling the SaveAs (and Close) methods. This is required because C# does not have optional parameters. So the code must fill in each and every parameter in the call. VB does support optional parameters, so does not need to set the extra parameters.

NOTE: C# is getting optional parameters in .NET 4.0 (VS 2010).

Finally, the code is cleaned up. Since Excel is accessed through COM interop, the double garbage collection code is added to ensure Excel is correctly closed.  See this link for more information on why this specific garbage collection code is recommended.

Enjoy!

Filed under: , , , , ,

Comments

# re: Writing Data from a DataTable to Excel

Thursday, July 23, 2009 6:13 PM by Mark Wisecarver

Awesome. Whatever we can do to keep you rolling please do...You're kicking this stuff out at an unbelievable rate and it's all uber cool. Thanks!

# VB.NETからExcelを操作する時参考になるサイトまとめ

Sunday, July 26, 2009 4:41 AM by 戦艦ゆにっき

業務でツールが出力したデータを分析して結果をExcelに出力するアプリを作っています。 本当、このアプリ開発にはいろいろあり悩まされてきたけど、ようやく終わりが見えてきたところで困ったのがExcelの終了処理

# re: Writing Data from a DataTable to Excel

Friday, August 07, 2009 4:10 PM by Paul Caesar

Deborah,

I've been looking for this code for days. You are my new hero! You saved me hours of effort in making this work.

# re: Writing Data from a DataTable to Excel

Wednesday, September 09, 2009 8:06 AM by Ken

Love the code; it works great with my code to pull XML data from a website into a dataset.  One question though.  If I want to leave the Excel file open so I can do further work on it, how do I do so with out leaving garbage out there?

# re: Writing Data from a DataTable to Excel

Thursday, September 24, 2009 5:30 PM by Marton Toth

Hi,

I use Excel 2008 on Mac. It does not enable the use of macros. I am not familiar with Applescript or C#.

My question is pretty similar and I wonder if it can be solved without the use of macros. I have several columns of data (heading is constant, length of columns could differ), which has to be transformed to fit to a statistical software so that each cell in the column produces as many cells beneath in the same column as the value of the cell (not negative integer). The value of the newly generated cells are the sequential number of the original cell in the column (except for the heading).

Eg:

XY

0

0

1

3

4

8

This column should produce altogether 16 cells in the same column (or new spreadsheet) 1 with the value "3", 3 with the value "4", 4 with the value "5" and 8 with the value "6" (the sequential number could be read out form an other parallel column as well).

I would very much appreciate if you could help solving ths frustrating problem.

M.

# re: Writing Data from a DataTable to Excel

Friday, September 25, 2009 12:04 PM by Deborah Kurata

Hi Marton -

My blog primarily focuses on .NET development. You may want to try posting your question to an Excel forum.

Good luck!

# re: Writing Data from a DataTable to Excel

Monday, October 05, 2009 12:59 AM by Manu

Please tell me what is this "missing" field ??  

# re: Writing Data from a DataTable to Excel

Monday, October 05, 2009 10:40 AM by Deborah Kurata

Hi Manu -

Thank you for stopping by the blog. Missing.Value is needed in C# because C# 3.0 does not support optional parameters.

Here is a link to the msdn documentation on Missing.Value:

msdn.microsoft.com/.../system.reflection.missing.value.aspx

# re: Writing Data from a DataTable to Excel

Friday, October 09, 2009 3:19 PM by noel

try to use the code as it but i get an undeline error on "Customers" name "Customers" is not declared

# re: Writing Data from a DataTable to Excel

Friday, October 09, 2009 6:02 PM by Deborah Kurata

Hi Noel -

Are you referring to this line?

Dim dt As Data.DataTable = Customers.RetrieveAsDataTable

As I mentioned in the description following the code, you can use any DataTable. In my example, the DataTable came from my Customers class. You will have to change the right side of this equation to reference your table from whereever it is.

Hope this helps.

# re: Writing Data from a DataTable to Excel

Friday, October 16, 2009 5:14 AM by Manu

To  Deborah Kurata

Thanks a lot... I really appreciate your effort..

this blog was really helpful..

# re: Writing Data from a DataTable to Excel

Friday, October 16, 2009 5:17 AM by Manu

 WB.SaveAs(filename, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, null, null, false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlShared, false, false, null, null, null);

this code also works.. :: )

# re: Writing Data from a DataTable to Excel

Wednesday, October 28, 2009 2:52 PM by sanjay

Terrific Mate..

# re: Writing Data from a DataTable to Excel

Monday, November 02, 2009 1:52 PM by Chris

This is a nice example of automating Excel via .NET, which I would like to see more of, but this method will be painfully slow for large amounts of data.  Anyone else have "bulk" methods for sending the data in one shot?

I know this can be done with an array, but you must first get from the datatable to the array.  Using a  StreamWriter to go to .csv is also fast, but this file must then be opened in Excel.  It would be nice to have a fast direct method.

# re: Writing Data from a DataTable to Excel

Thursday, November 19, 2009 4:51 PM by rngGuy

I used the excel API and it was extremely slow.  Then I found this article

theengineroom.provoke.co.nz/.../how-to-bulk-insert-data-into-an-excel-worksheet-using-c-and-office-12.aspx

Highlights:

1) Get your datatable

2) delcare object array

3) fill object array with data

4) get an excel range object of exact size of column with and number of rows

5) excelRng.Value2 = object array

Your data is 'pasted' into your worksheet and you don't have to use the clipboard object

HTH

# re: Writing Data from a DataTable to Excel

Thursday, November 19, 2009 11:07 PM by Deborah Kurata

Thanks for  the tip, rngGuy!

# re: Writing Data from a DataTable to Excel

Tuesday, December 08, 2009 6:18 AM by Anil panwar

Great Job!! Act help...

# re: Writing Data from a DataTable to Excel

Tuesday, January 19, 2010 1:25 PM by Johan

Great tip rngGuy. tnks

# re: Writing Data from a DataTable to Excel

Wednesday, January 20, 2010 4:35 AM by sebas

Thanks, but people should be aware of a bug, when using another culture.

Small fix: 
               // due to an interop bug we've to set the culture to en-US
               // save the old one and apply the fix
               CultureInfo currentCulture = Thread.CurrentThread.CurrentCulture;
               Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");

excel magic here

              // put old culture back on
               System.Threading.Thread.CurrentThread.CurrentCulture = currentCulture;

# re: Writing Data from a DataTable to Excel

Friday, January 22, 2010 9:46 AM by Vinicius

Excellent, finally I found a person explaining a so simple thing in a good way.

Reference words: Windows Form ,  Application ,  Excel ,  C# ,  .NET ,  Cells .

# re: Writing Data from a DataTable to Excel

Tuesday, February 16, 2010 7:50 AM by bvpavan

thanks Deborah...its worked fine on xls file...but its not saving in xlsx file..iam using office 2010..any how its worked great on xls.

# re: Writing Data from a DataTable to Excel

Sunday, May 02, 2010 12:10 AM by Nero

Can't thank you enough Deborah. Your code saved my day !!!

After trying for last few days, finally I could copy data from a worksheet in one Workbook to another existing worksheet in a different workbook.

Cheers...

-Nero

# re: Writing Data from a DataTable to Excel

Wednesday, May 05, 2010 12:47 PM by Maverick

Thanks a lot .. its a really good piece of code.. and it works really nice...

# re: Writing Data from a DataTable to Excel

Thursday, June 03, 2010 12:06 PM by Dave

Deb, this works great, thanks.  However, one of the columns that's being returned is being shown as scientific notation.  Is there a way to format that column so that it's text?

# re: Writing Data from a DataTable to Excel

Monday, July 12, 2010 9:00 PM by Henry Tang

So lucky that I can search your code. Really nice and thanks Deborah!

# Excel VSTO SQL Server Browser (Grab from SQL and automate with Excel)

Friday, September 17, 2010 4:13 PM by Joao Livio { MIX ~ UP on USA}

Introduction Sometimes is necessary use Excel automation in order to grab some information from a specific

# re: Writing Data from a DataTable to Excel

Wednesday, October 06, 2010 4:25 PM by Francine Taylor

Deborah, thanks so much for an understandable and beautifully simple piece of code.  I really appreciated it!

# re: Writing Data from a DataTable to Excel

Wednesday, October 13, 2010 4:52 AM by Rhys

I missed the second paragraph (i.e. the important one) and spent some time trying to reinstall the interop.excell DLL before realising I just hadn't added it as a reference.  After that, I had the program working fine but I broke something trying to reinstall the interop.excel file.  Can anyone tell me how to fix the registry?

# re: Writing Data from a DataTable to Excel

Wednesday, October 13, 2010 8:11 PM by Rhys

Sorry, wasn't a registry problem at all.  Was something much simpler and is fixed now.

# re: Writing Data from a DataTable to Excel

Thursday, November 11, 2010 12:38 AM by kris

awesome

# re: Writing Data from a DataTable to Excel

Saturday, November 27, 2010 2:01 PM by Greg

I think one of these wold be cleaner:

       /// <summary>Add data to the sheets, with the columns names at the top</summary>

       /// <param name="dataTable">The data to be added to the sheet</param>

       /// <param name="sheetToAddTo">The worksheet to add the data to</param>

       /// <returns>The range of the data that has been added</returns>

       public virtual Range AddDataTableToWorksheet(System.Data.DataTable dataTable, Worksheet worksheet, bool overWriteExistingData)

       {

           Range returnValue = null;

           Range rngToWriteTo = null;

           try

           {

               if (overWriteExistingData)

               {

                   //remove any existing data

                   this.ClearWorksheet(worksheet, XlDeleteShiftDirection.xlShiftUp);

               }//end if -checking for WriteOptions(appends vs Overwrite)

               //create the object to store the column names

               object[,] columnNames;

               //create array to hold column ames

               columnNames = new object[1, dataTable.Columns.Count];

               //add the columns names from the datatable

               for (int i = 0; i < dataTable.Columns.Count; i++)

               {

                   columnNames[0, i] = dataTable.Columns[i].ColumnName;

               }// end for- getting column names

               //get last Row used---------add 1 to start on next line

               int lastRow = this.LastUsedRowIndex(worksheet)+1;

               if (lastRow <= 0) { lastRow = 1; }

               else if (lastRow > 1) { lastRow++; }

               //get a range object that the columns will be added to

               Range columnsNamesRange = worksheet.get_Range(worksheet.Cells[lastRow, 1], worksheet.Cells[lastRow, dataTable.Columns.Count]);

               columnsNamesRange.Font.Bold = true;

               //a simple assignement allows the data to be transferred quickly

               columnsNamesRange.Value2 = columnNames;

               //release the columns range object now it is finished with

               System.Runtime.InteropServices.Marshal.ReleaseComObject(columnsNamesRange);

               columnsNamesRange = null;

               //End Adding Header Columns

               //create the object to store the dataTable data

               object[,] rowData;

               rowData = new object[dataTable.Rows.Count, dataTable.Columns.Count];

               //insert the data into the object[,]

               for (int iRow = 0; iRow < dataTable.Rows.Count; iRow++)

               {

                   for (int iCol = 0; iCol < dataTable.Columns.Count; iCol++)

                   {

                       rowData[iRow, iCol] = dataTable.Rows[iRow][iCol];

                   }// end for-looping through columns in row

               }// end for- looping through rows in datatable

               //get a range to add the table data into

               //it is one row down to avoid the previously added row which was column headers

               lastRow += 1;

               rngToWriteTo = worksheet.get_Range(worksheet.Cells[lastRow, 1], worksheet.Cells[lastRow + dataTable.Rows.Count - 1, dataTable.Columns.Count]);

               //assign data to worksheet

               rngToWriteTo.Value2 = rowData;

               //return the range to the new data subtracting 1 from lastrow to include the header

               returnValue = worksheet.get_Range(worksheet.Cells[lastRow - 1, 1], worksheet.Cells[(lastRow - 1) + dataTable.Rows.Count - 1, dataTable.Columns.Count]);

           }

           catch (COMException ex)

           {

               returnValue = null;

               LastException = ex;

           }

           catch (Exception ex)

           {

               returnValue = null;

               LastException = ex;

           }

           finally

           {

               //release range

               if (rngToWriteTo != null)

               {

                   System.Runtime.InteropServices.Marshal.ReleaseComObject(rngToWriteTo);

                   rngToWriteTo = null;

               }

           }// end try catch finally

           return returnValue;

       }// end public Range AddDataTableToWorksheet

       public bool AddDataTableToWorksheet(Worksheet worksheet, System.Data.DataTable dataTable, bool overWriteExistingData, bool writeColumnHeaders)

       {

           bool returnValue = false;

           int lastUsedRow = 0;

           try

           {

               if (worksheet == null || dataTable == null) { return returnValue; }

               if (overWriteExistingData == true) { this.ClearWorksheet(worksheet, XlDeleteShiftDirection.xlShiftUp); }

               lastUsedRow = this.LastUsedRowIndex(worksheet) + 1;

               lastUsedRow++;

               if (writeColumnHeaders)

               {

                   foreach (DataColumn col in dataTable.Columns)

                   {

                       worksheet.Cells[lastUsedRow, col.Ordinal + 1] = col.ColumnName;

                   }// end foreach

                   lastUsedRow += 1;

               }// end if

               foreach (DataRow dr in dataTable.Rows)

               {

                   foreach (DataColumn col in dataTable.Columns)

                   {

                       if (dr[col.ColumnName] != DBNull.Value)

                       {

                           worksheet.Cells[lastUsedRow, col.Ordinal + 1] = dr[col.ColumnName];

                       }

                   }

                   lastUsedRow += 1;

               }

               if (overWriteExistingData)

               {

                   // Resize the columns

                   Range rng = worksheet.UsedRange;

                   rng.EntireColumn.AutoFit();

               }

           }

           catch (COMException ex) { returnValue = false; LastException = ex; }

           catch (Exception ex) { returnValue = false; LastException = ex; }

           return returnValue;

       }// end AddDataTableToWorksheet

# re: Writing Data from a DataTable to Excel

Sunday, December 05, 2010 11:00 PM by Arjun

Hi dude super work keep it up..i really needed this..written so neatly and easy to understand

# re: Writing Data from a DataTable to Excel

Tuesday, January 04, 2011 7:46 AM by Sethu Vidyaderrao

Excellent Article......................

Great Job ........

# re: Writing Data from a DataTable to Excel

Monday, February 14, 2011 9:29 AM by Avrohom

Greetings-

The C# code above works very well, indeed. However, I need to make one modification to it. How do I specify those columns which need to treat incoming data as TEXT - that is, alphanumeric characters (0,1,2,3, etc.) as TEXT values, and NOT as numerals?

# re: Writing Data from a DataTable to Excel

Wednesday, March 30, 2011 7:39 AM by Bobby

Hello can you tell me how to save in spesific folder??

i use this:

string savePath = Request.PhysicalApplicationPath + @"\Save_Forecast\"+TextBox1.Text+".xls";

and it gave me exception saying that it can't be more than 218 char

or can we change the default path??

thank you

# re: Writing Data from a DataTable to Excel

Wednesday, March 30, 2011 9:48 AM by Deborah Kurata

Hi Bobby -

If you put a break point in and display the contents of the savePath variable, what does it look like?

# re: Writing Data from a DataTable to Excel

Thursday, May 05, 2011 2:49 AM by kate

Hi, Im working on exporting a DataTable to an Excel file. My code is working, I put first my data on a table using DataGridView but everytime I click the button to export the table, it just create an Excel file but cannot retrieve the values.

# re: Writing Data from a DataTable to Excel

Tuesday, May 10, 2011 3:25 PM by Marc Brunelle

Thank you very much Deborah for this wonderful post. It got the job done for me. :)

Marc

# re: Writing Data from a DataTable to Excel

Monday, May 16, 2011 10:20 PM by Teresa

Thank you Deborah, you are awesome! ^^

# re: Writing Data from a DataTable to Excel

Thursday, May 26, 2011 12:28 AM by navin

hi,

i have pasted your code...

excel is saving .. but when i open it ..its showing a blank document ...

i need to save it in csv format , is it possible to do with the above code ...

thanx n regards

T.Navin

# re: Writing Data from a DataTable to Excel

Friday, June 03, 2011 3:04 PM by tolis

Good post..thanks...

# re: Writing Data from a DataTable to Excel

Wednesday, June 29, 2011 7:59 AM by Chris Knight

This is great! Works perfectly for my reporting! Much appreciated!

# re: Writing Data from a DataTable to Excel

Thursday, July 07, 2011 4:36 AM by ronluo

thantks a lot, that helps me a lot!

# re: Writing Data from a DataTable to Excel

Monday, July 11, 2011 6:05 AM by dhiraj

This does export the datatable into the excel. But what to do when we run the application on the machine with no microsoft office installed??

# re: Writing Data from a DataTable to Excel

Sunday, August 14, 2011 8:04 AM by Lyndall

Shoot, so that's that one suppoess.

# re: Writing Data from a DataTable to Excel

Wednesday, September 07, 2011 7:17 AM by sami

Deborah ,

when tried the above code to import the DataGridView to Excel, i get the below error

*******

Error1'System.Data.DataTable' does not contain a definition for 'RetrieveAsDataTable' and no extension method 'RetrieveAsDataTable' accepting a first argument of type 'System.Data.DataTable' could be found (are you missing a using directive or an assembly reference?)

******

code used for DataTable is as below;

DataTable dtGenInfo = new DataTable();

DataTable dt = dtGenInfo.RetrieveAsDataTable();

Kindly let me know where m i going wrong

# re: Writing Data from a DataTable to Excel

Wednesday, September 07, 2011 7:20 AM by sami

Code Block:

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

using System.Data.Sql;

using System.Data.SqlClient;

using excel = Microsoft.Office.Interop.Excel;

using System.Reflection;

namespace trial

{

   public partial class Form1 : Form

   {

       public Form1()

       {

           InitializeComponent();

       }

       //------------------------------Database connection-------------------

       SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS2008;Initial Catalog=TCGen;Integrated Security=True");

       SqlDataAdapter daGenInfo = new SqlDataAdapter("select * from GenInfo", @"Data Source=.\SQLEXPRESS2008;Initial Catalog=TCGen;Integrated Security=True");

       DataTable dtGenInfo = new DataTable();

       private void Form1_Load(object sender, EventArgs e)

       {

           //---General Information Add/Update/Delete---

           SqlCommandBuilder cbGenInfo = new SqlCommandBuilder(daGenInfo);

           daGenInfo.Fill(dtGenInfo);

           bindingSource1.DataSource = dtGenInfo;

           dataGridView1.DataSource = bindingSource1;

           dataGridView1.AutoResizeColumns();

       }

       private void button1_Click(object sender, EventArgs e)

       {

           excel.Application oXL;

           excel.Workbook oWB;

           excel.Worksheet oSheet;

           excel.Range oRange;

           // Start Excel and get Application object.

           oXL = new excel.Application();

           // Set some properties

           oXL.Visible = true;

           oXL.DisplayAlerts = false;

           // Get a new workbook.

           oWB = oXL.Workbooks.Add(Missing.Value);

           // Get the active sheet

           oSheet = (excel.Worksheet)oWB.ActiveSheet;

           oSheet.Name = "Customers";

           // Process the DataTable

           // BE SURE TO CHANGE THIS LINE TO USE *YOUR* DATATABLE

           DataTable dt = dtGenInfo.RetrieveAsDataTable();

           int rowCount = 1;

           foreach (DataRow dr in dt.Rows)

           {

               rowCount += 1;

               for (int i = 1; i < dt.Columns.Count + 1; i++)

               {

                   // Add the header the first time through

                   if (rowCount == 2)

                   {

                       oSheet.Cells[1, i] = dt.Columns[i - 1].ColumnName;

                   }

                   oSheet.Cells[rowCount, i] = dr[i - 1].ToString();

               }

           }

           // Resize the columns

           oRange = oSheet.get_Range(oSheet.Cells[1, 1],

                         oSheet.Cells[rowCount, dt.Columns.Count]);

           oRange.EntireColumn.AutoFit();

           // Save the sheet and close

           oSheet = null;

           oRange = null;

         //  oWB.SaveAs("test.xls", Excel.XlFileFormat.xlWorkbookNormal,Missing.Value, Missing.Value, Missing.Value, Missing.Value,Excel.XlSaveAsAccessMode.xlExclusive,Missing.Value, Missing.Value, Missing.Value,Missing.Value, Missing.Value);

           oWB.SaveAs("test.xls", Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, null, null, false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlShared, false, false, null, null, null);

           oWB.Close(Missing.Value, Missing.Value, Missing.Value);

           oWB = null;

           oXL.Quit();

           // Clean up

           // NOTE: When in release mode, this does the trick

           GC.WaitForPendingFinalizers();

           GC.Collect();

           GC.WaitForPendingFinalizers();

           GC.Collect();

       }

   }

}

# re: Writing Data from a DataTable to Excel

Friday, September 09, 2011 10:35 AM by S.L. Barth

Thank you! This post has been very helpful to me.

# Writing Data from a DataTable to Excel in Sharepoint 2007

Saturday, September 24, 2011 8:11 AM by peithiviraj

I have added your code in my sharepoint webpart.but that is not working in client system.

its working charm in my own system(Which i developed the webpart).

What may the probs

# re: Writing Data from a DataTable to Excel

Monday, September 26, 2011 4:13 AM by magazine for ipad

This saved my day.Thank's for this useful article.

As I was trying to implement this in my sharepoint site, I was wondering if there is a way for me to export data in spgridview to excel.

# re: Writing Data from a DataTable to Excel

Thursday, September 29, 2011 1:19 AM by MANJEET CHAUHAN

It Is very help me.........

# re: Writing Data from a DataTable to Excel

Tuesday, October 04, 2011 4:19 AM by praveen

It was Great, but i get interop exception when i use the same code in windows server 2008 where microsoft excel is not installed. Can you please provide the fix Asap.......

# re: Writing Data from a DataTable to Excel

Monday, October 10, 2011 3:18 AM by vijay kumar N

Thanks...Good work.... keep posting like this articles...

# re: Writing Data from a DataTable to Excel

Thursday, November 03, 2011 3:30 AM by Keshab Pandey

Good one.......Really Like it

# re: Writing Data from a DataTable to Excel

Thursday, November 03, 2011 1:25 PM by Rama

Wonderful.. Easy to understand and yet powerful to generate the desired results.

# re: Writing Data from a DataTable to Excel

Thursday, November 17, 2011 9:37 AM by Steve

Thanks Deborah, for yet again a great post.  I bought one of your excellent books many years ago, Doing Objects - a great read!

# re: Writing Data from a DataTable to Excel

Monday, January 02, 2012 11:44 PM by sonalp

hi Dedorah,

                 i tried the first solution (ie. in C#) but i got the error ..........

Retrieving the COM class factory for component with CLSID {00024500-0000-0000-C000-000000000046} failed with HRESULT: 0x80070005(Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))).

                for this error i made some changes in DCOM comfig but still not working.

                please help me...

# re: Writing Data from a DataTable to Excel

Monday, January 09, 2012 5:18 AM by Rahul

One shot solution!!!!!

Leave a Comment

(required) 
(required) 
(optional)
(required) 
If you can't read this number refresh your screen
Enter the numbers above: