问题描述
大家好!
我有点卡在这里。我正在用excel构建一些数据库。现在我希望用户能够在必要时向其添加新数据。为此,我创建了一个程序,从excel文件中获取特定数据并将其写入数据表。这很好用。现在我想将数据表的数据添加到我的Excel数据库中。但我总是希望将新数据放入nexr free行。我的代码不能正常工作。它覆盖了excel文件的标题。也许我错过了解get_Range方法,但是现在我一无所知。
这是我到目前为止的代码:
Hi everyone!
I'm a little bit stuck here. I'm building somewhat of a data base with excel. Now I want the user to be able to add new data to it whenever necessary. For that I have created a program so far that gets specific data from excel files and writes those to a datable. This works just fine. Now I want to add the data of the datatable to my excel data base. But I always want the new data to be placed into the nexr free row. My code is not working correctly though. It over writes the headers of the excel file. Maybe I missunderstand the get_Range method, but right now I'm clueless.
This is the code I have so far:
private void datatableToMasterfile(DataTable drToEx)
{
string masterfileName = @"C:\Users\q371298\Desktop\Datenbank\Datenbank_Reifen_080415.xls";
// open Masterfile
Excel.Application xl = new Excel.Application();
Excel.Workbook wb = xl.Workbooks.Open(masterfileName);
Excel.Worksheet wsDatenBank = wb.Sheets.get_Item(1);
//Check for last filled row
Excel.Range dbRange = (Excel.Range)wsDatenBank.Cells[wsDatenBank.Rows.Count, 1];
int lastRow = (int)dbRange.get_End(Excel.XlDirection.xlUp).Row+3;
int newRow = lastRow + 1;
//Create Array to hold the data of DataTable
object[,] arr = new object[drToEx.Rows.Count, drToEx.Columns.Count];
//Fill DataTable in Array
for (int r = 0; r < drToEx.Rows.Count; r++)
{
DataRow dr1 = drToEx.Rows[r];
for (int c =0; c < drToEx.Columns.Count; c++)
{
arr[r, c] = dr1[c];
}
}
//Set Excel Range to paste the data
Excel.Range startCell = (Excel.Range)wsDatenBank.Cells[newRow, 1];
Excel.Range endCell = (Excel.Range)wsDatenBank.Cells[1 + drToEx.Rows.Count - 1, drToEx.Columns.Count];
Excel.Range range = wsDatenBank.get_Range(startCell, endCell);
//Fill array in Excel
range.Value = arr;
xl.Visible = true;
}
我真的很感激帮助,因为我还是比较新的。
Thanx很多!
Susie
I would really appreciate the help, as I am still fairly new to this.
Thanx a lot!
Susie
推荐答案
范围行=(范围)工作表.Rows [newRow];
Line.Insert();
Range Line = (Range)worksheet.Rows[newRow];
Line.Insert();
这篇关于如何将数据添加到“特定”数据?使用c#的Excel工作表中的单元格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!