對不起,如果已經回答了這個問題,我搜索了幾個小時,而且我也是編程的新手。c#如何使用OleDbCommand將指定值添加到指定列名下的Excel工作表的下一個可用行
目前,我有我的Excel電子表格15行數據,下面的代碼將值插入行40,並再次按下導出按鈕將插入一個新行的值入行41等等
我的問題是我怎樣才能得到它插入一個新的行,直接在我現有的數據下面的值(第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();
}
UPDATE
到目前爲止,我可以得到下一個可用行的INT,現在我要指定列下添加值到一個可用行。
爲了便於讓我們說我有2列,名稱爲(列1,列2)和值我想是(1,2)
如何做到這一點,分別設置?
我迄今爲止代碼:
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;
}
您正在尋找[excel interop](https://msdn.microsoft.com/en-us/library/microsoft.office.interop.excel.aspx)熟悉MSDN文檔,因爲它將成爲您的單曲最大的資源。 –