如何使用Openpyxl

时间:2017-03-18 23:27:34

标签: python openpyxl

我编写了一个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%确定它是正确的)

我想更改"否则"中选择的行的背景和前景色。上面的部分,我没有设法找到办法;

我知道如何将特定颜色和字体应用于特定行:我是用作标题行的第一行,但我不知道如何获取当前行索引以便我可以应用特定行" else"每行的颜色和字体。节

欢迎任何想法

感谢

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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))

答案 2 :(得分:-1)

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