C#中如何用DataList绑定excel的数据

2025-01-04 18:12:46
推荐回答(2个)
回答1:

C#中用dataList绑定exel的数据的方法:
1、display.asp代码

OnClick="btnUpload_Click" />








OnPageIndexChanging = "PageIndexChanging" AllowPaging = "true">

2、绑定excel的配置文件webConfig.xml:

connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};
Extended Properties='Excel 8.0;HDR={1}'"/>
connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};
Extended Properties='Excel 8.0;HDR={1}'"/>

3、后端c#代码:
protected void btnUpload_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
string FileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
string Extension = Path.GetExtension(FileUpload1.PostedFile.FileName);
string FolderPath = ConfigurationManager.AppSettings["FolderPath"];

string FilePath = Server.MapPath(FolderPath + FileName);
FileUpload1.SaveAs(FilePath);
Import_To_Grid(FilePath, Extension, rbHDR.SelectedItem.Text);
}
}

回答2:

OleDbConnection conn=new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=zk.xls; Extended Properties=Excel 8.0");
conn.Open();
string strsql="select * from [Sheet1$]";//如果有多张表 可用conn.GetOleDbSchemaTable取得一个集合,然后再动态的和数据控件绑定
OleDbCommand cmd=new OleDbCommand (strsql,conn);
OleDbDataAdapter ad=new OleDbDataAdapter ();
ad.selectCommand=cmd;
Datatable dt=new Datatable();
ad.fill(dt);
DataGridView1.Datasource=dt;//数据源与数据控件邦定