python处理docx

#写入

from docx import Document
from docx.shared import Inches

document = Document()

document.add_heading('Document Title', 0)

p = document.add_paragraph('A plain paragraph having some ')
p.add_run('bold').bold = True
p.add_run(' and some ')
p.add_run('italic.').italic = True

document.add_heading('Heading, level 1', level=1)
document.add_paragraph('Intense quote', style='IntenseQuote')

document.add_paragraph(
    'first item in unordered list', style='ListBullet'
)
document.add_paragraph(
    'first item in ordered list', style='ListNumber'
)

document.add_picture('monty-truth.png', width=Inches(1.25))

table = document.add_table(rows=1, cols=3)
hdr_cells = table.rows[0].cells
hdr_cells[0].text = 'Qty'
hdr_cells[1].text = 'Id'
hdr_cells[2].text = 'Desc'
for item in recordset:
    row_cells = table.add_row().cells
    row_cells[0].text = str(item.qty)
    row_cells[1].text = str(item.id)
    row_cells[2].text = item.desc

document.add_page_break()

document.save('demo.docx')

#读取其中excel

pip install python-docx

import docx
from docx import Document #导入库

path = "E:\\python_data\\1234.docx" #文件路径
document = Document(path) #读入文件
tables = document.tables #获取文件中的表格集
table = tables[0  ]#获取文件中的第一个表格
for i in range(1,len(table.rows)):#从表格第二行开始循环读取表格数据
    result = table.cell(i,0).text + "" +table.cell(i,1).text+
    table.cell(i,2).text + table.cell(i,3).text
    #cell(i,0)表示第(i+1)行第1列数据,以此类推
    print(result)

###############################

转自:http://python-docx.readthedocs.io/en/latest/

https://blog.csdn.net/zhengyikuangge/article/details/80451424

你可能感兴趣的:(python)