0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Python:Excel(xlsx)のA列の値をdictの並び順に合わせて行全体を並び替える

0
Posted at
from openpyxl import load_workbook
from copy import copy

input_file = "input.xlsx"
output_file = "output.xlsx"

# dictの登録順で並べ替える
order = {
    "A": 1,
    "B": 2,
    "C": 3,
    "D": 4,
    "E": 5,
    "F": 6
}

# ブック読み込み
wb = load_workbook(input_file)
ws = wb.active

start_row = 3
end_row = 8
max_col = ws.max_column

# =====================================================
# 3~8行目を「値+書式」で退避
# =====================================================
rows = []

for r in range(start_row, end_row + 1):

    row_cells = []

    for c in range(1, max_col + 1):

        cell = ws.cell(r, c)

        row_cells.append({
            "value": cell.value,
            "font": copy(cell.font),
            "fill": copy(cell.fill),
            "border": copy(cell.border),
            "alignment": copy(cell.alignment),
            "number_format": cell.number_format,
            "protection": copy(cell.protection),
            "comment": copy(cell.comment) if cell.comment else None,
            "hyperlink": copy(cell.hyperlink) if cell.hyperlink else None
        })

    # A列をキーにする
    key = ws.cell(r, 1).value

    # dictにないものは最後
    sort_key = order.get(key, float("inf"))

    rows.append({
        "sort_key": sort_key,
        "cells": row_cells,
        "height": ws.row_dimensions[r].height,
        "hidden": ws.row_dimensions[r].hidden
    })

# =====================================================
# dict順に並べ替え
# =====================================================
rows.sort(key=lambda x: x["sort_key"])

# =====================================================
# シートへ書き戻し
# =====================================================
for r, row_data in enumerate(rows, start=start_row):

    # 行の高さ
    ws.row_dimensions[r].height = row_data["height"]
    ws.row_dimensions[r].hidden = row_data["hidden"]

    for c, data in enumerate(row_data["cells"], start=1):

        cell = ws.cell(r, c)

        cell.value = data["value"]
        cell.font = copy(data["font"])
        cell.fill = copy(data["fill"])
        cell.border = copy(data["border"])
        cell.alignment = copy(data["alignment"])
        cell.number_format = data["number_format"]
        cell.protection = copy(data["protection"])
        cell.comment = copy(data["comment"]) if data["comment"] else None

        if data["hyperlink"]:
            cell._hyperlink = copy(data["hyperlink"])
        else:
            cell._hyperlink = None

# 保存
wb.save(output_file)

print("並び替え完了")
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?