gpt4 book ai didi

python - 如何使用 Openpyxl 读取现有的工作表表格?

转载 作者:行者123 更新时间:2023-12-05 01:15:05 27 4
gpt4 key购买 nike

Excel 工作表中的一系列单元格可以格式化为表格。 Openpyxl 在 documentation 中提供,如何编写这样一个表的示例。

如何使用 Openpyxl 读取现有的 Excel 工作表?

一个简单的 openpyxl 语句,当提供表名时,会将表读入 openpyxl Table 对象。

最佳答案

以下函数从表名定义的范围中读取单元格值,并返回一个包含列标题列表和数据字典的元组。这对于创建 Pandas DataFrame 很有用:

from openpyxl import load_workbook
import pandas as pd


def read_excel_table(sheet, table_name):
"""
This function will read an Excel table
and return a tuple of columns and data

This function assumes that tables have column headers
:param sheet: the sheet
:param table_name: the name of the table
:return: columns (list) and data (dict)
"""
table = sheet.tables[table_name]
table_range = table.ref

table_head = sheet[table_range][0]
table_data = sheet[table_range][1:]

columns = [column.value for column in table_head]
data = {column: [] for column in columns}

for row in table_data:
row_val = [cell.value for cell in row]
for key, val in zip(columns, row_val):
data[key].append(val)

return columns, data

book = load_workbook('table.xlsx')
ws = book.active

columns, data = read_excel_table(ws, 'Table1')
df = pd.DataFrame(data=data, columns=columns)

关于python - 如何使用 Openpyxl 读取现有的工作表表格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56923379/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com