【问题标题】:how to extract different tables in excel sheet using python如何使用python在excel表格中提取不同的表格
【发布时间】:2021-11-14 05:29:44
【问题描述】:

在一个 excel 文件中,工作表 1,工作表的不同位置有 4 个表。如何读取这 4 个表。例如,我什至从谷歌添加了一张图片快照以供参考。在不使用索引的情况下,还有其他方法可以提取表吗?

【问题讨论】:

  • 1.你为什么不想使用索引? 2.能否描述一下表格位置、大小等的约束条件。 3.可以举个例子吗?
  • 我不想使用 excel 索引,因为有更多的工作表具有不同的 excel 工作表结构和格式。显然我们可以使用数据框索引,对不起,如果我的问题让您对 excel 表索引和数据框索引感到困惑。
  • 这些是真的吗Excel Table
  • 除了虚拟看到之外,您还需要什么信息来确认有n个表?是否确认您在两个表格之间至少有一行空白?

标签: python-3.x excel pandas dataframe


【解决方案1】:

您可以将您的 excel 表格转换为 csv 文件,然后使用 csv 模块来抓取行。

//excel转csv的代码

import pandas as pd read_file = pd.read_excel ("Test.xlsx") read_file.to_csv ("Test.csv",index = None,header=True) df = pd.DataFrame(pd.read_csv("Test.csv")) print(df)

为了更好的方法,请向我们提供示例 excel 文件

【讨论】:

    【解决方案2】:

    您可以将您的 excel 表格转换为 csv 文件,然后使用 csv 模块来抓取行。

        import pandas as pd
        read_file  = pd.read_excel("Test.xlsx")
        read_file.to_csv ("Test.csv",index = None,header=True) 
        enter code here
        df = pd.DataFrame(pd.read_csv("Test.csv")) 
        print(df)
    

    为了更好的方法,请向我们提供示例 excel 文件

    【讨论】:

      【解决方案3】:

      我假设您的表格格式为“Excel Tables”。 您可以通过标记范围然后单击来创建Excel表格:

      Samuel Oranyeli 提供了一个很好的指南,如何使用 Python 导入 Excel 表格。我用过his code 并举例说明。


      我在excel中使用了以下数据,其中每种颜色代表一个表格。


      关于代码的备注:

      以下部分可用于检查我们正在使用的工作表中存在哪些表:

      # check what tables that exist in the worksheet
      print({key : value for key, value in ws.tables.items()})
      

      在我们的示例中,此代码将给出:

      {'Table2': 'A1:C18', 'Table3': 'D1:F18', 'Table4': 'G1:I18', 'Table5': 'J1:K18'}

      您可以在此处设置数据框名称。如果数据帧的数量与表的数量不匹配,请小心,您将收到错误。

      # Extract all the tables to individually dataframes from the dictionary
      Table2, Table3, Table4, Table5 = mapping.values()
      
      # Print each dataframe
      print(Table2.head(3)) # Print first 3 rows from df
      

      print(Table2.head(3)) 给出:

         Index   first_name   last_name     address
         0          Aleshia   Tomkiewicz    14 Taylor St
         1             Evan   Zigomalas     5 Binney St
         2           France   Andrade       8 Moor Place
      

      完整代码:

      #import libraries
      from openpyxl import load_workbook
      import pandas as pd
      
      # read file
      wb = load_workbook("G:/Till/Tables.xlsx") # Set the filepath + filename
      
      # select the sheet where tables are located
      ws = wb["Tables"]
      
      # check what tables that exist in the worksheet
      print({key : value for key, value in ws.tables.items()})
      
      mapping = {}
      
      # loop through all the tables and add to a dictionary
      for entry, data_boundary in ws.tables.items():
          # parse the data within the ref boundary
          data = ws[data_boundary]
          
          ### extract the data ###
          # the inner list comprehension gets the values for each cell in the table
          content = [[cell.value for cell in ent] 
                     for ent in data]
          
          header = content[0]
          
          #the contents ... excluding the header
          rest = content[1:]
          
          #create dataframe with the column names
          #and pair table name with dataframe
          df = pd.DataFrame(rest, columns = header)
          mapping[entry] = df
      
      #  print(mapping)
      
      # Extract all the tables to individually dataframes from the dictionary
      Table2, Table3, Table4, Table5 = mapping.values()
      
      # Print each dataframe
      print(Table2)
      print(Table3)
      print(Table4)
      print(Table5)
      

      示例数据,example file:

      first_name last_name address city county postal
      Aleshia Tomkiewicz 14 Taylor St St. Stephens Ward Kent CT2 7PP
      Evan Zigomalas 5 Binney St Abbey Ward Buckinghamshire HP11 2AX
      France Andrade 8 Moor Place East Southbourne and Tuckton W Bournemouth BH6 3BE
      Ulysses Mcwalters 505 Exeter Rd Hawerby cum Beesby Lincolnshire DN36 5RP
      Tyisha Veness 5396 Forth Street Greets Green and Lyng Ward West Midlands B70 9DT
      Eric Rampy 9472 Lind St Desborough Northamptonshire NN14 2GH
      Marg Grasmick 7457 Cowl St #70 Bargate Ward Southampton SO14 3TY
      Laquita Hisaw 20 Gloucester Pl #96 Chirton Ward Tyne & Wear NE29 7AD
      Lura Manzella 929 Augustine St Staple Hill Ward South Gloucestershire BS16 4LL
      Yuette Klapec 45 Bradfield St #166 Parwich Derbyshire DE6 1QN
      Fernanda Writer 620 Northampton St Wilmington Kent DA2 7PP
      Charlesetta Erm 5 Hygeia St Loundsley Green Ward Derbyshire S40 4LY
      Corrinne Jaret 2150 Morley St Dee Ward Dumfries and Galloway DG8 7DE
      Niesha Bruch 24 Bolton St Broxburn, Uphall and Winchburg West Lothian EH52 5TL
      Rueben Gastellum 4 Forrest St Weston-Super-Mare North Somerset BS23 3HG
      Michell Throssell 89 Noon St Carbrooke Norfolk IP25 6JQ
      Edgar Kanne 99 Guthrie St New Milton Hampshire BH25 5DF

      【讨论】:

        【解决方案4】:

        【讨论】:

          猜你喜欢
          • 2020-01-25
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多