Milan90 Milan90 - 3 months ago 11
C# Question

Adding items to existing excel file

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!

Answer
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();
}

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

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

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