0

I have problem. I need a program which creates a new excel file and add items to it from my application. If the file exists , I need to add next records to an existing file.

string Filetest = "C:\\Users\\Tom\\Documents\\File.xls";

        Excel.Application oApp;

        Excel.Workbook obook;


        oApp = new Excel.Application();
        obook = oApp.Workbooks.Add();
        oSheet = (Excel.Worksheet)obook.Worksheets.get_Item(1);
        if (File.Exists(Filetest))
        {


        }




            oSheet.Cells[i, 1] = comboBox1.Text;
            oSheet.Cells[i, 2] = comboBox4.Text;
            oSheet.Cells[i, 3] = textBox9.Text;
            oSheet.Cells[i, 4] = textBox5.Text;
            oSheet.Cells[i, 5] = maskedTextBox6.Text;
            oSheet.Cells[i, 6] = textBox1.Text;
            oSheet.Cells[i, 7] = textBox2.Text;
            oSheet.Cells[i, 8] = maskedTextBox1.Text;
            oSheet.Cells[i, 9] = textBox21.Text;
            oSheet.Cells[i, 10] = textBox12.Text;
            oSheet.Cells[i, 11] = textBox3.Text;
            oSheet.Cells[i, 12] = textBox23.Text;
            oSheet.Cells[i, 13] = maskedTextBox6.Text;
            oSheet.Cells[i, 14] = textBox6.Text;
            oSheet.Cells[i, 15] = textBox7.Text;
            oSheet.Cells[i, 16] = "034";
            oSheet.Cells[i, 17] = comboBox3.Text;
        oSheet.Cells[i, 18] = DateTime.Today.ToShortDateString();

        oSheet.Cells[1000, 1] = i;



        obook.SaveAs(Filetest);
        obook.Close();
        oApp.Quit();

        i++;

What should i put here ?

if (File.Exists(Filetest))
        {


        }

Pls help :( and thank you!

0

2 Answers 2

3
string Filetest = "C:\\Users\\Tom\\Documents\\File.xls";
Excel.Application oApp;
Excel.Workbook obook;

oApp = new Excel.Application();
if (File.Exists(Filetest))
{
    obook = oApp.Workbooks.Open(Filetest);
}
else
{
    obook = oApp.Workbooks.Add();
}

var oSheet = (Excel.Worksheet)obook.Worksheets.get_Item(1);

oSheet.Cells[i, 1] = comboBox1.Text;
// etc

obook.SaveAs(Filetest);
obook.Close();
oApp.Quit();
Sign up to request clarification or add additional context in comments.

Comments

0

I would invert your logic. Try figuring out if you have an existing document or if you need a new one. Something like:

    Excell.Application oApp ;
    if (File.Exists(Filetest))
    { 
       oApp = //lookup how to load an Excell app from a file
    }
    else{
       oApp = new Excel.Application();
       obook = oApp.Workbooks.Add();
    }

    oSheet = (Excel.Worksheet)obook.Worksheets.get_Item(1);

    //continue with your logic to fill in the cells and save.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.