EXCEL:读取文本文件到EXCEL并对数据列进行格式化

来源:互联网 发布:淘宝分销需要交钱吗 编辑:程序博客网 时间:2024/06/05 07:16
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 = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets.Add(missing, missing, missing, missing);        excel.Application.DisplayAlerts = false;//不显示提示对话框        for (int i = 0; i < P_str_List.Count; i++)//遍历泛型集合        {            P_str_Content = P_str_List[i];//记录遍历到的值            if (Regex.IsMatch(P_str_Content, "^[0-9]*[1-9][0-9]*$"))//判断是否是数字                newWorksheet.Cells[i + 1, 1] = Convert.ToDecimal(P_str_Content).ToString("¥00.00");//格式化为货币格式,再添加到工作表中            else                newWorksheet.Cells[i + 1, 1] = P_str_Content;//直接将遍历到的内容添加到工作表中        }        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文件    }}

0 0
原创粉丝点击