我正在尝试覆盖/编辑excel文件中工作表中的一列,即使它没有引发任何错误,但仍然没有更新excel工作表。
这是我的代码:
Cursor.Current = Cursors.WaitCursor;
string path = Path.Combine(Application.StartupPath, ConfigurationManager.AppSettings["ExportTemplate"]);
oXL = new Microsoft.Office.Interop.Excel.Application();
oXL.Visible = false;
oXL.DisplayAlerts = false;
mWorkBook = oXL.Workbooks.Open(path, 0, false, 5, "", "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
//Get all the sheets in the workbook
mWorkSheets = mWorkBook.Worksheets;
//Get the allready exists sheet
mWSheet1 = (Microsoft.Office.Interop.Excel.Worksheet)mWorkSheets.get_Item("MetaData");
Microsoft.Office.Interop.Excel.Range range = mWSheet1.UsedRange;
foreach (Excel.Worksheet oworksheet in mWorkBook.Worksheets)
{
if (oworksheet.Name == "Disicpline")
{
long fullrow = oworksheet.Rows.Count;
int rowcount = oworksheet.UsedRange.Rows.Count; //get row count
//long lastrow = oworksheet.Cells[fullrow, 1].get_End(XlDirection.xlUp).Row;
oworksheet.Cells[rowcount, 1].value = txtDiscCode.Text;
oworksheet.Cells[rowcount, 2].value = txtDiscplinName.Text;
oworksheet.Cells[rowcount, 3].value = txtDiscCode.Text + txtDiscplinName.Text;
oworksheet.Cells[rowcount, 6].value = txtDiscCode.Text;
oworksheet.Cells[rowcount, 7].value = txtDiscCode.Text;
}
}
oXL.DisplayAlerts = false;
mWorkBook.SaveAs(path, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookDefault, Type.Missing, Type.Missing, false, false, Excel.XlSaveAsAccessMode.xlNoChange, Excel.XlSaveConflictResolution.xlLocalSessionChanges, Type.Missing, Type.Missing,
Type.Missing, Type.Missing);
mWorkBook.Close(true, path, Type.Missing);
Marshal.ReleaseComObject(mWorkBook);
GC.Collect();
GC.WaitForPendingFinalizers();
oXL.Quit();
答案 0 :(得分:0)
文件只是一个文件:
您可以使用File.Exist()
if (File.Exists("ExcelFilenameHere"))
{
File.Delete("ExcelFilenameHere");
}
在保存之前使用它