2016-11-10 89 views
0

我有这个函数写入并保存到excel文件。我想现在要做的就是追加到同一个现有的Excel文件。这个是函数:追加到现有的excel文件

private void button8_Click(object sender, EventArgs e)//creates excel file and writes data to it 
    { 
     Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application(); 

     if (xlApp == null) 
     { 
      MessageBox.Show("Excel is not properly installed!!"); 
      return; 
     } 

     if (System.IO.File.Exists("cross_check.xls")) 
     { 



     } 
     else 
     { 


      Excel.Workbook xlWorkBook; 
      Excel.Worksheet xlWorkSheet; 
      object misValue = System.Reflection.Missing.Value; 

      xlWorkBook = xlApp.Workbooks.Add(misValue); 
      xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1); 
      IndexProp += 1; 
      xlWorkSheet.Cells[IndexProp, 1] = comboBox2.Text; 
      xlWorkSheet.Cells[IndexProp, 2] = textBox5.Text; 
      xlWorkSheet.Cells[IndexProp, 3] = textBox2.Text; 
      xlWorkSheet.Cells[IndexProp, 4] = comboBox3.Text; 
      xlWorkSheet.Cells[IndexProp, 5] = textBox3.Text; 
      xlWorkSheet.Cells[IndexProp, 6] = comboBox1.Text; 


      xlWorkBook.SaveAs(@"cross_check.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue); 
      xlWorkBook.Close(true, misValue, misValue); 
      xlApp.Quit(); 

      Marshal.ReleaseComObject(xlWorkSheet); 
      Marshal.ReleaseComObject(xlWorkBook); 
      Marshal.ReleaseComObject(xlApp); 

      MessageBox.Show("Excel file created succcessfully"); 
     } 

    } 
} 

这种特殊的块是文件检查,如果它存在,然后呢追加操作,如果它的存在。我该怎么做呢?

if (System.IO.File.Exists("cross_check.xls")) 
     { 



     } 
+1

除非您使用Excel功能,否则创建并附加到Excel可以轻松使用的.CSV文件会更容易。我发现Interop很困难,特别是如果程序在不同的PC上运行。如果你有Excel功能,你需要我下一步尝试在Excel中使用VBA来完成这项工作。 Interop将是我的最后选择。 – rheitzman

+0

@rheitzman问题是我计划加载这个excel文件到数据网格中,因此在一段时间后在.CSV文件中可能有问题 – Jevon

回答

1

想要打开文件使其成为活动工作簿,然后进行所需的任何更改。从那里你可以保存它或做任何你想要的东西。

+0

要更改:我想继续添加然后保存文件。请原谅我,但我不是擅长交错。通常我会使用文本文件并打开,每当完成文件关闭并保存最初创建的名称。但在这个例子中,我发现excel文件在每次操作结束时都会保存。我如何保持开放并继续添加? – Jevon

+0

如何追加到excel文件中确实没有区别。你可以像使用文本文件一样进行。如果文件存在,则打开它 xlWorkBook = xlApp.Workbooks.Open(“filename”,0,true,5,“”,“”,true,Microsoft.Office.Interop.Excel.XlPlatform.xlWindows,“\ t” ,false,false,0,true,1,0); –

+0

C#interop只会编写你给它的任何命令。它不会保存文档,除非您调用保存,就像用户手动添加它时的工作方式一样。不清楚每次操作结束时保存的含义。 –