您可能需要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应用程序后使用。