0

我正在尝试在 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();
        }
4

1 回答 1

2

问题是您只使用了一个DataTableGridView而您还没有加入两者。

这是一种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();
于 2012-12-18T09:36:26.913 回答