asp.Net excelのデータを読み出しgridviewにバインド

3153 ワード

フロントlabel,DropDownList,gridviewコントロール
aspx.csコアコード:
 
  
using System.Data.OleDb;//
public void Excel_Click(object sender, EventArgs e)
{
if (this.AttachmentFile.Value == "" && this.Label1.Text == "" && DropDownList2.SelectedValue == "")
{
Response.Write("window.alert(' ')");
}
if (this.AttachmentFile.Value != "" && this.DropDownList2.SelectedValue == "")
{
HttpFileCollection files = HttpContext.Current.Request.Files;
HttpPostedFile postedFile = files[0];
fileName = System.IO.Path.GetFileName(postedFile.FileName);
if (fileName != "")
{
postedFile.SaveAs("\\\\localhost\\ \\" + fileName);
}
string strConn;
strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + "\\\\localhost\\ \\" + fileName + ";Extended Properties=Excel 8.0;";//this.AttachmentFile.Value.ToString()
OleDbConnection conn = new OleDbConnection(strConn);
conn.Open();
DataTable sheetNames = conn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
foreach (DataRow dr in sheetNames.Rows)
{
DropDownList2.Items.Add(dr[2].ToString());
}
this.Label1.Text = "\\\\localhost\\ \\" + fileName;//this.AttachmentFile.Value.ToString();
conn.Close();
}
if (this.Label1.Text.ToString() != "" && this.DropDownList2.SelectedValue != "")// && this.DropDownList1.SelectedValue.ToString() != " "
{

// gridview
GridView1.DataSource = createDataSource(DropDownList2.SelectedValue.ToString(), this.Label1.Text.ToString());//, this.DropDownList1.SelectedValue.ToString()
GridView1.DataBind();


}


}
// Excel
private DataSet createDataSource(string select, string lable)

{
string strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + lable + ";Extended Properties=Excel 8.0;";
string strsql = "select , , , , , from [" + select + "] order by , , ";//excel
OleDbConnection conn = new OleDbConnection(strCon);
OleDbDataAdapter da = new OleDbDataAdapter(strsql, conn);
try
{
conn.Open();
DataSet ds = new DataSet();
da.Fill(ds);
conn.Close();
return ds;
}
catch (Exception e)
{
Response.Write("window.alert(' , " + e.Message + "')");
return null;
}
}

以上は07以前のバージョンexcelを挿入しました
07以降はマイナーチェンジのみ
 
  
string strCon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + lable + ";Extended Properties=Excel 12.0;";