Showing posts with label Export DataTable to Excel. Show all posts
Showing posts with label Export DataTable to Excel. Show all posts

Friday, March 11, 2011

Export DataTable to Excel in C#.Net

This is one of the fastest way to export data to Excel file from DataTable

You Need to Import below 2 Libraries for this class to work.
1. Microsoft Office 12.0 Object Library
2. Microsoft Excel 12.0 Object Library


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Threading;
using System.IO;

namespace ExportData2Excel
{
class Export2Excel
{

public void export(DataTable dt)
{
//Create Excel Objects
Microsoft.Office.Interop.Excel.Application oExcel = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbooks oBooks;
Microsoft.Office.Interop.Excel.Sheets oSheets;
Microsoft.Office.Interop.Excel.Workbook oBook;
Microsoft.Office.Interop.Excel.Worksheet oSheet;

//Create New Excel WorkBook
oExcel.Visible = true;
oExcel.DisplayAlerts = false;
oExcel.Application.SheetsInNewWorkbook = 1;
oBooks = oExcel.Workbooks;

oBook = (Microsoft.Office.Interop.Excel.Workbook)(oExcel.Workbooks.Add(Type.Missing));
oSheets = oBook.Worksheets;
oSheet = (Microsoft.Office.Interop.Excel.Worksheet)oSheets.get_Item(1);
oSheet.Name = "FinalData";

// Create Array to hold the data of DataTable
object[,] arr = new object[dt.Rows.Count, dt.Columns.Count];

//Fill DataTable in Array
for (int r = 0; r < dt.Rows.Count; r++)
{
DataRow dr = dt.Rows[r];
for (int c = 0; c < dt.Columns.Count; c++)
{
arr[r, c] = dr[c];
}
}

//Set Excel Range to Paste the Data
Microsoft.Office.Interop.Excel.Range c1 = (Microsoft.Office.Interop.Excel.Range)oSheet.Cells[1, 1];
Microsoft.Office.Interop.Excel.Range c2 = (Microsoft.Office.Interop.Excel.Range)oSheet.Cells[1 + dt.Rows.Count - 1, dt.Columns.Count];
Microsoft.Office.Interop.Excel.Range range = oSheet.get_Range(c1, c2);

//Fill Array in Excel
range.Value2 = arr;

}

}

}