EXCEL:将文本文件数据分解到EXCEL中的不同工作表

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文件
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值