C# program that interfaces with MS Excel: Create a new Excel file
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
//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)
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.