Although the data has been imported to an Excel worksheet, sometimes, we need to insert rows or columns for writing additional data information. For example, there is an Excel file about employees contact information with several groups, each of which shows information in one department. If a new employee joins one department, we need to insert a new row in the corresponding group and writing his/her contact information.
This post focuses on how to insert rows and columns in Excel worksheet with C#. Because Spire.XLS for .NET is used in this example, so please download and install it on your system at the beginning. Then, add necessary reference, Spire.XLS dll file and System.Drawing.
- Load file which we want to insert rows and columns and initialize Worksheet.
- Insert row with worksheet.InsertRow(). If we just want to add one row, pass one parameter to this method. This parameter sepcifies where to insert the row.
- Copy contents from other rows to new rows by using worksheet.Copy(). There are three parameters in this method, the source range and a bool value.
- Save and launch file.
static void Main(string args)
//Load File and Initialize Worksheet
Workbook workbook = new Workbook();
workbook.LoadFromFile(@”D:\Work\My Documents\Student Info.xlsx”);
Worksheet worksheet = workbook.Worksheets;
//Insert Blank Row
//Insert Row with Copying Data from Other Rows
//Set Style for New Rows
worksheet.Range[“A13:E14”].Style.Color = Color.LightCyan;
worksheet.Range[“A13:E14”].Style.Font.IsBold = true;
//Insert Blank Column
//Insert Column with Copying Data from Other Columns
worksheet.Copy(worksheet.Range[“D1:E21”], worksheet.Range[“G1:H21”], true);
//Set Style for New Columns
worksheet.Range[“G1:H21”].Style.Font.IsBold = true;
worksheet.Range[“G1:H21”].Style.Color = Color.LightCyan;
//Save and Launch File
Result Shown As Following:
Freely Download Spire.XLS for .NET