Skip to content

Instantly share code, notes, and snippets.

@xyb
Last active March 23, 2023 08:07
Show Gist options
  • Save xyb/6791de9245e69092c97a1ed3a84a1396 to your computer and use it in GitHub Desktop.
Save xyb/6791de9245e69092c97a1ed3a84a1396 to your computer and use it in GitHub Desktop.
unmerge excel cell and export as csv
#!/usr/bin/env python3
# Usage: $0 input.xlsx output.csv
from openpyxl.workbook import Workbook
from openpyxl import load_workbook
from openpyxl.utils.cell import range_boundaries
import sys
import csv
input = sys.argv[1]
output = sys.argv[2]
print(f'{input} ==> {output}')
wb = load_workbook(input)
for st_name in wb.sheetnames:
st = wb[st_name]
mcr_coord_list = [mcr.coord for mcr in st.merged_cells.ranges]
for mcr in mcr_coord_list:
min_col, min_row, max_col, max_row = range_boundaries(mcr)
top_left_cell_value = st.cell(row=min_row, column=min_col).value
st.unmerge_cells(mcr)
for row in st.iter_rows(min_col=min_col, min_row=min_row, max_col=max_col, max_row=max_row):
for cell in row:
cell.value = top_left_cell_value
sh = wb.active
with open(output, 'w') as f:
c = csv.writer(f)
for r in sh.rows:
c.writerow([cell.value for cell in r])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment