代码之家  ›  专栏  ›  技术社区  ›  RobertJRu

c#如何使用OleDbCommand将指定值添加到Excel工作表中指定列名下的下一行

  •  0
  • RobertJRu  · 技术社区  · 7 年前

    对不起,如果这已经得到了回答,我搜索了几个小时,我也是一个全新的编程。

    我的问题是,如何让它插入一个新行,在现有数据(第16行)的正下方插入一个值,依此类推,每次单击导出按钮。我希望保留命令程序。

     private void exportBtn_Click(object sender, EventArgs e)
    {
        OleDbCommand newRow = new OleDbCommand();
        newRow.CommandType = CommandType.Text;
        newRow.CommandText = "INSERT INTO [Sheet1$] ([Company:], [County:], [State:], [Notes:], [User:], [Email:], [Username:], [Password:], [SMMM PWD:], [CAD:]) VALUES (1,2,3,4,5,6,7,8,9,10)";
        newRow.Connection = connectionExl;
    
        connectionExl.Open();
        newRow.ExecuteNonQuery();
        connectionExl.Close();
    }
    

    更新

    到目前为止,我可以得到下一个可用行的int值,现在我想将指定列下的值添加到该可用行。

    我该怎么做?

    private void exportBtn_Click(object sender, EventArgs e)
        {
            Excel.Application xlApp = StartExcel();
    //Excel.Application xlApp = new Excel.Application();  // instead of above line you can open new instance of Excel application and at the end of procedure xlApp.Application.Quit();
            Excel.Workbook myBook = xlApp.Workbooks.Open(@"C:\Users\path\path\excel.xlsx");
    
            Excel.Worksheet mySheet = myBook.Sheets[1];
            xlApp.Visible = true; // by default excel is invisible leave it invisible if you just like to add data and save it (also use new instance of Excel in this case) 
            int lastRow = mySheet.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell).Row;
            int openRow = lastRow + 1;
            mySheet.Cells[openRow, 1].Value = "your value for column A";
            mySheet.Cells[openRow, 2].Value = "your value for column B";
    
            myBook.Save();
            myBook.Close();
    
        }
    
        private static Excel.Application StartExcel() // would be better to make it public somewhere in your module
        {
            Excel.Application instance = null;
            try { instance = (Excel.Application)Marshal.GetActiveObject("Excel.Application"); }
            catch (System.Runtime.InteropServices.COMException ex) { instance = new Excel.Application(); }
            return instance;
        }
    
    1 回复  |  直到 7 年前
        1
  •  0
  •   Richard Mneyan    7 年前

    您可能需要Microsoft.Office.Interop。Excel或其他Excel库。 以下是一些Interop示例,您可以根据需要进行调整:

    public int getLastRow(Excel.Worksheet ws)
    {
        object[,] arData = ws.UsedRange.FormulaR1C1; // FormulaR1C1 returns only string in 2 dimensional array
        for (int iRow = arData.GetUpperBound(0); iRow > 0; iRow--) {
            for (int iCol = 1; iCol <= arData.GetUpperBound(1); iCol++) {
                if (arData[iRow, iCol].ToString() != "") { return iRow; }
            }
        }
        return 0;
    }
    

    int lastRow = ws.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell).Row;
    

    您可以启动Excel并根据需要进行调整,以设置为工作簿/工作表:

    using System.Runtime.InteropServices;
    using Excel = Microsoft.Office.Interop.Excel;
    
    void test()
    {
        Excel.Application xlApp = csXL.StartExcel();
        Excel.Worksheet ws = xlApp.ActiveSheet;
        int irow = getLastRow(ws);
    }
    
    public static Excel.Application StartExcel()
    {
        Excel.Application instance = null;
        try { instance = (Excel.Application)Marshal.GetActiveObject("Excel.Application"); }
        catch (System.Runtime.InteropServices.COMException ex) { instance = new Excel.Application(); }
        return instance;
    }
    

    在这种情况下,你不需要 OleDbCommand 您可以使用二维数组插入数据:

    object[,] arLoad = new object[0, 9]; arLoad[0, 0] = 1; arLoad[0, 1] = 2;
    ws.Range["A" + irow + ":J" + irow].FormulaR1C1 = arLoad; // or use Value instead of FormulaR1C1
    

    请记住,从二维数组将数据加载到Excel时,数组是基于0的,但从Excel读取时,下限数组是1。

    这里有几种在特定列/单元格下添加数据的方法,但在使用二维数组添加数据时,速度要快得多,如我上面所示。对于小项目,速度不是问题。

    Excel.Worksheet ws;
    Excel.Range rngXL = ws.Cells[3, 2]; // Set range to cell B3
    rngXL.Value = "Sample Test"; 
    rngXL.FormulaR1C1 = "= 3 + 2";
    ws.Cells[4,2].FormulaR1C1 = "5";
    ws.Cells[5, 3].Value = "2"; // Cell E3
    ws.Range["B5:D5"].Value = "Same text for cells B5,C5,D5";
    ws.Range["E5"].Value = "This cell is";
    

    也请阅读此处 Unable to open another excel file (when one excel is opened by .net) 使用简单的解决方案,如何使用Excel进行干净的退出。在我编辑您的代码的地方,将使用Excel应用程序的开放实例。如果您只需要更新excel并退出它,请使用新的excel实例,并在完成excel应用程序后使用。