我正在尝试合并asp.net中的两个excel文件,并将它们作为一个表格显示在gridview中。下面的代码只显示一个表。谁能告诉我下面的代码有什么问题?如果你有更好的主意,请告诉我。
protected void MergTables()
{
string connString = ConfigurationManager.ConnectionStrings[hwTypes].ConnectionString;
OleDbConnection DBConnection = new OleDbConnection(connString);
DBConnection.Open();
OleDbCommand DBCommand = new OleDbCommand("SELECT * FROM [Sheet1$]", DBConnection);
OleDbDataAdapter da = new OleDbDataAdapter(DBCommand);
DataSet ds = new DataSet("Stock");
da.Fill(ds, "HWTypes");
DBConnection.Close();
string _stockConn = ConfigurationManager.ConnectionStrings[stockConn].ConnectionString;
DBConnection = new OleDbConnection(_stockConn);
DBConnection.Open();
DBCommand = new OleDbCommand("SELECT * FROM [Stock_voorlopig$]", DBConnection);
da = new OleDbDataAdapter(DBCommand);
da.Fill(ds, "Stock");
DBConnection.Close();
for (int i = 0; i < ds.Tables["HWTypes"].Rows.Count; i++)
{
ds.Tables["HWTypes"].Rows[i]["ProductID"] = ds.Tables["Stock"].Rows[i]["Partno"];
}
GridView1.DataSource = ds.Tables["Stock"];
GridView1.DataBind();
}
答案 0 :(得分:2)
问题是您在DataTable
中只使用了一个GridView
而且还没有加入。{/ p>
这是一种使用Linq-To-DataSet
连接两个表的方法,并创建一个匿名类型作为GridView
的数据源。
DataSet ds = new DataSet("Stock");
using (var dbConnection = new OleDbConnection(connString))
using (var dbCommand = new OleDbCommand("SELECT * FROM [Sheet1$]", dbConnection))
using (var da = new OleDbDataAdapter(dbCommand))
{
da.Fill(ds, "HWTypes");
}
using (var dbConnection = new OleDbConnection(stockConn))
using (var dbCommand = new OleDbCommand("SELECT * FROM [Stock_voorlopig$]", dbConnection))
using (var da = new OleDbDataAdapter(dbCommand))
{
da.Fill(ds, "Stock");
}
var joined = from rType in ds.Tables["HWTypes"].AsEnumerable()
join rStock in ds.Tables["Stock"].AsEnumerable()
on rType.Field<string>("ProductID") equals rStock.Field<string>("Partno")
select new
{
ProductID = rType.Field<string>("ProductID")
// add the other columns you need here
};
GridView1.DataSource = joined;
GridView1.DataBind();