The provided instructions and code are a basic guide to creating an Excel file in C# using the Microsoft Office Interop library.
Set Up Your Development Environment
Open Visual Studio and create a new Windows Forms Application project.
Create a new project and add a Button to the form.
Note: To create a new project go to File (on the top left corner), Select new and select project.
Add Necessary References
Click on Project tab and select Add Reference. Select Microsoft Excel 12.0 Object Library and click ok.
C# code
Double-click on the button to open the code-behind file.
Replace any existing code with the following code:
using System;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
namespace ExcelFileCreation
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void buttonCreateExcel_Click(object sender, EventArgs e)
{
Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
xlWorkSheet.Cells[1, 1] = "Hello, Excel!";
xlWorkBook.SaveAs("C:\\csharp-Excel.xlsx");
xlWorkBook.Close();
xlApp.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
MessageBox.Show("Excel file created. You can find the file at C:\\csharp-Excel.xlsx");
}
private void releaseObject(object obj)
{
try
{ System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
MessageBox.Show("Exception Occurred while releasing object: " + ex.ToString());
}
finally
{
GC.Collect();
}
}
}
}
The code initializes Excel, creates a new workbook and worksheet, adds data to cell A1, saves the workbook, closes Excel, and then releases the Excel objects.
The releaseObject method is used to release COM objects and ensure proper resource management.
The Excel file is saved as “C:\csharp-Excel.xlsx” in this example. You can change the file path and name as needed.