Friday, March 11, 2011

Copy Pecific Columns(With Data) of One DataTable To Unother DataTable

Copy Pecific Columns(With Data) of One DataTable To Unother DataTable

There are two datatable DT1 And DT2

DT1 Consists of below 5 Coloumns:

1. EmpID
2. EmpName
3. Department
4. Designation
5. Reporting_Office

Now I Want to Copy Only below 3 columns data to DT2

1. EmpID
2. EmpName
3. Department

Code :

// Create Array with required coloumns Name
string[] cols = {"EmpID","EmpName","Designation"};

// Create new Datatable
DataTable DT2 = new DataTable();

// Fill datatable with new colunms data
DT2 = DT1.DefaultView.ToTable("DT2", false, cols);

Fill Array With DataTable in C#.Net

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

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

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;

}

}

}