python xlsxwriter 在使用 write_row 时更改所有单元格宽度

python xlsxwriter change all cell widths when using write_row

使用 write_row() 时如何为整个 'worksheet' 或每列定义列宽?

例如我有:

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()

我想更改所有列 (a,b,c) 的列宽..

有一个相关的 set_column() 方法接受 width:

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

Set properties for one or more columns of cells.

以下是应用方法:

worksheet.set_column(0, 2, 100)

解决方案是

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

但您可以在这里查看详细信息:http://assist-software.net/blog/how-export-excel-files-python-django-application