我有这个函数写入并保存到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