1
Reply

How to add new column to existing excel sheet using C#

Chiquaqua

Chiquaqua

May 3 2012 4:31 PM
9.8k
Hello,

I have an excel sheet. How can I append new columns to the end of that sheet using C#.

Please help.

Here is my code

 public void AddColumn(string sheetName, string strConn)
        {
            try
            {         
                OleDbConnection oledbConn = new OleDbConnection(strConn);
                oledbConn.Open();
                string strQuery = string.Format("SELECT * FROM [" + sheetName + "]", oledbConn);
                OleDbDataAdapter oledbDA = new OleDbDataAdapter(strQuery, strConn);

                DataSet DS = new DataSet();
                oledbDA.Fill(DS);

                //add column to excel
                xlWorkBook = new Excel.Workbook();
                xlWorkSheet = new Excel.Worksheet();
                xlSheets = xlWorkBook.Worksheets;

                int lastRow = xlWorkSheet.Rows.CurrentRegion.Count;     

                xlApp = new Excel.Application();               
                xlWorkSheet = new Excel.Worksheet();              
                xlWorkSheet.get_Range(xlWorkSheet.Cells[1, 1],xlWorkSheet.Cells[xlWorkSheet.Rows.Count, 1]).Insert(System.Reflection.Missing.Value, Excel.XlInsertShiftDirection.xlShiftToRight);

                //DataColumn addColumn = new DataColumn();
                //addColumn.DataType = System.Type.GetType("System.String");
                //addColumn.ColumnName = "Test";
                //addColumn.ReadOnly = true;
                //addColumn.AllowDBNull = true;

                //DS.Tables[0].Columns.Add(addColumn);

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }

Answers (1)