python - 行的循环和 XLSXwriter 格式

标签 python loops xlsxwriter

我有一个包含许多工作表的工作簿,我想在创建后对其进行格式化,并且我想根据列更改标题行的颜色。例如,我希望前 9 列为一种颜色,然后第 10 列应为另一种颜色,然后其余所有列应为第三种颜色。

这就是我正在循环的内容...它有点有效,但第 0 行中的所有单元格最终颜色相同;最后分配的颜色总是覆盖前面的列。

visitFormat = mtbook.add_format({'bg_color':'#e9ccfc'})
cognotesFormat = mtbook.add_format({'bg_color':'#d2eff2'})
filedateFormat = mtbook.add_format({'bg_color':'#8cbcff'})

for worksheet in mtbook.worksheets():
    print(worksheet)
    # for every column
    for i in range(len(subreportCols)):
        # set header bgcolor based on current column (i)
        if [i] in range(0,11):
            useheader = visitFormat
        elif [i] == 10:
            useheader = cognotesFormat
        else:
            useheader = filedateFormat
        # Write the value from cell (first row, column=1) back into that cell with formatting applied
        worksheet.write(0, i, subreportCols[i], useheader)

我对此感到困惑,因为我认为它是单独编写每一列的。我需要以某种方式逐个单元地执行此操作吗?

谢谢!

最佳答案

通过故障排除解决了这个问题,离开以防它对其他人有帮助(毕竟有一个“回答您的问题”按钮)。

在这一行中:

if [i] in range(0,11):

...我以为我正在做的是使用 [i] 作为对列表中第 i 个值的引用,但实际上我引用了整个列表。我将 [i] 换成了 i,效果很好。

关于python - 行的循环和 XLSXwriter 格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46473189/

相关文章:

python - 如何在python中将两个数据帧一个带值另一个带 bool 值变成一个数据帧?

python - 使用 post 请求和 xsrf token 登录,但收到 419

PHP 包装每 4 个元素

asp.net - javascript循环仅适用于所有其他元素

python - Xlsxwriter - 将字符串写入给定参数的单元格

excel - Pandas:迭代 DataFrame 列表并将每个数据框导出到 Excel 工作表

python - XLSX Writer Python- 3 以数字为中点的色标

python - 在(和为)多个操作系统上创建 Python 发行版(eggs)的最佳实践是什么

python - Django:自定义对象json序列化

javascript - jQuery提交不停 - 无限循环