# Word操作库
pip install docx
# Excel操作库
pip install openpyxl
# 打包exe工具
pip install pyinstaller
参考地址:https://python-docx.readthedocs.io/en/latest/
注意事项
Word内部结构
# 有时候通过公开的方法无法取到数据时,可以考虑用内部的xml结构处理
from docx import Document
doc= Document(path)
body_element = doc._body._body
# 显示文档内部结构
print(body_element.xml)
#获取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)
doc= Document(path)
for table in doc.tables:
for row in table.rows:
for cell in row.cells:
print(cell.text)
doc= Document(path)
for g in doc.paragraphs:
for run in g.runs:
print(run.text)
参考地址:https://openpyxl.readthedocs.io/en/stable/usage.html
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()
原理就是获取每列最大宽进行设置
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
打包目的:在没有python环境的电脑上也可以运行我们的程序
PyInstaller test.py --onefile --noconsole
执行之后会在目录下生成dist与build文件夹
dist:文件夹里面的exe文件就是我们需要的exe。
现在在没有Python环境的电脑也可以执行了。
import glob
files= glob.glob(docxPath+"/*.docx")
import re
re.sub(r‘^[0-9,.]*‘, "", text)
import ntpath
name=ntpath.basename(path)
from os.path import isfile
isfile(path)
原文:https://www.cnblogs.com/lixiaobin/p/pythonexcelword.html