[英]c# How do I add specified values to the next available row of an Excel worksheet under specified column names using OleDbCommand
Sorry if this has been answered I searched for hours, and I am also brand new to programming. 抱歉,如果已经回答了我,我搜索了几个小时,并且对编程也很陌生。
Currently I have 15 rows with data in my excel spreadsheet, the code below will insert the values into row 40, and pressing the export button again will insert a new row with the values into row 41 etc... 目前,我的excel电子表格中有15行包含数据的代码,下面的代码会将这些值插入第40行,再次按下导出按钮会将具有这些值的新行插入第41行,依此类推。
My question is how can I get it to insert a new row with the values directly below my existing data (row 16) and so on with each proceeding export button click. 我的问题是我如何才能在现有数据(第16行)的正下方插入新行,并在每次进行导出按钮单击时依此类推。 I am looking to keep the command procedure.
我希望保留命令过程。
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 UPDATE
So far I can get the int of the next available row, Now I want to add values under specified columns to that available row. 到目前为止,我可以获取下一个可用行的int值,现在我想将指定列下的值添加到该可用行。
For ease let's say I have 2 columns named (column1, column2) and values I want to set respectively are (1,2) 为简单起见,假设我有两个名为(column1,column2)的列,而我想分别设置的值是(1,2)
How do I do this? 我该怎么做呢?
My code so far: 到目前为止,我的代码:
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;
}
You would probably need Microsoft.Office.Interop.Excel or other Excel library. 您可能需要Microsoft.Office.Interop.Excel或其他Excel库。 Below I put together some sample with Interop you can adjust as needed:
下面我将一些示例与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;
}
If your worksheet is not formatted beyond the data range, the below would give you the last row. 如果您的工作表的格式没有超出数据范围,则下面将为您提供最后一行。
int lastRow = ws.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell).Row;
You can start your Excel and adjust as needed to set to your workbook/worksheet: 您可以启动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;
}
In this case you wouldn't need OleDbCommand
you can just insert your data with 2 dimensional array: 在这种情况下,您不需要
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
Keep in mind when you load data into Excel from 2 dimensional array your array is 0 based, but when you read from Excel your Lower Bound array is 1. I would wait a day maybe someone would post better answer. 请记住,当您从二维数组将数据加载到Excel中时,您的数组是基于0的,但是当您从Excel中读取时,下界数组是1。我会等待一天,也许有人会发布更好的答案。
Here are few ways to add data under particular column/cell, but it is a lot faster when you are adding data with 2 dimensional array, like I showed above. 这是在特定的列/单元格下添加数据的几种方法,但是当您使用二维数组添加数据时,这要快得多,就像我上面显示的那样。 for small entries speed is not issue.
对于小条目速度不是问题。
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";
Also read here Unable to open another excel file (when one excel is opened by .net) with simple solution how to make clean Exit with Excel. 另请阅读此处无法打开简单的解决方案,如何使用Excel干净退出, 无法打开另一个excel文件(当.net打开一个excel时) 。 Where I have edited your code would use open instance of Excel Application.
我在其中编辑代码的地方将使用Excel Application的开放实例。 If you just need to update excel and exit it use new instance of Excel and when you done quite the excel application.
如果您只需要更新excel并退出它,请使用Excel的新实例以及完成excel应用程序的时间。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.