Python xlwt:在编写bug时使用easyxf设置单元格的样式

2024-05-16 16:32:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要在我通过我的程序创建的xls文件中设置某些单元格和行的样式,但我有一些问题,可能是对xlwt easyxf的工作原理的误解。

首先,如果我写的单元格没有值,只有样式,那么里面的值会被删除吗?

第二,我试图使用单元格的样式和值写入单元格,但我始终收到一个错误:

"TypeError: 'XFStyle' object is not callable". -Solved

现在的问题是样式没有得到实现。在写入单元格并将其输出到xls文件后,根本没有颜色、bg、大小和字体更改。

我试着用google搜索这个,并跟随其他人的例子,但是无论出于什么原因,我的代码都不起作用。这里是:

def stylize_spreadsheet_accordingly(iFile, workbook, row_grey, row_underline, row_font_size, cells_yellow):
    #this time iFile is the file you're overwriting

    #styling stuff

    print "styling the document..."

    new_sheet.col(0).width = 256 * 18
    new_sheet.col(1).width = 256 * 69.43
    new_sheet.col(2).width = 256 * 9
    new_sheet.col(3).width = 256 * 20.71
    new_sheet.col(4).width = 256 * 8.43

    font_size_style = xlwt.easyxf('font: name Calibri, bold on, height 280;')
    font_underline_style = xlwt.easyxf('font: underline on;')
    fill_grey_style = xlwt.easyxf('pattern: back_color gray25;')
    fill_yellow_style = xlwt.easyxf('pattern: back_color yellow;')

    iBook = open_workbook(iFile)
    iSheet = iBook.sheet_by_index(0)

    for row_index in range(iSheet.nrows):
        if row_index in row_grey:
            for col_index in range(iSheet.ncols):
                new_sheet.write(row_index,col_index, iSheet.cell(row_index,col_index).value, fill_grey_style)
        if row_index in row_underline:
            for col_index in range(iSheet.ncols):
                new_sheet.write(row_index,col_index, iSheet.cell(row_index,col_index).value, font_underline_style)
        if row_index in row_font_size:
            for col_index in range(iSheet.ncols):
                new_sheet.write(row_index,col_index, iSheet.cell(row_index,col_index).value, font_size_style)
    for each in cells_yellow:
        new_sheet.write(each[0], each[1], iSheet.cell(each[0],each[1]).value, fill_yellow_style)

    return workbook

new_sheet是我在另一个函数中创建的全局变量,该函数表示我添加到xlwt工作簿中的工作表。我传入的工作簿是应该包含new_sheet的文件。我可能把事情搞得太复杂了,或者做得太不道德了,但这是有效的。

另外,如果有不同的方法,我可以这样做,或者用不同的方法把某些细胞变成全彩,请告诉我。再次感谢。

谢谢,我把代码改成了你们说的,TypeError消失了,但完成后,我创建和使用的样式选项都没有通过。xls文件仍采用默认格式。怎么会这样?


Tags: innewindexstyle样式colwidthsheet
2条回答

您正在创建样式,然后尝试调用它们。

例如:

font_size_style = xlwt.easyxf('font: name Calibri, bold on, height 280;')
...
new_sheet.write(row_index,col_index, iSheet.cell(row_index,col_index).value, fill_grey_style())

注意这一点:

fill_grey_style()

你得到的是'XFStyle' object is not callable,因为你像函数一样调用它,而不是仅仅把它传递给sheet.write,例如

而不是

new_sheet.write(row_index,col_index, iSheet.cell(row_index,col_index).value, fill_grey_style())

使用

new_sheet.write(row_index,col_index, iSheet.cell(row_index,col_index).value, fill_grey_style)

相关问题 更多 >