添加项目到现有的excel文件

本文关键字:excel 文件 项目 添加 | 更新日期: 2023-09-27 18:03:42

我有问题。我需要一个程序,创建一个新的excel文件,并从我的应用程序中添加项目。如果文件存在,则需要向现有文件添加下一个记录。

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++;

我应该在这里写些什么?

if (File.Exists(Filetest))
        {

        }

请帮忙:谢谢!

添加项目到现有的excel文件

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

我会颠倒你的逻辑。试着弄清楚你是否有一个现有的文档,或者你是否需要一个新的文档。比如:

    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.