把Excel文件中的数据读入到DataGrid中
使用Excel文件做为DataGrid的数据源是非常简单的,一旦数据被装载进来,就可以把数据再保存进SQL Server或XML中。我们只需要简单地使用OLE DB Provider 来访问Excel文件,然后返回DataSet即可。
下面是要显示的Excel数据contact.xls:
姓名
|
性别
|
地址
|
net_lover | Male | amxh@21cn.com |
amxh | Male | amxh@21cn.com |
孟子 E 章 | Male | amxh@21cn.com |
<%@ 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> |
只需要指定Excel路径,并用[]选择一个工作表即可。
更多内容请参考:
- HOW TO: Transfer Data to an Excel Workbook by Using Visual Basic .NET
- HOWTO: Automate Microsoft Excel from Microsoft Visual C# .NET
- HOW TO: Transfer XML Data to Microsoft Excel 2002 by Using Visual C# .NET