Openpyxl - 如何读取文件中所有工作表中的相同单元格?

问题描述 投票:0回答:1

我想循环遍历 Excel 文件中的所有工作表,从每个工作表中读取单元格 B2 的内容,然后将其打印出来。稍后,我计划根据该单元格的字符串值设置条件。

  • 感兴趣的单元格是B2:我想打印三个不同的学生姓名,分别是Roberto、Miquel Angelo 和Leonardo。
  • 我当前的代码仅打印“Leonardo”,(Sheet_3)。
# Importing modules
import openpyxl as op
import pandas as pd
import numpy as np
import xlsxwriter
import openpyxl
from openpyxl import Workbook, load_workbook

# Defining the file path
file_path = r'C:/Users/machukovich/Desktop/stackoverflow.xlsx'

# Load workbook as openpyxl
reference_workbook = openpyxl.load_workbook(file_path)

# We will mantain the workbook open
wb = reference_workbook.active

# Getting the sheetnames as a list using the sheetnames attribute

sheet_names = reference_workbook.sheetnames
print(sheet_names)

# Loading the file into a dictionary of Dataframes
dict_of_df = pd.read_excel(file_path, sheet_name=None, skiprows=2)

# Reading up the B2 cell for later use:
student_name = wb['B2'].value
for sheet_names in dict_of_df:
    print(student_name)
  • 您可以在下面找到 Excel 文件的快照以进一步说明。

pandas for-loop openpyxl ordereddictionary pandas.excelwriter
1个回答
0
投票

只需执行以下操作就可以了

from openpyxl import load_workbook

file_path = r'C:/Users/machukovich/Desktop/stackoverflow.xlsx'
reference_workbook = openpyxl.load_workbook(file_path)
for sheet in reference_workbook.worksheets:
    print(f"Name {sheet['B2'].value}")
© www.soinside.com 2019 - 2024. All rights reserved.