C#编写一个程序,将txt文本转换成excel

using OfficeOpenXml;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.LinkLabel;

namespace TxtToExcel
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void BtnToExcel_Click(object sender, EventArgs e)
        {
            string txtFilePath = "";
            using (OpenFileDialog openFileDialog = new OpenFileDialog())
            {

                openFileDialog.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";

                if (openFileDialog.ShowDialog() == DialogResult.OK)
                { 
                    txtFilePath = openFileDialog.FileName;
                }
            }

            // 检查文件是否存在 
            if (!File.Exists(txtFilePath))
            {
                MessageBox.Show("txt文件不存在!");
                return;
            }
            SaveFileDialog saveFileDialog = new SaveFileDialog();

            // 设置默认文件类型和扩展名
            saveFileDialog.DefaultExt = "xlsx";
            saveFileDialog.Filter = "Excel files (*.xlsx)|*.xlsx|All files (*.*)|*.*";
            // 使用EPPlus创建Excel文件  
            ExcelPackage.LicenseContext = OfficeOpenXml.LicenseContext.NonCommercial; // 设置许可  
            var package = new ExcelPackage();
            var ws = package.Workbook.Worksheets.Add("Sheet1");

            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                // 用户选择的文件路径  
                string filePath = saveFileDialog.FileName;
                //标题
                ws.Cells[1, 1].Value = "时间";
                ws.Cells[1, 2].Value = "级电压(kV)";
                ws.Cells[1, 3].Value = "本体球隙(mm)";
                ws.Cells[1, 4].Value = "截波球隙(mm)";
                ws.Cells[1, 5].Value = "原边电流(A)";
                ws.Cells[1, 6].Value = "DA输出数字量";

                // 用于跟踪已写入的时间戳  
                HashSet<string> seenTimestamps = new HashSet<string>();
                // 正则表达式用于匹配和提取数据  
                //Regex regex = new Regex(@"(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}).*?级电压:(-?\d+\.\d+) kV; 本体球隙:(\d+\.\d+)mm; 截波球隙:(\d+\.\d+); 原边电流:(\d+\.\d+)A ; DA输出数字量:(\d+)");
                Regex regex = new Regex(@"(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}).*?级电压:([+-]]?\d+\.\d+) kV; 本体球隙:(\d+\.\d+)mm; 截波球隙:(\d+\.\d+|-\d+\.\d+|\d+); 原边电流:(\d+(\.\d+)?)A ; DA输出数字量:(\d+)");
                int row = 2; // 从第二行开始写入数据(第一行是标题)
                //

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值