加入两个Excel文件并在GridView中显示

时间:2009-05-13 15:50:16

标签: c# asp.net excel

我有两个不同的Excel文件(.xls)。 KATIP中有一个名为excel1.xls的列,SAVCI中有一个名为excel2.xls的列。我想获取这些列并将它们合并到一个名为Nobet的表中,其中有两列:SAVCIKATIP

然后我想在ASP.NET中的Gridview控件中显示它们。我有工作代码,但是当我运行它时,它会获得名为KATIP的第一列,然后获取名为SAVCI的列。它们没有合并,它们显示为不同的列。

OleDbConnection DBConnection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" +
    Server.MapPath("~/App_Data/excel1.xls") + ";" + "Extended Properties=\"Excel 8.0;HDR=Yes\"");

DBConnection.Open();
string SQLString = "SELECT * FROM [Page1$]";
OleDbCommand DBCommand = new OleDbCommand(SQLString, DBConnection);
OleDbDataAdapter da = new OleDbDataAdapter(DBCommand);
DataSet ds = new DataSet("Nobet");
da.Fill(ds,"Nobet");
DBConnection.Close();
DBConnection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" +Server.MapPath("~/App_Data/excel2.xls") + ";" + "Extended Properties=\"Excel 8.0;HDR=Yes\"");

DBConnection.Open();
DBCommand = new OleDbCommand(SQLString, DBConnection);
da = new OleDbDataAdapter(DBCommand);
da.Fill(ds,"Nobet");
GridView1.DataSource = ds.Tables["Nobet"];
GridView1.DataBind();
DBConnection.Close();

1 个答案:

答案 0 :(得分:0)

我解决了我的问题......这就是我所做的:

OleDbConnection DBConnection = new
    OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" +
    Server.MapPath("~/App_Data/savcilik_katip.xls") + ";" + "Extended Properties=\"Excel 8.0;HDR=Yes\"");
DBConnection.Open();
OleDbCommand DBCommand = new OleDbCommand("SELECT * FROM [Sayfa1$]", DBConnection);
OleDbDataAdapter da = new OleDbDataAdapter(DBCommand);
DataSet ds = new DataSet("Nobet");
da.Fill(ds, "Nobet");
DBConnection.Close();
DBConnection = new
    OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" +
    Server.MapPath("~/App_Data/savcilik_savci.xls") + ";" + "Extended Properties=\"Excel 8.0;HDR=Yes\"");
DBConnection.Open();
DBCommand = new OleDbCommand("SELECT * FROM [Sayfa1$]", DBConnection);
da = new OleDbDataAdapter(DBCommand);
da.Fill(ds, "Nobetci");

DBConnection.Close();
for (int i = 0; i < ds.Tables["Nobet"].Rows.Count; i++)
{
    ds.Tables["Nobet"].Rows[i]["SAVCI"] = ds.Tables["Nobetci"].Rows[i]["SAVCI"];
}

GridView1.DataSource = ds.Tables["Nobet"];
GridView1.DataBind();