您的位置:首页 > 数据库

EXCEL:读取EXCEL指定表数据到文本文件

2014-04-26 13:23 429 查看
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;
using System.Text;
using System.IO;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
txtExcel.Text = Server.MapPath("~/File/excel.xls");//初始化Excel文件路径
txtTextFile.Text = Server.MapPath("~/File/textFile.txt");//初始化文本文件路径
BindDropDownList();
}
}

protected void btnExport_Click(object sender, EventArgs e)
{
//连接Excel数据库
OleDbConnection olecon = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + txtExcel.Text + ";Extended Properties=Excel 8.0");
olecon.Open();//打开数据库连接
OleDbDataAdapter oledbda = new OleDbDataAdapter("select * from [" + DropDownList1.SelectedValue + "$]", olecon);//从工作表中查询数据
DataSet myds = new DataSet();//实例化数据集对象
oledbda.Fill(myds);//填充数据集
StreamWriter SWriter = new StreamWriter(txtTextFile.Text, false, Encoding.Default);//实例化写入流对象
string P_str_Content = "";//存储读取的内容
for (int i = 0; i < myds.Tables[0].Rows.Count; i++)//遍历数据集中表的行数
{
for (int j = 0; j < myds.Tables[0].Columns.Count; j++)//遍历数据集中表的列数
{
P_str_Content += myds.Tables[0].Rows[i][j].ToString() + "  ";//记录当前遍历到的内容
}
P_str_Content += Environment.NewLine;//字符串换行
}
SWriter.Write(P_str_Content);//先文本文件中写入内容
SWriter.Close();//关闭写入流对象
SWriter.Dispose();//释放写入流所占用的资源
Response.Write("<script>alert('已经将" + DropDownList1.SelectedValue + "工作表中的数据成功写入到了文本文件中');</script>");
}
protected void btnBrowse_Click(object sender, EventArgs e)
{
System.Diagnostics.Process.Start(txtTextFile.Text);//打开选择的Excel文件
}

private void BindDropDownList()//对下拉列表进行数据绑定
{
DropDownList1.Items.Clear();//清空下拉列表项
//连接Excel数据库
OleDbConnection olecon = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + txtExcel.Text + ";Extended Properties=Excel 8.0");
olecon.Open();//打开数据库连接
System.Data.DataTable DTable = olecon.GetSchema("Tables");//实例化表对象
DataTableReader DTReader = new DataTableReader(DTable);//实例化表读取对象
while (DTReader.Read())//循环读取
{
string P_str_Name = DTReader["Table_Name"].ToString().Replace('$', ' ').Trim();//记录工作表名称
DropDownList1.Items.Add(P_str_Name);//将工作表名添加到下拉列表中
}
DTable = null;//清空表对象
DTReader = null;//清空表读取对象
olecon.Close();//关闭数据库连接
DropDownList1.SelectedIndex = 0;//设置下拉列表默认选项为第一项
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  .net c# excel sql server office