使用Excel文件做为DataGrid的数据源是非常简单的,一旦数据被装载进来,就可以把数据再保存进SQL Server或XML中。我们只需要简单地使用OLE DB Provider 来访问Excel文件,然后返回DataSet即可。
下面是要显示的Excel数据contact.xls:
姓名 |
性别 |
地址 |
net_lover | Male | [email protected] |
amxh | Male | [email protected] |
孟子 E 章 | Male | [email protected] |
只需要指定Excel路径,并用[]选择一个工作表即可。
<%@ Page Language="C#" Debug="true" %> <%@ Import Namespace="System.Data"%> <%@ Import Namespace="System.Data.OleDb"%> <script runat="server"> private DataSet CreateDataSource(){ string strConn; strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=C:\\Inetpub\\wwwroot\\contacts.xls;"+ "Extended Properties=Excel 8.0;"; OleDbConnection conn = new OleDbConnection(strConn); OleDbDataAdapter myCommand = new OleDbDataAdapter("SELECT * FROM [ContactList$]", strConn); DataSet myDataSet = new DataSet(); myCommand.Fill(myDataSet); return myDataSet; } public void Page_Load(Object sender, EventArgs e){ if (!IsPostBack) { mygrid.DataSource = CreateDataSource(); mygrid.DataBind(); } } </script> <center> <form runat="server"> <asp:datagrid runat="server" AutoGenerateColumns="false" width="500" id="mygrid"> <HeaderStyle BorderColor="White" BackColor="black" ForeColor="White" Font-Bold="True" Font-Name="Arial" Font-Size="9" HorizontalAlign="Center"/> <ItemStyle BorderColor="" BackColor="#FFFFF0" ForeColor="Black" Font-Name="Arial" Font-Size="8" Font-Bold="False" HorizontalAlign="Center"/> <Columns> <asp:BoundColumn HeaderText="姓名" ReadOnly="true" DataField="姓名"/> <asp:BoundColumn HeaderText="性别" ReadOnly="true" DataField="性别"/> <asp:BoundColumn HeaderText="Email" ReadOnly="true" DataField="地址"/> </Columns> </asp:datagrid> </form>
本文地址:http://com.8s8s.com/it/it43175.htm