using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Word = Microsoft.Office.Interop.Word;
using System.Threading;
using office = Microsoft.Office.Core;
using System.Reflection;
using System.Data.OleDb;
using System.Data;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
txtAccess.Text = Server.MapPath("~/File/access.mdb");//初始化access文件路径
txtExcel.Text = Server.MapPath("~/File/excel.xls");//初始化Excel文件路径
BindDropDownList();
}
}
protected void btnRead_Click(object sender, EventArgs e)
{
try
{
string P_str_Con = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + txtAccess.Text + ";Persist Security Info=True";//记录连接Access的语句
string P_str_Sql = "";//存储要执行的SQL语句
OleDbConnection oledbcon = new OleDbConnection(P_str_Con);//实例化OLEDB连接对象
OleDbCommand oledbcom;//定义OleDbCommand对象
oledbcon.Open();//打开数据库连接
//向Excel工作表中导入数据
P_str_Sql = @"select * into [Excel 8.0;database=" + txtExcel.Text + "]." + "[" + DropDownList1.SelectedValue + "] from " + DropDownList1.SelectedValue + "";//记录连接Excel的语句
oledbcom = new System.Data.OleDb.OleDbCommand(P_str_Sql, oledbcon);//实例化OleDbCommand对象
oledbcom.ExecuteNonQuery();//执行SQL语句,将数据表的内容导入到Excel中
oledbcon.Close();//关闭数据库连接
oledbcon.Dispose();//释放资源
Response.Write("<script>alert('导入成功!');</script>");
}
catch
{
Response.Write("<script>alert('工作表已经存在,请选择其他数据表!');/script>");
}
}
protected void btnBrowse_Click(object sender, EventArgs e)
{
System.Diagnostics.Process.Start(txtExcel.Text);//打开选择的Excel文件
}
private void BindDropDownList()
{
string P_str_Con = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + txtAccess.Text + ";Persist Security Info=True";//记录连接Access的语句
OleDbConnection oledbcon = new OleDbConnection(P_str_Con);//实例化OLEDB连接对象
oledbcon.Open();//打开数据库连接
DataTable DTable = oledbcon.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });//获取所有数据表信息
oledbcon.Close();//关闭数据库连接
DropDownList1.Items.Clear();//清空下拉列表
for (int i = 0; i < DTable.Rows.Count; i++)//遍历数据表信息
{
DropDownList1.Items.Add(DTable.Rows[i][2].ToString());//将数据表名称添加到下拉列表中
}
if (DropDownList1.Items.Count > 0)//判断下拉列表中是否有项
DropDownList1.SelectedIndex = 0;//设置下拉列表默认选择第一项
}
}
EXCEL:读取ACCESS数据库中指定表数据到EXCEL
最新推荐文章于 2023-10-08 11:16:09 发布