Last active
March 23, 2023 08:07
-
-
Save xyb/6791de9245e69092c97a1ed3a84a1396 to your computer and use it in GitHub Desktop.
unmerge excel cell and export as csv
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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