[英]dynamically select range of cells in excel sheet in C#.Net
我正在准備將數據從excel表格導入到sql server 2005中。我幾乎沒有要求,但是我將數據從excel表格導入到database.I進行了很多搜索,但找不到答案,我也感到困惑,所以想到在這里問我的查詢。Excel工作表格式就是這種方式。
第一行包含標題“交易”
第二行包含子標題“日期”
從第三行開始,數據以列名開頭,后跟resp.rows中的數據。
CustId CustName OUtlet TerminalNum Date DateTime Amount<br/>
1 Nazima SS 770012234 1/22/2011 1/22/2011 12:34:45 1500.50<br/>
這是數據在Excel工作表中的方式。
我曾嘗試上傳圖片,但發布問題時卻顯示問題,所以我輸入了圖片。
我的要求是,當我將數據從Excel工作表導入數據庫時,我必須忽略前兩行,而必須從第三行中導入數據,並且我必須在一個表中導入totalamount(62854)和total.of rows(11)和其他表中的數據。
通過使用以下語句,我可以使用oledbcommand導入數據:
oledbcommand cmd=new oledbcommand("select * from [sheet1$]",con);
和
oledbcomaand cmd=new oledbcommand("select * from [sheet1$A3:H13]",con);
這兩個語句都起作用,但是我不希望這樣,因為最終用戶可以從任何單元格輸入數據,所以我想動態指定工作表以及范圍。最終用戶在哪個單元格中開始輸入數據,數據以及總量並且沒有行數應該毫無問題地導入數據庫的reso.tables中。
而且我還想知道,每當最終用戶在excel工作表中輸入新行而不插入表中已經存在的先前行時,如何在表中插入新行。
接下來,我想知道哪種方法是將數據從excel導入數據庫的最佳方法。是通過excel interop還是通過Oledb。
給我一些指導,我需要如何執行這些過程。
希望你理解我的懷疑。
使用Interop
將會是一種簡單而更好的方法。 但是,我從未使用過它,因此不知道如何使用它。
My requirement is that when i import data from excel sheet to database i have to ignore the first two rows and have to import data from third row and i have to import totalamount(62854) and total no.of rows(11) in one table and data in other table.
OleDbDataAdapter
將數據加載到DataSet
DataSet
上進行操作,即執行所需的操作。 DataSet
到你想要的Database
編輯:
樣例代碼:
public static void ExcelOperations(string ConnectionString)
{
try
{
DataTable Sheets = new DataTable();
using (OleDbConnection connection = new OleDbConnection(ConnectionString))
{
connection.Open();
//Retrieve the Sheets
Sheets = connection.GetSchema("Tables");
//Display the Sheets
foreach (DataRow sheet in Sheets.Rows)
{
Console.WriteLine(sheet["TABLE_NAME"]);
}
//Take the First Sheet
string firstSheet = Sheets.Rows[0][2].ToString();
//Retrieve contents
DataSet Contents = new DataSet();
using (OleDbDataAdapter adapter = new OleDbDataAdapter("select FirstName,LastName,Email,Mobile from [" + firstSheet + "]", connection))
{
adapter.Fill(Contents, "MyTable");
}
//Display the contents
foreach (DataRow content in Contents.Tables["MyTable"].Rows)
{
Console.WriteLine(content[0] + " | " + content[1] + " | " + content[2] + " | " + content[3]);
}
Console.WriteLine();
//Remove First Row; Note: This is not heading!
Contents.Tables["MyTable"].Rows.RemoveAt(0);
//Since the first row is removed, Second Row becames first row now.
//Clearing the LastName of our First Row.
Contents.Tables["MyTable"].Rows[0][1] = "";
//Displaying the Contents
foreach (DataRow content in Contents.Tables["MyTable"].Rows)
{
Console.WriteLine(content[0] + " | " + content[1] + " | " + content[2] + " | " + content[3]);
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.