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
Printable View
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
Take a look at my attached example should be of some help.
Hope this helps!!
:wave: :thumb: :wave:
Before export the data you should load the data from database to a listview control and then export it to excel.Code: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");
I make use of this code to export data to excel and it is working fine.
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
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
You should add the reference (Microsoft Office library) in you project references. Then it will work.