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");//初始化文本文件路径
BindDropDownList();
}
}
protected void btnExport_Click(object sender, EventArgs e)
{
int P_int_Counts = CBoxShowCount().Tables[0].Rows.Count;//获取记录总数
int P_int_Page = P_int_Counts;//记录要分解为几个文件
int P_int_PageRow = 1;//记录每个文件的记录数
for (int i = 0; i < P_int_Page; i++)//循环访问每个文件
{
string filePath = System.IO.Path.Combine(txtTextFile.Text, DropDownList1.SelectedValue + i.ToString() + ".txt");
using (StreamWriter SWriter = new StreamWriter(filePath, false, Encoding.Default))//实例化写入流对象
{
string P_str_Content = "";//存储读取的内容
for (int r = i * P_int_PageRow; r < (i + 1) * P_int_PageRow; r++)//遍历数据集中表的行数
{
if (r < P_int_Counts)//判断遍历到的行数是否小于总行数
{
for (int c = 0; c < CBoxShowCount().Tables[0].Columns.Count; c++)//遍历数据集中表的列数
{
P_str_Content += CBoxShowCount().Tables[0].Rows[r][c].ToString() + " ";//记录当前遍历到的内容
}
P_str_Content += Environment.NewLine;//字符串换行
}
}
SWriter.Write(P_str_Content);//先文本文件中写入内容
SWriter.Close();//关闭写入流对象
}
}
string msg = "已经将" + DropDownList1.SelectedValue + "工作表中的数据分解到了" + P_int_Page.ToString() + "个文本文件中";
Response.Write("<script>alert('" + msg + "');</script>");
}
//获取Excel工作表中的数据
private DataSet CBoxShowCount()
{
//连接Excel数据库
OleDbConnection olecon = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + txtExcel.Text + ";Extended Properties=Excel 8.0");
OleDbDataAdapter oledbda = new OleDbDataAdapter("select * from [" + DropDownList1.SelectedValue + "$]", olecon);//从工作表中查询数据
DataSet myds = new DataSet();//实例化数据集对象
oledbda.Fill(myds);//填充数据集
return myds;//返回数据集
}
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;//设置下拉列表默认选项为第一项
}
}
EXCEL:将EXCEL数据分解到多个文本文件
最新推荐文章于 2022-08-28 15:18:57 发布