我有问题。我需要一个程序来创建一个新的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))
{
}
请帮助:(谢谢!
答案 0 :(得分: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();
答案 1 :(得分:0)
我会颠倒你的逻辑。尝试确定您是否有现有文档或是否需要新文档。类似的东西:
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.