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.IO;
using System.Text.RegularExpressions;
using System.Text;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
txtOpenPath.Text = Server.MapPath("~/File/产品列表.txt");//初始化文件打开路径
txtSavePath.Text = Server.MapPath("~/File/产品列表.xls");//初始化文件保存路径
}
}
protected void btnRead_Click(object sender, EventArgs e)
{
int P_int_Count = 0;//记录正在读取的行数
string P_str_Line, P_str_Content = "";//记录读取行的内容及遍历到的内容
List<string> P_str_List = new List<string>();//存储读取的所有内容
StreamReader SReader = new StreamReader(txtOpenPath.Text, Encoding.Default);//实例化流读取对象
while ((P_str_Line = SReader.ReadLine()) != null)//循环读取文本文件中的每一行
{
P_str_List.Add(P_str_Line);//将读取到的行内容添加到泛型集合中
P_int_Count++;//使当前读取行数加1
}
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();//实例化Excel对象
object missing = System.Reflection.Missing.Value;//获取缺少的object类型值
//打开指定的Excel文件
Microsoft.Office.Interop.Excel.Workbook workbook = excel.Application.Workbooks.Open(txtSavePath.Text, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing);
Microsoft.Office.Interop.Excel.Worksheet newWorksheet;//声明工作表对象
for (int i = 0; i < P_str_List.Count; i++)//遍历泛型集合
{
P_str_Content = P_str_List[i];//记录遍历到的值
newWorksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets.Add(missing, missing, missing, missing);//创建新工作表
newWorksheet.Cells[1, 1] = P_str_Content;//直接将遍历到的内容添加到工作表中
}
excel.Application.DisplayAlerts = false;//不显示提示对话框
workbook.Save();//保存工作表
workbook.Close(false, missing, missing);//关闭工作表
Response.Write("<script>alert('已经将文本文件的内容分解到了Excel的不同数据表中!');</script>");
}
protected void btnBrowse_Click(object sender, EventArgs e)
{
System.Diagnostics.Process.Start(txtSavePath.Text);//打开选择的Excel文件
}
}
EXCEL:将文本文件数据分解到EXCEL中的不同工作表
最新推荐文章于 2024-10-13 20:33:29 发布