Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert Columns between columns in excel

Tags:

c#

excel

I have an Excel File in which I have number of columns. Now I need to insert columns for example between "C" and "D".. so that the resulting columns should be "C" ,"New Column(D)", "E".. Please help me with this..

Parts of Code to open the Excel file is as below...

Microsoft.Office.Interop.Excel.Application application = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook workbook = application.Workbooks.Open(txtDestination.Text.ToString() + "\\" + Path.GetFileName(File_Name, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
                    Type.Missing, Type.Missing, Type.Missing, Type.Missing,
                    Type.Missing, Type.Missing, Type.Missing, Type.Missing,
                    Type.Missing, Type.Missing);
Worksheet worksheet = (Worksheet)workbook.ActiveSheet;
like image 967
Sundar Radnus Avatar asked Aug 31 '25 22:08

Sundar Radnus


1 Answers

I do it like this:

Select the column you want to insert the new column next to

Excel.Range oRng = oSheet.Range["I1"];

Insert the new column, specifying the direction you want to shift existing columns. In this case, we insert a new column to the left of I1; I1 will become H1

oRng.EntireColumn.Insert(Excel.XlInsertShiftDirection.xlShiftToRight, 
                    Excel.XlInsertFormatOrigin.xlFormatFromRightOrBelow);

To do something with the new column, such as set the header value, select the I1 range again.

oRng = oSheet.Range["I1"];

Set the column header text

oRng.Value2 = "Discount";
like image 189
a_arias Avatar answered Sep 03 '25 12:09

a_arias