无法保存现有的Excel文件

时间:2013-07-10 17:21:27

标签: c# visual-studio-2010 save export-to-excel

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文件时,它会说管理员阻止该文件进行编辑,或者说该文件是只读的。所以在文件打开之后无法编辑任何内容,因为在任何一种情况下它只在只读模式下打开。

此外,我之后无法删除该文件。

2 个答案:

答案 0 :(得分:0)

您需要退出(关闭)Excel,然后在完成后将worksheetworkbookapp变量设置为Nothing,这样它们就是实际发布(关闭)。

workbook.Save()
app.ActiveWorkBook.Close()
app.Quit()

worksheet = Nothing
workbook = Nothing
app = Nothing

答案 1 :(得分:0)

试试这个:

xlWorkbook.Save();
xlApp.DisplayAlerts = false;
xlApp.Visible = false;
xlWorkbook.Close(Microsoft.Office.Interop.Excel.XlSaveAction.xlSaveChanges, System.Reflection.Missing.V`enter code here`alue, System.Reflection.Missing.Value);
xlWorkbook = null;
xlWorksheet = null;
xlApp.Quit();
xlApp = null;

我可能会过度杀戮,但最好是安全而不是抱歉