Saturday, September 01, 2012

How to write data into the Excel 2010 using C#.Net


How to write data into the Excel 2010 using C#.Net
You can use .Net library to export or write data into the excel 2010 and above, below the code to do the same using C#.NET
Add Reference
Goto .NET tab and addMicrosoft.Office.Interop.Excel” reference in your project
NameSpace
using Excel = Microsoft.Office.Interop.Excel;
C#.Net Source Code
var exApp = new Excel.Application();

// Make the Excel file visible.
exApp.Visible = true; 
//Add one sheet into
exApp.Workbooks.Add(); 
// use only one workSheet.
Excel._Worksheet workSheet = exApp.ActiveSheet;
// column headings in cells A1 and B1.
workSheet.Cells[1, "A"] = "ID";
workSheet.Cells[1, "B"] = "Description";
var row = 1;
for (int i = 0; i <= 10; i++)
{
   row++;
   workSheet.Cells[row, "A"] = "Id_" + i;
   workSheet.Cells[row, "B"] = "Description " + i;
} 
workSheet.Columns[1].AutoFit();
workSheet.Columns[2].AutoFit();
// Call to AutoFormat
workSheet.Range["A1", "B3"].AutoFormat(Excel.XlRangeAutoFormat.xlRangeAutoFormatClassic2);
//Copy into the range
workSheet.Range["A1:B3"].Copy();

No comments: