您的位置:首页 > 编程语言 > Python开发

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

2019-05-05 21:48 691 查看

果然用了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
7ff7
):
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)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: