private void button1_Click(object sender, EventArgs e)
{
Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
Excel.Workbook workbook = app.Workbooks.Open(@"C:\\Users\\Admin\\Desktop\\Dropbox\\Vandit's Folder\\Internship\\Copy of test.xls");
Excel.Worksheet worksheet = workbook.ActiveSheet;
rcount = worksheet.UsedRange.Rows.Count;
MessageBox.Show(rcount.ToString());
rcount++;
if (textBox1.Text == "" && textBox2.Text == "")
{
MessageBox.Show("Both text boxes cannot be empty");
}
else if (textBox1.Text == "" && textBox2.Text != "")
{
worksheet.Cells[rcount, 1] = "";
worksheet.Cells[rcount, 2] = textBox2.Text;
}
else if (textBox1.Text != "" && textBox2.Text == "")
{
worksheet.Cells[rcount, 1] = textBox1.Text;
worksheet.Cells[rcount, 2] = "";
}
else
{
worksheet.Cells[rcount, 1] = textBox1.Text;
worksheet.Cells[rcount, 2] = textBox2.Text;
}
workbook.Save();
app.ActiveWorkbook.Close();
textBox1.Text = "";
textBox2.Text = "";
}
这是我正在使用的代码。当我运行此代码时,有时它可以完美运行并在 Excel 中正常更新。有时它会给我一个错误,说“文件已经存在。你想替换它吗?”。
此外,当我尝试通过目标文件夹正常打开 Excel 文件时,它要么说该文件被管理员阻止编辑,要么说该文件是只读的。因此,在文件像这样打开后,我无法编辑任何内容,因为在任何一种情况下,它都只能以只读模式打开。
此外,我之后无法删除该文件。