使用Microsoft.Office.Interop使用C#保存创建的文件

时间:2010-04-18 17:37:12

标签: c# excel interop

我有这个代码,它将创建excel文件和工作表,然后插入相同的值。

我面临的问题是我无法使用名称保存文件,因此我可以保存10个文件。

我使用了SaveAs但没有工作:

wb.SaveAs(@"C:\mymytest.xlsx", missing, missing, missing, missing,
     missing, XlSaveAsAccessMode.xlExclusive, missing, missing, missing, missing, missing);

这行代码会给我这个错误:

Microsoft Office Excel无法访问文件“C:\ A3195000”。有几个可能的原因:

•文件名或路径不存在。 •该文件正由另一个程序使用。 ?您尝试保存的工作簿与当前打开的工作簿具有相同的名称。

请建议解决这个问题。

这是我的代码:

private void button1_Click(object sender, EventArgs e)
{
  Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();

  if (xlApp == null)
  {
    MessageBox.Show("EXCEL could not be started. Check that your office installation and project references are correct.");
    return;
   }
   xlApp.Visible = true;

   Workbook wb = xlApp.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);
   Worksheet ws = (Worksheet)wb.Worksheets[1];

   if (ws == null)
   {
     MessageBox.Show("Worksheet could not be created. Check that your office installation and project references are correct.");
   }

   // Select the Excel cells, in the range c1 to c7 in the worksheet.
   Range aRange = ws.get_Range("C1", "C7");

   if (aRange == null)
   {
     MessageBox.Show("Could not get a range. Check to be sure you have the correct versions of the office DLLs.");
   }

   // Fill the cells in the C1 to C7 range of the worksheet with the number 6.
   Object[] args = new Object[1];
   args[0] = 6;
   aRange.GetType().InvokeMember("Value", BindingFlags.SetProperty, null, aRange, args);

   // Change the cells in the C1 to C7 range of the worksheet to the number 8.
   aRange.Value2 = 8;
   //       object missing = Type.Missing;
   //       wb.SaveAs(@"C:\mymytest.xlsx", missing, missing, missing, missing,
   //missing, XlSaveAsAccessMode.xlExclusive, missing, missing, missing, missing, //missing);

}

2 个答案:

答案 0 :(得分:1)

你真的有权将文件保存到C的根目录吗?我认为默认情况下你没有在Windows 7中使用它。

您可以尝试将Excel文件手动保存到C :.

答案 1 :(得分:0)

检查以下内容:

  • 使用"C:\\mymytest.xlsx"作为文件名(没有@符号和双反斜杠,因为反斜杠是转义字符)
  • 检查您是否还有另一个Excel运行副本 - 请参阅任务管理器中的EXCEL进程数。可能是您没有正确关闭Excel,然后在创建新工作簿时可以启动新实例 您可以通过确保始终具有不同的文件名(至少用于测试)来检查这是否是一个问题。