Knowing how to automate the creation of Microsoft Excel workbooks and worksheets can save individuals and organizations a lot of valuable time. In this shot, we will cover how we can do so using C#.
Before moving ahead, ensure you have a development environment with the .NET Framework set up on your device. For this shot, we will use Microsoft’s Visual Studio.
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;// Add the following namespace to work with excel filesusing Microsoft.Office.Interop.Excel;using _excel = Microsoft.Office.Interop.Excel;namespace Excel_with_C_Sharp{class Excel{// Create an excel application object, workbook oject and worksheet object_Application excel = new _excel.Application();Workbook workbook;Worksheet worksheet;// Method creates a new Excel file by creating a new Excel workbook with a single worksheetpublic void NewFile(){this.workbook = excel.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);this.worksheet = this.workbook.Worksheets[1];}// Method adds a new worksheet to the existing workbookpublic void NewSheet(){Worksheet newSheet = excel.Worksheets.Add(After: this.worksheet);}// Method saves workbook at a specified pathpublic void SaveAs(string path){workbook.SaveAs(path);}// Method closes Excel filepublic void Close(){workbook.Close();}}static void Main(){// Create an excel objectExcel file = new Excel();// Create a new workbook with a single sheetfile.NewFile();// Add a new sheet to the workbookfile.NewSheet();// Saving the file in a speicifed pathfile.SaveAs(@"file");// Closing the filefile.Close();}}
file.xlsx
to view a new Excel Workbook with two sheets: