使用Excel文件做为DataGrid的数据源是非常简单的,一旦数据被装载进来,就可以把数据再保存进SQL Server或XML中。我们只需要简单地使用OLE DB Provider 来访问Excel文件,然后返回DataSet即可。
<%@ 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>