PDA

Click to See Complete Forum and Search --> : export to excel from datatable


phrajib
Jul 22nd, 2007, 05:45 AM
Dear Friends,

I have a datatable in my application. Now I want to export the table into excel file by clicking a button in form. Please help me. I never export anything to excel before in C#.

-Rajib

Bombdrop
Jul 23rd, 2007, 06:37 AM
Take a look at my attached example should be of some help.

Hope this helps!!
:wave: :thumb: :wave:

RaviIntegra
Jul 24th, 2007, 02:01 AM
Microsoft.Office.Interop.Excel.ApplicationClass excel = new ApplicationClass();
excel.Application.Workbooks.Add(true);
for (int col = 0; col<lstView.Columns.Count;col++ )
{
excel.Cells[1, col + 1] = lstView.Columns[col].Text.ToString();
}
int rowIndex = 1;
int row = 0;
for (row=0; row <lstView.Items.Count;row++)
{
if (rowIndex <= lstView.Items.Count)
rowIndex++;
for (int col = 0; col < lstView.Columns.Count; col++)
{
excel.Cells[rowIndex, col + 1] = lstView.Items[row].SubItems[col].Text.ToString();
}
}
tmpRow = row;
tmpItx = rowIndex;
for (row = 0; row < lstViewPdf.Items.Count; row++)
{
if (tmpItx <= (lstViewPdf.Items.Count * 2))
tmpItx++;
for (int col = 0; col < lstViewPdf.Columns.Count; col++)
{
excel.Cells[tmpItx, col + 1] = lstViewPdf.Items[row].SubItems[col].Text.ToString();
}
}
Worksheet worksheet = (Worksheet)excel.ActiveSheet;
worksheet.Activate();
worksheet.SaveAs("D:\\Inputs\\test.xls", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing
, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
excel.Workbooks.Close();
excel.Quit();
MessageBox.Show("Process completed");

Before export the data you should load the data from database to a listview control and then export it to excel.
I make use of this code to export data to excel and it is working fine.

phrajib
Jul 25th, 2007, 12:06 AM
Thanks for ur help.

All my data is in a DataTable in C#.Net form. Have u any clu that can help me?

Thanks again.

Rajib

phrajib
Jul 25th, 2007, 05:41 AM
Dear RaviIntegra,

I have tried with ur example. But my C#.NET application is not allowing the namespace Microsoft.Office.......

It is telling that Office....... is not allowed in this namespace.

When I write Microsoft. it is giving only three options following it as Csharp, VisualBasic and Win32. But no Office under Microsoft.

Please help me if possible.

Rajib

RaviIntegra
Jul 26th, 2007, 12:58 AM
You should add the reference (Microsoft Office library) in you project references. Then it will work.