From f1cb8f4e5ceedbad9d14481f502e98096fe376d1 Mon Sep 17 00:00:00 2001 From: Suraj Shetty Date: Fri, 16 Oct 2020 13:42:00 +0530 Subject: [PATCH] feat: Pass custom widths for excel columns --- frappe/desk/query_report.py | 11 ++++++++--- frappe/utils/xlsxutils.py | 11 ++++++++--- 2 files changed, 16 insertions(+), 6 deletions(-) diff --git a/frappe/desk/query_report.py b/frappe/desk/query_report.py index dd318c8de6..b9be0ad683 100644 --- a/frappe/desk/query_report.py +++ b/frappe/desk/query_report.py @@ -345,8 +345,8 @@ def export_query(): data["result"] = handle_duration_fieldtype_values( data.get("result"), data.get("columns") ) - xlsx_data = build_xlsx_data(columns, data, visible_idx, include_indentation) - xlsx_file = make_xlsx(xlsx_data, "Query Report") + xlsx_data, column_widths = build_xlsx_data(columns, data, visible_idx, include_indentation) + xlsx_file = make_xlsx(xlsx_data, "Query Report", column_widths=column_widths) frappe.response["filename"] = report_name + ".xlsx" frappe.response["filecontent"] = xlsx_file.getvalue() @@ -380,11 +380,16 @@ def handle_duration_fieldtype_values(result, columns): def build_xlsx_data(columns, data, visible_idx, include_indentation): result = [[]] + column_widths = [] for column in data.columns: if column.get("hidden"): continue result[0].append(column["label"]) + column_width = column.get('width', 0) + # to convert into scale accepted by openpyxl + column_width /= 10 + column_widths.append(column_width) # build table from result for row_idx, row in enumerate(data.result): @@ -406,7 +411,7 @@ def build_xlsx_data(columns, data, visible_idx, include_indentation): result.append(row_data) - return result + return result, column_widths def add_total_row(result, columns, meta=None): diff --git a/frappe/utils/xlsxutils.py b/frappe/utils/xlsxutils.py index 2814c5ff40..3c7b027470 100644 --- a/frappe/utils/xlsxutils.py +++ b/frappe/utils/xlsxutils.py @@ -9,19 +9,24 @@ import xlrd import re from openpyxl.styles import Font from openpyxl import load_workbook +from openpyxl.utils import get_column_letter from six import BytesIO, string_types ILLEGAL_CHARACTERS_RE = re.compile(r'[\000-\010]|[\013-\014]|[\016-\037]') # return xlsx file object -def make_xlsx(data, sheet_name, wb=None): - +def make_xlsx(data, sheet_name, wb=None, column_widths=None): + column_widths = column_widths or [] if wb is None: wb = openpyxl.Workbook(write_only=True) ws = wb.create_sheet(sheet_name, 0) + for i, column_width in enumerate(column_widths): + if column_width: + ws.column_dimensions[get_column_letter(i + 1)].width = column_width + row1 = ws.row_dimensions[1] - row1.font = Font(name='Calibri',bold=True) + row1.font = Font(name='Calibri', bold=True) for row in data: clean_row = []