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

jes*_*516 2 python excel xlsxwriter

在使用时,如何为整个"工作表"或每列定义列宽write_row()

例如我有:

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()
Run Code Online (Sandbox Code Playgroud)

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

ale*_*cxe 6

有一种相关的set_column()方法可以接受width:

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

设置一列或多列单元格的属性.

以下是如何应用它:

worksheet.set_column(0, 2, 100)
Run Code Online (Sandbox Code Playgroud)


小智 5

解决方案是

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
Run Code Online (Sandbox Code Playgroud)

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