如何使用Openpyxl获取当前行索引

问题描述 投票:3回答:3

我编写了一个Python脚本来从.json文件中提取一些字符串值,将它们存储在一些字典中并使用Openpyxl将它们填充到.xlsx文件中,我是第一次使用它:

简而言之,看起来像这样:

WORKBOOK = Workbook()
WORKSHEET = WORKBOOK.active
. . .
. . .
for PERSON in TEAM_LIST:
    for ITEM in ITEMS[PERSON]:
       if PERSON in REGULAR_LIST:
          PERSON_ITEMS_ROW = (PERSON,ITEM[0],ITEM[1],ITEM[2],ITEM[3],ITEM[4)]
          SHEET.append(PERSON_ITEMS_ROW)    # Fill each row with some PERSON ITEMS
      else:
        PERSON_ITEMS_ROW = (PERSON,ITEM[0],ITEM[1],ITEM[2],ITEM[5],ITEM[6])
        SHEET.append(PERSON_ITEMS_ROW)      # Fill each row with other PERSON ITEMS

这段代码效果很好(虽然我不是100%肯定它是正确的)

我想更改上面“其他”部分中选择的行的背景和前景色,而我无法找到方法来执行此操作;

我知道如何将特定颜色和字体应用于特定行:我为第一行用作标题行,但我不知道如何获取当前行索引,因此我可以在每个行上应用特定颜色和字体一排“其他”部分

欢迎任何想法

谢谢

python openpyxl
3个回答
0
投票

您正在寻找ws._current_row。 注意:ws._current_row仅在插入新单元格后有效。

你可以这样做:

    ...
    SHEET.append(PERSON_ITEMS_ROW)
    # For all cells in ws._current_row
    for row_cells in ws.iter_rows(min_row=ws._current_row,  max_row=ws._current_row):
        for cell in row_cells:
            cell.font = Font(color=colors.GREEN, italic=True)

    # Only for cell in column A == 1
    ws.cell(row=ws._current_row, column=1).font = Font(color=colors.RED)  

如果您不想使用不受支持的ws._current_row

    # Assume you start in row==2
    for ws_current_row, PERSON in enumerate(TEAM_LIST, 2):
        #...
        #SHEET.append(PERSON_ITEMS_ROW)

        # For all cells in ws_current_row
        for row_cells in ws.iter_rows(min_row=ws_current_row, max_row=ws_current_row):
            for cell in row_cells:
                cell.font = Font(color=colors.GREEN, italic=True)

        # Only for cell in column A == 1
        ws.cell(row=ws_current_row, column=1).font = Font(color=colors.RED)

OOP解决方案,或openpyxl可以实现它。 例如:

    from openpyxl.workbook.workbook import Workbook as _Workbook
    from openpyxl.worksheet.worksheet import Worksheet as _Worksheet

    class Worksheet(_Worksheet):
        # Overload openpyxl.Worksheet.append
        def append(self, iterable):
            super().append(iterable)
            return self._current_row, \
                   self._cells_by_col(min_col=1, min_row=self._current_row,
                                      max_col=self.max_column, max_row=self._current_row)

    class Workbook(_Workbook):
        # Workaround, as openpyxl is not using self.create_sheet(...) in __init__
        def __init__(self, write_only=True):
            super().__init__(write_only)
            self.__write_only = False
            self.create_sheet()

        # Not working for self.read_only and self.write_only :
        # Overload openpyxl.Workbook.create_sheet
        def create_sheet(self, title=None, index=None):
            new_ws = Worksheet(parent=self, title=title)
            self._add_sheet(sheet=new_ws, index=index)
            return new_ws

    for PERSON in TEAM_LIST:
        # ...
        ws_current_row, iter_col = SHEET.append(PERSON_ITEMS_ROW)

        # Iterate all cells from generator iter_col
        for cell in [col_cells[0] for col_cells in iter_col]:
            cell.font = Font(color=colors.RED, italic=True)

        # Only for cell in column A == 1
        ws.cell(row=ws_current_row, column=1).font = Font(color=colors.BLUE)

用Python测试:3.4.2 - openpyxl:2.4.1 - LibreOffice:4.3.3.2 OpenPyXL Documentation


0
投票

这是一个相当古老的主题,但我想分享简单的解决方案,以获取行号,同时使用ws.iter_rows()方法迭代行。我从行元组中获取第一个对象,这是一个单元格,因此它也有关于它的行和列的信息。

for row in ws.iter_rows(min_row=1, max_row=ws.max_rows):
    print('Row number:', str(row[0].row))

-1
投票

除了自己的内部使用,openpyxl没有“当前”行的概念。在你的情况下,我怀疑ws.max_row是你想要的。

© www.soinside.com 2019 - 2024. All rights reserved.