一滴水


(:不快乐是一天,快乐也是一天哦:)

导航

读取Excel表格中的数据[copy]

Posted on 2005-04-09 03:46  一滴水  阅读(2860)  评论(3编辑  收藏  举报
<% @Import Namespace="System.Data" %>
<% @Import Namespace="System.Data.OleDb" %>
<HTML>
    
<HEAD>
        
<title>如何读取Excel表格中的数据</title>
        
<script language="C#" runat="server">
        
            
void SubmitBtn_Click(object sender, System.EventArgs e)
            
{    
                
// 获取Excep文件的完整路径
                string source = File1.Value;
                string ConnStr 
= "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + source + ";Extended Properties=Excel 8.0";
                string query 
= "SELECT * FROM [Sheet1$]";
                OleDbCommand oleCommand 
= new OleDbCommand(query, new OleDbConnection(ConnStr));
                OleDbDataAdapter oleAdapter 
= new OleDbDataAdapter(oleCommand);
                DataSet myDataSet 
= new DataSet();
                
// 将 Excel 的[Sheet1]表内容填充到 DataSet 对象
                oleAdapter.Fill(myDataSet, "[Sheet1$]");
                
// 数据绑定
                DataGrid1.DataSource = myDataSet;
                DataGrid1.DataMember 
= "[Sheet1$]";
                DataGrid1.DataBind();
            }

        
        
</script>
    
</HEAD>
    
<body>
        
<form id="Form1" method="post" runat="server">
            
<H3>如何读取Excel表格中的数据</H3>
            请选择Excel表格:
<BR>
            
<INPUT type="file" id="File1" name="File1" runat="server" size="26"><br>
            
<asp:Button 
                
id="SubmitBtn" 
                runat
="server" 
                Text
="开始显示" 
                OnClick
="SubmitBtn_Click">
            
</asp:Button><br>
            
<br>
            
<asp:DataGrid id="DataGrid1" runat="server"></asp:DataGrid>
        
</form>
    
</body>
</HTML>