Access和Excel做数据源
时间:2010-12-04 来源:阿-辉
App_Data文件夹下面的,这里的复制不是直接将文件拖进来,而是复制文件将数据文件复制到目录下面去
,然后点击解决方案上面有个显示所有文件的按钮,然后将数据文件包含在项目中就行了!
Access作为数据源
//引入命名空间
using System.Data.OleDb;
namespace WebApplication
{
public class AccessHelper
{
static readonly string strConnection = "Provider=Microsoft.ACE.OLEDB.12.0;Data
Source=F:\\试验\\Access\\WebAccess\\WebApplication\\App_Data\\Database.accdb;Persist
Security Info=False";
public OleDbConnection OledCon()
{
OleDbConnection con = new OleDbConnection(strConnection);
con.Open();
return con;
}
public DataSet GetData(string strAccess)
{
OleDbConnection odc = OledCon();
using (odc)
{
OleDbDataAdapter odda = new OleDbDataAdapter(strAccess, odc);
DataSet ds = new DataSet();
odda.Fill(ds);
return ds;
}
}
}
}
页面后台
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Get();
}
}
AccessHelper Ah = new AccessHelper();
protected void Get()
{
string strsql = "select * from 个人信息表";
DataSet ds = Ah.GetData(strsql);
DLOne.DataSource = ds;
DLOne.DataBind();
}
}
页面前台
<form id="form1" runat="server">
<div>
<asp:DataList ID="DLOne" runat="server">
<ItemTemplate>
<%# Eval("myname") %>
</ItemTemplate>
</asp:DataList>
</div>
</form>
Excel作为数据源
//引入命名空间
using System.Data.OleDb;
namespace WebApplication
{
public partial class Excel
{
public DataSet GetDataFromExcel_(string strsql)
{
OleDbConnection connection = new OleDbConnection
("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=F:\\试验\\Access\\WebAccess\\WebApplication\
\App_Data\\Info.xls;Extended Properties=Excel 8.0");
OleDbDataAdapter dataadapter = new OleDbDataAdapter(strsql,connection);
DataSet dataset = new DataSet();
dataadapter.Fill(dataset);
return dataset;
}
}
}
页面后台
public partial class ExcelHelper : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GetDatal();
}
}
Excel E = new Excel();
protected void GetDatal()
{
DataSet ds= E.GetDataFromExcel_("select * from [info$]");
gridview.DataSource = ds;
gridview.DataBind();
}
}
页面前台
<form id="form1" runat="server">
<div>
<asp:GridView ID="gridview" runat="server">
</asp:GridView>
</div>
</form>