国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > .NET > 正文

asp.net讀取excel中的數據并綁定在gridview

2024-07-10 13:27:02
字體:
來源:轉載
供稿:網友
前臺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("<script>window.alert('請選擇要導入的文件')</script>");
}
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("http:////localhost//文件夾//" + fileName);
}
string strConn;
strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + "http:////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 = "http:////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("<script>window.alert('沒有數據,或者" + e.Message + "')</script>");
return null;
}
}


以上是插入07以前版本excel

如果07版本以后只需要做小小修改

復制代碼 代碼如下:


string strCon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + lable + ";Extended Properties=Excel 12.0;";

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 海南省| 滨州市| 苏州市| 剑河县| 霸州市| 德兴市| 石嘴山市| 宿州市| 凤翔县| 房产| 天镇县| 水城县| 昂仁县| 玉门市| 武平县| 兴和县| 柞水县| 乐陵市| 长春市| 墨竹工卡县| 岗巴县| 正宁县| 榆林市| 苏尼特右旗| 永昌县| 旬邑县| 赤水市| 中江县| 专栏| 潮安县| 蕉岭县| 北碚区| 汶上县| 类乌齐县| 淅川县| 博乐市| 共和县| 东乌珠穆沁旗| 祁阳县| 宝兴县| 金门县|