Python实现Word表格转成Excel表格的示例代码

2020-09-27 0 541

准备工作

pip install docx
pip install openpyxl

具体代码

# 没有的先pip install 包名称
from docx import Document
from openpyxl import Workbook

document = Document(\'Docx文件路径.dicx\')

count = 0
tables = []
wb = Workbook()
ws = wb.active

# 设置列数,可以指定列名称,有几列就设置几个,
# A对应列1,B对应列2,以此类推
# 只能处理列数一致的表格,不一致的请在word文档(转下行)
# 中处理好后,再运行程序
ws[\'A1\'] = \'国家\'
ws[\'B1\'] = \'专利号\'
ws[\'C1\'] = \'自己设置\'
ws[\'D1\'] = \'懂?\'
ws[\'E1\'] = \'5\'
ws[\'F1\'] = \'6\'
ws[\'G1\'] = \'7\'
ws[\'H1\'] = \'8\'
ws[\'I1\'] = \'9\'
ws[\'J1\'] = \'10\'
ws[\'K1\'] = \'11\'
ws[\'L1\'] = \'12\'

total = len(document.tables)
print(\"总共\", total, \"个表格等待处理,请喝杯咖啡等待许久...\")
for index in range(0, total):
  table = []
  for row in document.tables[index].rows:
    line = []
    for grid in row.cells:
      line.append(grid.text)
    table.append(line)
    ws.append(line)
  count = count + 1
  print(\"第\", count, \"个表格正在处理...剩余\", total - count + 1, \"个表格\", \"\\n\")
  tables.append(table)
  # 测试专用,测试前30条数据请打开注释
  # if count == 30:
  #   break

wb.save(\"要保存xlsx的路径.xlsx\")
print(tables)
print(\"表格处理完成...\")

图片效果

Python实现Word表格转成Excel表格的示例代码

Python实现Word表格转成Excel表格的示例代码

Python实现Word表格转成Excel表格的示例代码

附加说明

本文章主要以实现功能为主,相关优化工作请自行解决。
文中代码可能存在隐含异常,或者有更好的实现途径,也请读者自行解决,或者在评论区留言,当大家看到,分享你的意见。

到此这篇关于Python实现Word表格转成Excel表格的示例代码的文章就介绍到这了,更多相关Python Word转成Excel内容请搜索自学编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持自学编程网!

遇见资源网 Python Python实现Word表格转成Excel表格的示例代码 http://www.ox520.com/25318.html

常见问题

相关文章

发表评论
暂无评论
官方客服团队

为您解决烦忧 - 24小时在线 专业服务