小白的第一个python办公自动化项目——自动生成文件索引表(pandas简化版)

果然用了pandas容易多了。。可惜pandas对hyperlink不支持,不能一简到底。。

完整代码如下:

#!/usr/bin/env python
# coding: utf-8


import os, xlwt, re
import pandas as pd
from xlrd import open_workbook

book = xlwt.Workbook(encoding='utf8', style_compression=0)  # 初始化工作簿
sheet = book.add_sheet('sheet1')  # 新建工作表

path = r"E:\箱单"  # 指定文件夹路径

"""用os来提取指定文件夹下所有文件名、文件路径以及文件名中关键词,分别加入对应的list,用字典生成DataFrame"""


def get_file(path):
    n = 0
    files_date = []
    files_name = []
    files_path = []
    marks = []
    data = {}
    for root, dirs, files in os.walk(path):

        for file in files:
            n += 1

            # 把提取的日期加入files_date,若无日期,为空
            date = re.search(r'(\d{4}-?\d{1,2}-?\d{1,2})', file)
            if date:
                file_date = date.group()
            else:
                file_date = " "
            files_date.append(file_date)

            # 把文件名加入files_name
            file_name = file
            files_name.append(file_name)

            # 把文件路径加入files_path
            file_path = os.path.join(root, file)
            files_path.append(file_path)

            # 把提取的唛头加入marks,若无唛头,写入“无唛头信息”
            pattern = re.compile(r'(Q-[0-9a-zA-Z]+)')
            result = re.findall(pattern, file)
            if result:
                mark = str(" ".join(i for i in result))
            else:
                mark = "无唛头信息"
            marks.append(mark)

            # 用pandas建一个临时的表格存入DataFrame
    data["发货日期"] = files_date
    data["文件名"] = files_name
    data["文件路径"] = files_path
    data["唛头"] = marks

    df = pd.DataFrame(data)
    df.set_index("发货日期", inplace=True)
    df = df.sort_values(by=["发货日期"], ascending=False)
    df.to_excel(r"temp.xls")


get_file(path)

workbook = r"temp.xls"

"""以下用xlrd读取临时表格,并用xlwt预建excel文件,存入公式生成的文件超链接,并删除临时表格"""
def create_indexer(workbook):
    bk = open_workbook(workbook, formatting_info=True)
    st = bk.sheets()[0]
    my_book = xlwt.Workbook()
    my_sheet = my_book.add_sheet("箱单索引表")
    my_sheet.col(1).width = 256*55
    my_sheet.col(2).width = 256*35
    my_sheet.write(0, 0, "发货日期")
    my_sheet.write(0, 1, "箱单链接")
    my_sheet.write(0, 2, "唛头")

    for rowx in range(1, st.nrows):
        f_date = st.cell_value(rowx, 0)
        my_sheet.write(rowx, 0, f_date)

        f_name = st.cell_value(rowx, 1)
        f_path = st.cell_value(rowx, 2)
        my_sheet.write(rowx, 1, xlwt.Formula('HYPERLINK("%s";"%s")'%(f_path,f_name)))

        f_mark = st.cell_value(rowx, 3)
        my_sheet.write(rowx, 2, f_mark)

    os.remove(r"temp.xls")
    my_book.save(r'C:\Users\61782_000\Desktop\箱单索引表.xls')


create_indexer(workbook)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值