0
我有一個像下面這樣的代碼,爲我的記錄生成一個Excel文件,我想像我每次運行我的程序一樣,它會檢查最後一行,如果最後一行行不爲空,那麼它會將新數據插入到新行中。但是,我的代碼沒有得到期望的結果。任何人都可以幫助我呢?由於用每次保存添加新數據覆蓋Excel文件
Microsoft.Office.Interop.Excel.Application xla = new Microsoft.Office.Interop.Excel.Application();
string file = "TestingAccounts.xls";
Workbook wb = new Workbook();
Worksheet ws = new Worksheet();
object misValue = System.Reflection.Missing.Value;
try
{
wb = xla.Workbooks.Open(file, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
ws = (Worksheet)wb.Worksheets.get_Item(1);
xla.Workbooks.Open(file);
Range last = ws.Cells.SpecialCells(XlCellType.xlCellTypeLastCell, Type.Missing);
Range range = ws.get_Range("A1", last);
int lastUsedRow = last.Row + 1;
ws.Cells[lastUsedRow, 1] = "abc";
xla.DisplayAlerts = false;
wb.SaveAs(file, XlFileFormat.xlAddIn, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, XlSaveAsAccessMode.xlNoChange, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing);
wb.Close(true, misValue, misValue);
xla.Quit();
releaseObject(ws);
releaseObject(wb);
releaseObject(xla);
}
catch
{
MessageBox.Show("The excel file is not exist. Click ok to create new one");
wb = xla.Workbooks.Add(XlSheetType.xlWorksheet);
ws = (Worksheet)xla.ActiveSheet;
xla.DisplayAlerts = false;
wb.SaveAs(file, XlFileFormat.xlAddIn, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, XlSaveAsAccessMode.xlNoChange, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing);
wb.Close(true, misValue, misValue);
xla.Quit();
releaseObject(ws);
releaseObject(wb);
releaseObject(xla);
}
假設我上面的代碼想如果最後使用的行被發現,但在空在下一行添加「ABC」。
謝謝您的建議。我會嘗試一下!順便說一句,你能幫我解決這個問題,檢查excel是否已經存在,並創建一個新的,否則因爲上面的代碼在嘗試這樣做時會遇到錯誤。 – fj123
您可以使用.NET System.IO命名空間並執行if(File.Exists(fileName))。 – MikeB