python xlsxwriter change all cell widths when using write_row
Asked Answered
E

2

8

How would i define a column width for the entire 'worksheet' or for each column when using write_row()?

For example i have:

workbook = xlsxwriter.Workbook(loc_path + 'monbatch_test1.xlsx')
worksheet = workbook.add_worksheet()

monbatch = [
    [a,b,c,],
    [a,b,c,],
    [a,b,c,]
    ]

row, col = 3, 0

for mon in monbatch:
    worksheet.write_row(row, col, mon, rows_format)
    row += 1
workbook.close()

I would like to change the column width for all columns (a,b,c)..

Exuberant answered 7/1, 2015 at 4:2 Comment(0)
F
15

There is a relevant set_column() method that accept width:

set_column(first_col, last_col, width, cell_format, options)

Set properties for one or more columns of cells.

Here is how you can apply it:

worksheet.set_column(0, 2, 100)
Felisha answered 7/1, 2015 at 4:11 Comment(1)
I'd like to add, this value is in 1 unit per font character width. Default font is Calibri 11px of which equates to 8.75~px per unit. xlsxwriter.readthedocs.org/worksheet.html#worksheet-set-columnEtienne
I
5

The solution would be

def compute_rows(text, width):
    if len(text) < width:
        return 1
    phrases = text.replace('\r', '').split('\n')

    rows = 0
    for phrase in phrases:
        if len(phrase) < width:
            rows = rows + 1
        else:
            words = phrase.split(' ')
            temp = ''
            for idx, word in enumerate(words):
                temp = temp + word + ' '
                # check if column width exceeded
                if len(temp) > width:
                    rows = rows + 1
                    temp = '' + word + ' '
                # check if it is not the last word
                if idx == len(words) - 1 and len(temp) > 0:
                    rows = rows + 1
    return rows

But you can see it in details here: http://assist-software.net/blog/how-export-excel-files-python-django-application

Inessive answered 9/7, 2015 at 10:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.