Python操作Word与Excel并打包

时间:2023-03-09 21:36:11
Python操作Word与Excel并打包

安装模块

# Word操作库
pip install docx
# Excel操作库
pip install openpyxl
# 打包exe工具
pip install pyinstaller

Word操作

参考地址:https://python-docx.readthedocs.io/en/latest/

  1. 注意事项

    • 只能对openxml规格的docx格式操作
  2. Word内部结构

# 有时候通过公开的方法无法取到数据时,可以考虑用内部的xml结构处理
from docx import Document
doc= Document(path)
body_element = doc._body._body
# 显示文档内部结构
print(body_element.xml)
  1. 实例:获取文档目录
#获取xml的命名空间
def xpath_ns(tree):
"get xml namespace"
nsmap = dict((k, v) for k, v in tree.nsmap.items() if k)
return nsmap doc= Document(path)
body_element = doc._body._body
ns= xpath_ns(body_element)
# 获取目录所在节点
links = body_element.xpath('./w:p/w:hyperlink')
for link in links:
# 获取每一条目录的内容
runs= [Run(r,None) for r in link.xpath('w:r[@w:rsidRPr]',namespaces=ns)]
for r in runs:
# 打印内容
print(r.text)
  1. 实例:读取表格内容
doc= Document(path)
for table in doc.tables:
for row in table.rows:
for cell in row.cells:
print(cell.text)
  1. 实例:读取段落内容
doc= Document(path)
for g in doc.paragraphs:
for run in g.runs:
print(run.text)

Excel操作

参考地址:https://openpyxl.readthedocs.io/en/stable/usage.html

  1. 实例:格式设置
import openpyxl
from openpyxl.styles import PatternFill, Border, Side, Alignment,Font # 单元格字体
bft=Font(name="Meiryo UI",size=9,bold=True)
# 填充样式
headFill=PatternFill("solid", fgColor="d9d9d9")
# 边框线
thin = Side(border_style="thin", color="000000")
# 边框填充样式
border= Border(top=thin, left=thin, right=thin, bottom=thin)
# 对齐方式
align= Alignment(horizontal="center", vertical="center")
# 改行设置
wraptext= Alignment(vertical="center",wrapText=True) bk= openpyxl.load_workbook(filename="test.xlsx")
oSheet=bk["test"]
# Value设置数据
cell=oSheet.cell(row=row,column=col,value="hello world!")
cell.font=bft
cell.fill= headFill
cell.border= border
cell.alignment= align
#cell.alignment= wraptext
# 固定头三行三列
oSheet.freeze_panes='D4'
bk.save(expath)
bk.close()
  1. 实例:自动列宽

原理就是获取每列最大宽进行设置

import openpyxl

def getMaxLength(max,data):
"比较字符个数返回最大值"
length=len(str(data))
if length > max:
return length
else:
return max book= openpyxl.load_workbook(filename="test.xlsx")
sheet=book["test"]
for col in sheet.columns:
max_length=0
for cell in col:
max_length=getMaxLength(max_length,cell.value)
adjusted_width = (max_length + 2) * 1.2
sheet.column_dimensions[col[0].column_letter].width = adjusted_width

打包exe文件

打包目的:在没有python环境的电脑上也可以运行我们的程序

  1. cmd到py文件目录
    • 确认已经安装pyinstaller
  2. 执行打包
PyInstaller test.py --onefile --noconsole
  • --onefile: 表示打包成一个exe文件
  • --noconsole:表示不显示黑色命令窗口
  1. 执行之后会在目录下生成dist与build文件夹

    dist:文件夹里面的exe文件就是我们需要的exe。

    现在在没有Python环境的电脑也可以执行了。

其他操作

  1. 获取文件夹文件
import glob
files= glob.glob(docxPath+"/*.docx")
  1. 字符串匹配替换
import re
re.sub(r'^[0-9,.]*', "", text)
  1. 获取文件名称
import ntpath
name=ntpath.basename(path)
  1. 判断路径是否为文件
from os.path import isfile
isfile(path)