MS Office文档可能是最不结构化的数据源之一。但在现实生活中,MS Office文档,特别是Excel和Word,几乎在每个公司,单位中都在使用。仅仅因为它是一个灵活而简单的工具,任何人都可以使用。所以也是为什么需要学习用Pythonl来处理的重要原因。#python

5分钟学会Python处理.docx和.xlsx文件(5分钟学会Python处理.docx和.xlsx文件)(1)

word文件的真相-------您可以轻松编辑没有任何库的.docx文件。从技术上讲,它只是一个zip存档。因此,您可以解压缩它,在document.xml文件中进行替换并再次压缩它。它比处理旧的二进制.doc文件要好得多。但是还有更优雅的方式。

5分钟学会Python处理.docx和.xlsx文件(5分钟学会Python处理.docx和.xlsx文件)(2)

本5 分钟教程任务是从.xlsx文档中读取数据并根据现有模板生成.docx文件。要使用.xlsx文件,将使用openpyxl python库。

openpyxl库用于处理.xlsx文件

首先安装库并打开了input / table.xlsx文件:

#sudo pip install openpyxl

#sudo pip2 install openpyxl import openpyxl wb = openpyxl.load_workbook(filename = 'input/table.xlsx') 现在可以选择工作表并获取某些单元格的值: ws = wb.worksheets[1] print(ws["A1"].value)

输出:

Username

表头怎么处理?如果我们在表中有9列,我们可以这样做:

for col in range(1, 10):

print(ws.cell(column=col, row=1).value)

输出:

Username

Surname

Attribute1

Attribute2

Attribute3

Attribute4

Attribute5

Attribute6

Attribute7

如果想要阅读整个表(没有头),我们可以这样做:

first_cell_value = "1" row = 2 table = dict() while first_cell_value != None: if not ws.row_dimensions[row].hidden: table[row] = dict() for col in range(1, 10): table[row][col] = ws.cell(column=col, row=row).value row = 1 first_cell_value = ws.cell(column=1, row=row).value

请注意,略过隐藏的行。

从这样的表格结构中,可以获得分析所需的一切。

用于处理.docx文件的python-docx库

5分钟学会Python处理.docx和.xlsx文件(5分钟学会Python处理.docx和.xlsx文件)(3)

然后让我们弄清楚如何使用.docx文件。安装了python-docx库并打开了.docx模板文件:

#sudo pip install python-docx #sudo pip2 install python-docx import docx document = docx.Document(docx = 'input/template.docx')

以下是如何遍历doc文件中的段落,找到关键字" USERNAME "并将其替换为所需的值"John":

import re

for paragraph in document.paragraphs:

if "USERNAME" in paragraph.text:

paragraph.text = re.sub("USERNAME", "John", paragraph.text)

如果需要读取或编辑.docx文件中的表怎么办?你可以这样读表:

for table in document.tables: for row in table.rows: for cell in row.cells: for paragraph in cell.paragraphs: print(paragraph.text)

要将行插入表中,我们的行为如下:

rows_to_add = dict() rows_to_add[1] = ['1','2','3','4'] for table in document.tables: for row in rows_to_add: cells = table.add_row().cells for n in range(0,len(rows_to_add[row]), 1): cells[n].text = rows_to_add[row][n]

最后,将修改后的模板保存到新文件中:

document.save('output/john_smith.docx')

本文标签:

docx,Microsoft,MS Excel,MS Office,MS Word,openpyxl,python,python-docx,xlsx 。

老规矩,有问题问公众号“python_dada"。

,