我有這個函數寫入並保存到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"))
{
}
除非您使用Excel功能,否則創建並附加到Excel可以輕鬆使用的.CSV文件會更容易。我發現Interop很困難,特別是如果程序在不同的PC上運行。如果你有Excel功能,你需要我下一步嘗試在Excel中使用VBA來完成這項工作。 Interop將是我的最後選擇。 – rheitzman
@rheitzman問題是我計劃加載這個excel文件到數據網格中,因此在一段時間後在.CSV文件中可能有問題 – Jevon