Jun 17, 2012

Easily Create Excel in .NET-Excel Object Model

As we all know that there are three ways to manage Excel files in .NET. Excel Object Model is one choice and the other is using Microsoft Jet Engineto connecting Excel; the third way is to get a 3rd party component to server as an interface.
Three Steps to Create Excel via C#.NET
Step 1 Add the Microsoft Excel Object Library to your project(14.0 or 12.0)
Create a new project and add the Microsoft Excel Object Library to you project.
Right click your project reference, choose add reference,  from .com tag, locate Microsoft Excel Object Library to add in.
Step 2 Using Namespace
using Excel = Microsoft.Office.Interop.Excel;
Step 3 Create Excel File in .NET
Excel.Application myXlsApp ;
Excel.Workbook myXlsWorkBook ;
Excel.Worksheet myXlsWorkSheet ;
object misValue = System.Reflection.Missing.Value;
xlApp = new Excel.ApplicationClass();
xlWorkBook = myXlsApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)myXlsWorkBook.Worksheets.get_Item(1);
xlWorkSheet.Cells[1, 1] = "http://www.e-iceblue.com";
myXlsWorkBook.SaveAs("D:\samples.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
myXlsWorkBook.Close(true, misValue, misValue);
MessageBox.Show("Excel file created , you can find the file D:\samples.xls");
private void releaseObject(object obj)
obj = null;
catch (Exception ex)
obj = null;
MessageBox.Show("Exception Occured while releasing object " + ex.ToString());
Press F5 to execute this program , You will get an Excel file in D discs.

No comments:

Post a Comment