0

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

4

1 回答 1

0

这是 VBA 代码,但您应该了解解决方案的要点。循环遍历单元格,直到找到空白单元格并将数据插入其中。解决方案的关键是 a) 将 Range 对象设置为工作表中的某个起始单元格(在本例中为“A1”)和 b) 通过使用 Range.Offset(1,0) 偏移每一行来循环遍历单元格) 来“移动”一行。

' select start range
Set rangePaste = Range("A1")

' loop until you find a blank cell in column A
Do Until rangePaste.Value = ""
  Set rangePaste = rangePaste.Offset(1, 0) ' move down row
Loop

'set cell value
rangePaste.Value = "abc"
于 2012-10-31T06:28:06.837 回答