Flag This Hub

C# program that interfaces with MS Excel: Create a new Excel file

By


1. Open a new Visual C# .NET windows application. Name the project CreateExcel.

2. In Solution Explorer, right-click the References node and select Add Reference. On the COM tab, select “Microsoft Excel 10.0 Object Library”, and then click OK.

3. Design a form. Add a Button and a Textbox.

4. Set Name property of Textbox to “txtExcelFileName”.

5. Set Name property of Button to “btnCreateExcel” and text property to “Create Excel File”.

6. In the code behind file import the library Microsoft Excel 10.0 Object Library using: using Excel;

7. Double click on the Button and pest the following code into the “btnCreateExcel_Click” event

//Add a reference to excel.application

Excel.Application exc;

try

{

//Creating new excel.application

exc = new Excel.Application();

//To make application visible

exc.Visible = true;

//To get the workbooks collection and add a new worksheet to workbook

Workbooks workbooks = exc.Workbooks;

_Workbook workbook = workbooks.Add(XlWBATemplate.xlWBATWorksheet);

//To save the excel file

exc.Save(txtExcelFileName.Text + ".xls");

MessageBox.Show("Excel file created successfully.");

txtExcelFileName.Text = "";

}

catch (Exception ex)

{

MessageBox.Show(ex.Message.ToString());

}

finally

{

exc = null;

}


Press F5 to build and run the project.

8. Put your excel file name with location like c:\MyExcelFile.xls in the text box and then press the “Create Excel File” Button. An excel file by the name MyExcelFile.xls will be created at the specified location.

No comments yet.

Submit a Comment
Members and Guests

Sign in or sign up and post using a hubpages account.



    Like this Hub?
    Please wait working