5
5

More than 3 years have passed since last update.

# 【Python, Excel】 セル結合を駆逐する

Last updated at Posted at 2020-12-24

# 嘆き

なぜ、この世には「セル結合」なるものが存在するのでしょうか...

（ソース）

（統計表における機械判読可能なデータ作成に関する表記方法：https://www.soumu.go.jp/main_content/000723626.pdf）

「前処理やるぞー」と思った矢先にセル結合の嵐だともうやる気が90%減です。

そこでpythonでセル結合を駆逐する関数を実装しました。

unmerge.py
``````import openpyxl
import sys

class excel_operate:
def __init__(self, excel_dir):
self.excel_dir = excel_dir
self.sheet_number = len(self.workbook.get_sheet_names())
self.sheet_contains =  [self.workbook.worksheets[i] for i in range(self.sheet_number)]
self.merged_cells_list = [self.sheet_contains[i].merged_cells.ranges for i in range(self.sheet_number)]

def get_merged_cells_location(self):
self.merged_cells_location_list = [""]*self.sheet_number
for i in range(self.sheet_number):
self.merged_cells_location_list[i] = [format(self.merged_cells_list[i][j]) for j in range(len(self.merged_cells_list[i]))]
else:
print("The merged cells location was got!")

def break_merged_cells(self):
for i in range(self.sheet_number):
for j in range(len(self.merged_cells_list[i])):
self.sheet_contains[i].unmerge_cells(self.merged_cells_location_list[i][j])
else:
pass
else:
print('The all merged cells were unmerged!')

Excel = excel_operate(r"セル結合を駆逐したいExcelのpath")
Excel.get_merged_cells_location()
Excel.break_merged_cells()
Excel.workbook.save("名前.xlsx")

``````

5
5
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
5
5