【Excel批处理】多个 txt 文本一键批量转excel(数据录入)

76 阅读4分钟

视频演示

多个 txt 文本一键批量转excel(数据录入) - 视频演示

前言

大家好,我是老罗软件,最近公司有一个变态的需求,有一堆txt文本,需要将文本的内容录入到excel表格里面去。单个文本是很容易操作的,但多个文件就相当耗费人力,今天老罗就是帮大家来解决这个问题的。

 

需求描述

有一批txt文本,抽查一个,打开内容如下:

image

 

需要将内容放到excel表格里面,需要处理分隔符 , 结果如下图:

image

 

问题是,每一个文本的分隔符还不一样!!!!!!!

如果只有一个文本,我想人工操作还是很简单的,但是我有一批文本都需要录入:

image

 

如果你想早点下班,抛开这些重复的繁琐步骤,节省更多时间充实自己,就请往下看。

 

解决方案

关注公众号:”老罗软件“  , 可以获取到解决方案软件下载。

 

这是一个专业解决excel多文件处理的方案, 找到 Excel功能大全, 然后在弹出的框里点击 ”数据录入“。

image

 

软件打开后, 我们设置好界面的参数:

image

 

 

下面我来详细介绍下参数意思。


 数据文件目录:  就是你的txt文本的位置。

 输出类型:    支持两种 “多个excel” , “一个excel多个表单” 。 

 标题行:       如果文本里面包含了标题,就勾选这个。

 分隔符:       选填,不填就根据内容智能挑选分隔符。

 

设置好之后,点击开始处理, 程序会一条一条处理, 执行完,打开结果文件,如果你选择的是 “一个excel多个表单” ,结果就如下图:

image

 

如果你选择的是 “多个excel文件” ,则结果如图:

image

 

如果您有疑问可以一起来探讨,功能就介绍到 这里 ,希望能帮助大家,感谢!!!

技术实现

非技术人员不需要观看!!  这里设计到的技术复杂, 我也就就简单讲解实现原理。

 

软件是基于Python开发的现代化办公自动化软件,主要使用了如下技术架构:

1. PySide6 (Qt6) - 现代化GUI界面框架:

2. springboot: excel的数据脱敏是通过后端java实现的。

  1. 文件处理:os.walk() - 递归遍历目录结构。

  2. http请求: requests框架。 

 

部分代码解析

项目的 开始 按钮,会开启一个QThread线程去处理,首先是获取excel目录, 然后通过os.walk遍历目录获取到所有文件,然后一个一个进行处理,处理的业务代码如下:

import logging
import re

from api.excel_api import ExcelAPI
from utils import FileUtils


class DataImportService:

    def __init__(self):
        self.api = ExcelAPI()


    def parse_file(self, file_path , delimiter):
        def _read_lines(path):
            encs = ['utf-8-sig', 'gb18030', 'utf-16']
            for enc in encs:
                try:
                    with open(path, 'r', encoding=enc) as f:
                        return [line.rstrip('\r\n') for line in f]
                except Exception:
                    continue
            out = []
            with open(path, 'rb') as f:
                for b in f:
                    s = None
                    try:
                        s = b.decode('utf-8', errors='ignore').rstrip('\r\n')
                    except Exception:
                        try:
                            s = b.decode('gb18030', errors='ignore').rstrip('\r\n')
                        except Exception:
                            s = b.decode('latin1', errors='ignore').rstrip('\r\n')
                    out.append(s)
            return out

        def _norm_delim(s):
            k = (s or '').strip().lower()
            if not k:
                return None, None
            if k in ('\t', 'tab', '制表符'):
                return 'regex', r'(?i)(?:\t|\t|tab)'
            if k in ('\n', 'newline'):
                return 'char', '\n'
            if k in ('space', '空格'):
                return 'whitespace', None
            if k in ('逗号', 'comma', '中文逗号'):
                return 'regex', r'[,,]'
            if k in ('英文逗号'):
                return 'char', ','
            if k in ('分号', 'semicolon'):
                return 'regex', r'[;;]'
            if k in ('竖线', '管道', 'pipe'):
                return 'regex', r'[||]'
            if k in ('冒号', 'colon'):
                return 'regex', r'[::]'
            if k in ('斜杠', 'slash'):
                return 'regex', r'[/、]'
            return 'regex', r'(?i)' + re.escape(s)

        def _eval_delim(lines, mode, sep):
            nonempty = [x for x in lines if x]
            if not nonempty:
                return (0.0, 0)
            counts = []
            for s in nonempty[:1000]:
                if mode == 'whitespace':
                    parts = re.split(r'\s+', s.strip())
                elif mode == 'regex':
                    parts = re.split(sep, s)
                else:
                    parts = s.split(sep)
                counts.append(len(parts))
            valid = sum(1 for c in counts if c > 1)
            if not counts:
                return (0.0, 0)
            mode_count = max(set(counts), key=counts.count)
            return (valid / len(counts), mode_count)

        def _choose_delim(lines):
            specs = [
                ('regex', r'[,,]'),
                ('regex', r'[;;]'),
                ('regex', r'[\||]'),
                ('regex', r'(?i)(?:\t|\t|tab)'),
                ('char', '\t'),
                ('regex', r'[::]'),
                ('regex', r'[/、]'),
                ('whitespace', None),
            ]
            best_spec = None
            best_score = (-1.0, -1)
            for spec in specs:
                score = _eval_delim(lines, spec[0], spec[1])
                if score[0] > best_score[0] or (score[0] == best_score[0] and score[1] > best_score[1]):
                    best_spec = spec
                    best_score = score
            if best_score[0] <= 0:
                return None, None
            return best_spec

        lines = _read_lines(file_path)
        mode, sep = _norm_delim(delimiter)
        if mode is None:
            mode, sep = _choose_delim(lines)

        out = []
        for s in lines:
            if not s:
                continue
            if mode == 'whitespace':
                parts = re.split(r'\s+', s.strip())
                out.append([p.strip() for p in parts])
            elif mode == 'regex' and sep:
                parts = re.split(sep, s)
                out.append([p.strip() for p in parts])
            elif mode == 'char' and sep:
                parts = s.split(sep)
                out.append([p.strip() for p in parts])
            else:
                out.append([s])
        return out


    def handle_file(self , file_path , out_excel_path ,delimiter,has_title):
        ## 读取文本文件
        data_content = self.parse_file(file_path , delimiter)
        print(data_content)
        self.api.import_data(out_excel_path, {
            "data_content":data_content,
            "has_title":has_title
        })

 

代码没有开源噢。 如果您有技术合作意向,还请联系本人。今天就介绍到 这里 ,希望能帮助大家,感谢!!!

 

结尾语

单个文本录入excel,我们用wps这些有名的工具就可以了,  但是针对多文件批量一键处理还可以尝试我文章中的介绍方法,可以为你提高很大的工作效率,让你有时间充实自己,而不是像机器人一样做重复的工作,没有任何新的收获。 就说到这里了, 如帮助到你了,还请点个赞,感谢!!