feat: Pass custom widths for excel columns

This commit is contained in:
Suraj Shetty 2020-10-16 13:42:00 +05:30
parent 5173b21bdb
commit f1cb8f4e5c
2 changed files with 16 additions and 6 deletions

View file

@ -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):

View file

@ -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 = []