使用 pandas 将 Excel sheet table (Listobject) 读入 python

Read Excel sheet table (Listobject) into python with pandas

有多种方法可以将 excel 数据读入 python。 Pandas 还提供 API 用于读写

import pandas as pd
from pandas import ExcelWriter
from pandas import ExcelFile

df = pd.read_excel('File.xlsx', sheetname='Sheet1')

效果不错。

但是:将每个 sheet 的 table 直接访问到 pandas 数据帧的方法是什么?

上图显示了一个 sheet 包括一个 table SEPARATED THAN CELL (1,1)。

此外,sheet 可能包含多个 table(VBA 中的列表对象)。

我找不到任何方法将它们读入 pandas。

注意 1:无法修改工作簿以将所有 table 移至单元格 (1,1)。 注 2:我只想使用 pandas(如果可能的话)并尽量减少导入其他库的需要。但是实在没有别的办法我准备用其他lybray。无论如何,我无法使用 xlwings 来管理。

here 看起来可以解析 excel 文件,但是没有为 table 提供解决方案,只为完整的 sheet 提供解决方案。

documentation of pandas 似乎不提供这种可能性。

谢谢。

这是一种解析一个table的方法,但是需要您了解有关解析的部分的一些信息。

df = pd.read_excel("file.xlsx", usecols="B:I", index_col=3)
print(df)

不优雅,仅当 sheet 中存在一个 table 时才有效,但第一步:

import pandas as pd
import string

letter = list(string.ascii_uppercase)

df1 = pd.read_excel("file.xlsx")

def get_start_column(df):
    for i, column in enumerate(df.columns):
        if df[column].first_valid_index():
            return letter[i]

def get_last_column(df):
    columns = df.columns
    len_column = len(columns)
    for i, column in enumerate(columns):
        if df[column].first_valid_index():
            return letter[len_column - i]

def get_first_row(df):
    for index, row in df.iterrows():
        if not row.isnull().values.all():
            return index + 1

def usecols(df):
    start = get_start_column(df)
    end = get_last_column(df)
    return f"{start}:{end}"

df = pd.read_excel("file.xlsx",  usecols=usecols(df1), header=get_first_row(df1)) 
print(df)

我知道这个问题已经被标记为已解决,但我发现一篇文章提供了更强大的解决方案: Full Post

我想这个库的更新版本支持更好的工作簿结构可见性。这是一个摘要:

  1. 使用来自 openpyxl
  2. load_workbook 函数加载工作簿
  3. 然后,您可以访问其中的工作表,其中包含 excel 中的列表对象(表格)集合。
  4. 获得表的访问权限后,您就可以获取这些表的范围地址。
  5. 最后他们遍历范围并从中创建一个 pandas 数据框。

这是一个更好的解决方案,因为它使我们能够遍历工作簿中的所有工作表和表格。

您可以使用 xlwings,这是处理 python 中的 excel 个文件的好包。

这是针对单个 table,但使用 xlwings 集合(App>books>sheets>tables)遍历所有 tables 非常简单。表格当然是列表对象。

import xlwings
import pandas

with xlwings.App() as App:
    _ = App.books.open('my.xlsx')
    rng = App.books['my.xlsx'].sheets['mysheet'].tables['mytablename'].range
    df: pandas.DataFrame = rng.expand().options(pandas.DataFrame).value