I want to show data in datagridview in c# using from two source one from excel sheet and other from text file .I want to join these data source .For example if I get columns from Excel sheet excel1 excel2 AND Txt1 Txt2 from text file .Then I want to show result like excel1 excel2 Txt1 Txt2 in data grid view. Current i can show data from excel file using below code.
private void button_cars_Click(object sender, EventArgs e)
{
String name = "Car List";
String constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + "c:\\Vehicle_List.xlsx" + ";Extended Properties='Excel 12.0 XML;HDR=YES;';";
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand oconn = new OleDbCommand("Select CARID, BRAND, MODEL, FUEL, CC, YEAR From [" + name + "$]", con);
con.Open();
OleDbDataAdapter sda = new OleDbDataAdapter(oconn);
DataTable data = new DataTable();
sda.Fill(data);
dataGridViewMain.DataSource = data;
}
I handle this situation like this
public DataTable mergeSheetAndTextFile()
{
String name = "Sheet1";
String constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
"D:\\YOURPATH\\List.xlsx" +
";Extended Properties='Excel 12.0 XML;HDR=YES;';";
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand oconn = new OleDbCommand("Select col1,col2 From [" + name + "$]", con);
con.Open();
OleDbDataAdapter sda = new OleDbDataAdapter(oconn);
DataTable data = new DataTable();
sda.Fill(data);
data.Columns.Add("Txt1Col", typeof(System.String));
string[] txtFileLines= File.ReadAllLines("c://YOURPATH//test.txt");
int count=0;
foreach (DataRow row in data.Rows)
{
if(count<txtFileLines.Length){
row["Txt1Col"]=txtFileLines[count]
count++;`enter code here`
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.