Jan-16-2019, 04:36 AM
A little further each day... but always needing a bit of hand holding.
I decided that it would be a good thing to be able to have the columns be the width of the data. So, I to google around and see how. I found some code and worked it in, but it doesn't seem to work to set the column width, but I can't figure out why. I print out the various bits of data as the program runs, and it all seems to be accurate. But is never gets applied... but also doesn't give any error!
Same with me trying to set the font as a fixed width font, so that I can know the width is sufficient. I've put in the code, but nothing happens and no errors.
Pointing out errors would be a blessing for anyone willing to look!
Thank you in advance... little by little, I'm learning something every day!
I decided that it would be a good thing to be able to have the columns be the width of the data. So, I to google around and see how. I found some code and worked it in, but it doesn't seem to work to set the column width, but I can't figure out why. I print out the various bits of data as the program runs, and it all seems to be accurate. But is never gets applied... but also doesn't give any error!
Same with me trying to set the font as a fixed width font, so that I can know the width is sufficient. I've put in the code, but nothing happens and no errors.
Pointing out errors would be a blessing for anyone willing to look!
Thank you in advance... little by little, I'm learning something every day!
import os, glob, shutil, openpyxl from pathlib import Path from collections import defaultdict from openpyxl.reader.excel import load_workbook from openpyxl import Workbook from openpyxl.compat import range from openpyxl.utils import get_column_letter from openpyxl.styles import Font from datetime import datetime startTime = datetime.now() os.chdir("c://test") mainfile = 'Example.xlsx' wb = load_workbook(mainfile) ws = wb.active header, *data = ws.values groups = defaultdict(lambda: defaultdict(list)) for row in data: subgroup, group = row[-1][:-1], row[-1][-1] groups[group][subgroup].append(row) for group, subgroups in sorted(groups.items()): wb = Workbook() wsf =Font(name = 'Courier New', sz = 12) wb.remove(wb.active) dest_filename = (f'{mainfile[:-5]} Group {group}.xlsx') for subgroup, rows in sorted(subgroups.items()): ws = wb.create_sheet(title = subgroup) ws.append(header) for row in rows: ws.append(row) wb.save(filename = dest_filename) #print(datetime.now() - startTime) dims = {} for row in ws.rows: for cell in row: if cell.value: cell.font = wsf dims[cell.column] = max((dims.get(cell.column, 0), len(str(cell.value)))) for col, value in dims.items(): ws.column_dimensions[col].width = int(value) print(int(value)) print (cell, col, value) print(group,subgroup, dims) wb.save(filename = dest_filename) print(datetime.now() - startTime)