返回
Featured image of post windows小工具txt转xlsx

windows小工具txt转xlsx

前言

4月换了份新工作。在新环境下要学习的地方很多;工作侧重点也有所改变。当然工作也更忙了。下班闲暇之余敲敲代码写写自己的程序也是一种享受IT职业的方式。 言归正传,换了新工作后我依然没有逃避txt转xlsx的问题,天天都在手动打开txt设值分隔符。某天终于按耐不住这重复无聊的步骤,于是基于《windows二维码工具3.0》写了这个小工具。

正文

内容

  1. txt 转 xlsx 网上源码真的很多
  2. 界面设计上,由于工作中需要一次转20多个txt,所以选择批处理方式。
  3. 合并单元格,日期格式,金额格式,小数点。xlsx格式这一直是头大的问题。但庆幸的是在我的工作中完全不需要设置xlsx格式,所以内容都是以“字符串”写入单元格,无合并单元格。
  4. 运行环境需要安装 Visual C++ Redistributable for Visual Studio 2015 安装包

演示

gif演示动画

部分代码

class WriteThread(QtCore.QThread):
    '''
    工作线程,处理txt转xlsx
    '''
    _signal = pyqtSignal(int, str)

    def __init__(self, srcfiles, dstfiles, split, coding):
        super(WriteThread, self).__init__()
        self.srcfiles = srcfiles
        self.dstfiles = dstfiles
        self.split = split
        self.coding = coding

    def run(self):
        currentfile = ''
        try:
            for i in range(len(self.srcfiles)):
                currentfile = self.srcfiles[i]
                self.txt_to_xlsx(self.srcfiles[i], self.dstfiles[i], self.split, self.coding)
            self._signal.emit(0, "OK")
        except Exception as e:
            self._signal.emit(-1, currentfile + ':' + str(e))
    def txt_to_xlsx(self, filename, outfile, split, encoding):
        fr = codecs.open(filename, 'r', encoding=encoding)
        wb = openpyxl.Workbook()
        ws = wb.active
        row = 0
        for line in fr:
            row += 1
  #          line = line.strip() 2020年3月28号
            line = line.split(split)
            col = 0
            for j in range(len(line)):
                col += 1
                ws.cell(column=col, row=row, value=line[j])
        wb.save(outfile)

打包exe说明

  1. 环境使用virtualenv (annaconda环境下打包exe会非常的大)
  2. 安装pyqt5 openpyxl pyinstaller
  3. 打包命令 pyinstaller -F -w txt2xlsx.py 或 pyinstaller txt2xlsx.spec

感悟

实际工具不难写,开发初期写了个cmd版本,在工作中试用了一天。实测可以满足需求,后续花了几个小时完成了界面开发。小工具满足自己的需求,也给大家参考参考,最最重要的还是要想法去折腾。所以我也自己琢磨着搞个小程序,收集些需求空闲之余折腾下。

源代码和工具下载

链接: https://pan.baidu.com/s/1bkITnqW85KNC0CSw52XuSQ 提取码: swca