使用python读取word,写入execl

word里面有2张表,需要找到第二张表,并写入execl中:使用python读取word,写入execl

代码如下:

#coding:utf-8
import os
from docx import Document
import win32com
from win32com.client import Dispatch, constants def parse_docx(f,title):
d = Document(f)
for t in d.tables:
'''获取需要的表'''
tbTitle = t.cell(0, 0).text
if title == tbTitle:
tableInfo = []
columnLen = len(t.columns)
rowLen = len(t.rows)
for i in range(0,columnLen):
tmp = []
for row in t.rows:
tmp.append(row.cells[i].text)
#删除第一个元素->表名
del(tmp[0])
tableInfo.append(tmp)
#返回的后两个参数表示tableInfo表的行数和列数
return [tbTitle,tableInfo,rowLen-1,columnLen]
return None def writeExecl(fileName,sheet,tableInfo):
excel = win32com.client.Dispatch('Excel.Application')
excel.Visible=0
excel.DisplayAlerts=0
#对传入文件名的处理
if fileName:
if os.path.exists(fileName):
workbook = excel.Workbooks.Open(fileName)
else:
workbook = excel.Workbooks.Add()
workbook.SaveAs(fileName)
else:
workbook = excel.Workbooks.Add() try:
sht = workbook.Worksheets(sheet)
except:
sheetNew = workbook.Worksheets.Add()
sheetNew.Name =sheet
sheetNew.Activate()
sht = workbook.Worksheets(sheet)
#execl表格是从1开始的
sht.Cells(1, 1).Value = tableInfo[0]
#把tableInfo看作是一行数据,依次赋值
for i in range(0,tableInfo[3]):
for j in range(0,tableInfo[2]):
sht.Cells(j+2, i+1).Value = tableInfo[1][i][j] workbook.Save()
excel.Application.Quit() if __name__ == "__main__":
docxFile = "123.docx"
execlFile = "roro.xlsx"
sheet = "roro" tableName = "内科"
#读取word中tableName的内容
tableInfo = parse_docx(docxFile,tableName) #处理execl
writeExecl(execlFile,sheet,tableInfo)

运行后生成文件 roro.xlsx,内容如下:

使用python读取word,写入execl

上一篇:UVaLive 7360 Run Step (排列组合,枚举)


下一篇:ThinkPad E40无线网卡驱动安装 FOR CENTOS6.3