2016-11-10 90 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只會編寫你給它的任何命令。它不會保存文檔,除非您調用保存,就像用戶手動添加它時的工作方式一樣。不清楚每次操作結束時保存的含義。 –