1 首先将doc文档格式转换成docx
2 然后安装两个包 用到 python-docx 和 pandas 分别处理 word 和 excel
3 注意python的版本 要用64位的
4 code:
from docx import Document
import pandas as pd
word = '1111.docx'
excel = '2222.xlsx'
doc = Document(word) # word 文件
xls = pd.ExcelWriter(excel) # 用来写入 excel
tables = doc.tables # word 中所有 tables
print(tables)
tb = tables[0] # 第一个 table
print(dir(tb))
print(len(tb.rows), len(tb.columns)) # 行数、列数
mat = [] # 用 list 套 list 的方法装二维表格内容
for i, tb in enumerate(tables):
for c in range(0, len(tb.columns)):
row = []
for r in range(0, len(tb.rows)):
cell = tb.cell(r, c)
txt = cell.text if cell.text != '' else ' ' # 无内容用空格占位
print(txt)
row.append(txt)
mat.append(row)
# 用 mat 创建 DataFrame
df = pd.DataFrame(mat)
# print(df)
# DataFrame 写入 excel 中的某张 sheet
# 并且不要首列 index 和首行的 header(默认会有,比如数字标号)
df.to_excel(xls, sheet_name=f'{0}')
#break
#df.to_excel(xls, sheet_name=f'{i}', index=False, header=False)
xls.save() # 保存
xls.close() # 关闭5 用的文件 http://axuhongbo.top/file/?dl=ae3feb8b27353295943371afc461cbd8
6 参考链接 https://blog.csdn.net/HackerTom/article/details/101790510
7 另外一种客户要求的格式
from docx import Document
import pandas as pd
word = '1111.docx'
excel = '2222.xlsx'
doc = Document(word) # word 文件
xls = pd.ExcelWriter(excel) # 用来写入 excel
tables = doc.tables # word 中所有 tables
print(tables)
tb = tables[0] # 第一个 table
print(dir(tb))
print(len(tb.rows), len(tb.columns)) # 行数、列数
mat = [] # 用 list 套 list 的方法装二维表格内容
for i, tb in enumerate(tables):
for c in range(1, len(tb.columns)):
row = []
cell = tb.cell(0, 1)
txt = cell.text if cell.text != '' else ' ' # 无内容用空格占位
row.append(txt)
id = c
for r in range(0, len(tb.rows)):
cell = tb.cell(r, 0)
txt = cell.text if cell.text != '' else ' ' # 无内容用空格占位
if txt == '知识点编号':
id = r
break
print('id:'+str(id))
for r in range(1, 5):
if r < id:
cell = tb.cell(r, c)
txt = cell.text if cell.text != '' else ' ' # 无内容用空格占位
print(txt)
row.append(txt)
else:
txt = ' '
print(txt)
row.append(txt)
for r in range(id, len(tb.rows)):
cell = tb.cell(r, c)
txt = cell.text if cell.text != '' else ' ' # 无内容用空格占位
print(txt)
row.append(txt)
mat.append(row)
print("")
print("")
# 用 mat 创建 DataFrame
df = pd.DataFrame(mat)
# print(df)
# DataFrame 写入 excel 中的某张 sheet
# 并且不要首列 index 和首行的 header(默认会有,比如数字标号)
df.to_excel(xls, sheet_name=f'{0}', index=False, header=False)
#break
#df.to_excel(xls, sheet_name=f'{i}', index=False, header=False)
xls.save() # 保存
xls.close() # 关闭