我有一个像下面这样的代码,它为我的记录生成一个 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”。