Javy26
Javy26

Reputation: 385

appending to an existing excel file

I have this function which writes and saves to an excel file. What I want to do now is append to that same existing excel file.This is the function:

private void button8_Click(object sender, EventArgs e)//creates excel file and writes data to it
    {
        Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();

        if (xlApp == null)
        {
            MessageBox.Show("Excel is not properly installed!!");
            return;
        }

        if (System.IO.File.Exists("cross_check.xls"))
        {



        }
        else
        {


            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);
            IndexProp += 1; 
            xlWorkSheet.Cells[IndexProp, 1] = comboBox2.Text;
            xlWorkSheet.Cells[IndexProp, 2] = textBox5.Text;
            xlWorkSheet.Cells[IndexProp, 3] = textBox2.Text;
            xlWorkSheet.Cells[IndexProp, 4] = comboBox3.Text;
            xlWorkSheet.Cells[IndexProp, 5] = textBox3.Text;
            xlWorkSheet.Cells[IndexProp, 6] = comboBox1.Text;


            xlWorkBook.SaveAs(@"cross_check.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
            xlWorkBook.Close(true, misValue, misValue);
            xlApp.Quit();

            Marshal.ReleaseComObject(xlWorkSheet);
            Marshal.ReleaseComObject(xlWorkBook);
            Marshal.ReleaseComObject(xlApp);

            MessageBox.Show("Excel file created succcessfully");
        }

    }
}

This particular block is checking for the file if it exists and then does the append operation if it exists. How do I do this?

 if (System.IO.File.Exists("cross_check.xls"))
        {



        }

Upvotes: 0

Views: 1125

Answers (1)

Sam Marion
Sam Marion

Reputation: 690

You would want to open the file make it the active work book and then make any changes you want. From there you can save it or do what ever you want with it.

Upvotes: 1

Related Questions