Pythonword实现读取及导出代码解析
2个简单的代码,帮你实现word的导出和word的读取
功能一:导出word,word中的内容为
run3.element.rPr.rFonts.set(qn('w:eastAsia'), u'仿宋_GB2312')
这两句均是设置字体为仿宋_GB2312,之所以要两种格式写两遍,是因为word对中文支持不太友好,需要再填一句
功能二:读取word,word中的内容为
读取表格外文字的代码:
from docx import Document document=Document("长恨歌.docx") print("读取非表格中的内容:") all_paragraphs=document.paragraphs for paragraph in all_paragraphs: print(paragraph.text)
读取表格内文字的代码:
from docx import Document document=Document("长恨歌.docx") print("读取表格中的内容:") tables=document.tables for i in range(len(tables)): tb=tables[i]#获取表格的行 tb_rows=tb.rows #读取每一行内容 for i in range(len(tb_rows)): row_data=[] row_cells=tb_rows[i].cells#读取每一行单元格内容 for cell in row_cells:#单元格内容 row_data.append(cell.text) print(''.join(row_data))
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持来客网。