首页 > 解决方案 > 如何从 Excel 到 DataFrame 读取工作表上的多个表,其中表的位置不确定?

问题描述

将下面屏幕截图中突出显示的表格从 Excel 读取到 Pandas DataFrame 中的最简单方法是什么?假设我有成千上万个这样的工作表。我要阅读的区域在左上角有“Col4”,并且没有整个空白行或列。“Col4”可以出现在工作表的任何(行、列)上。

我想我总是可以采用粗暴的方法,首先阅读整张纸,找到“Col4”的位置,然后提取我想要的部分。但我想知道是否有更简单的方法可以做到这一点。

此外,到目前为止,我只与 Pandas 合作过。我知道除了 Pandas 之外还有许多其他软件包,例如 xlwings 或 xlrd。如果您知道这些软件包中的任何一个可能会有所帮助,请告诉我,我们也将不胜感激。

在此处输入图像描述

请注意,此问题不是pandas read_excel multiple tables on the same sheet的重复,因为该帖子中的解决方案仅处理预先知道行偏移量的情况。

我正在解决的这背后的业务问题是阅读许多由我公司的非工程师人员(人力资源、会计等)创建的电子表格,不幸的是,他们没有以一致且编程友好的方式创建电子表格。

标签: pythonexcelpandas

解决方案


Python 非常强大,但我不认为你会得到你正在寻找的那种灵活性,将它与 Excel 一起使用。也许有人会发布解决方案,但如果没有,您可以使用 VBA 来完成此任务,当所有内容都聚合到一张表中时,使用 Python 从该单一来源读取。

Sub CopyRangeFromMultipleSheets()

'Declaring variables
Dim Source As Worksheet
Dim Destination As Worksheet
Dim SourceLastRow, DestLastRow As Long

Application.ScreenUpdating = False

'Looping through all sheets to check whether "Master" sheet exist
For Each Source In ThisWorkbook.Worksheets
    If Source.Name = "Master" Then
        MsgBox "Master sheet already exist"
        Exit Sub
    End If
Next

'Inserting a new sheet after the "Main" sheet
Set Destination = Worksheets.Add(after:=Sheets("Sheet1"))

Destination.Name = "Master"

'Looping through all the sheets in the workbook
For Each Source In ThisWorkbook.Worksheets

    'Preventing consolidation of data from "Main" and "Master" sheet
    If Source.Name <> "Master" Then

        SourceLastRow = Source.Range("A1").SpecialCells(xlLastCell).Row

        Source.Activate

        If Source.UsedRange.Count > 1 Then

            DestLastRow = Sheets("Master").Range("A1").SpecialCells(xlLastCell).Row

            If DestLastRow = 1 Then
                'copying data from the source sheet to destination sheet
                Source.Range("D1", Range("T1").SpecialCells(xlLastCell)).Copy Destination.Range("A" & DestLastRow)
            Else
                Source.Range("D1", Range("T1").SpecialCells(xlCellTypeLastCell)).Copy Destination.Range("A" & (DestLastRow + 1))
            End If

        End If
    End If
Next

Destination.Activate

Application.ScreenUpdating = True

End Sub

推荐阅读