簡體   English   中英

使用 Python xlsxwriter 將變量 write_rich_string 格式屬性添加到文本

[英]Adding variable write_rich_string format properties to a text with Python xlsxwriter

我想生成一個 Excel 文件,其中包含多個跨單元格的字符串,並用一組 colors 標記每個字符串的某些部分。

如果我只想標記單個文本的固定部分,這是一個示例:

import xlsxwriter

outfile  = xlsxwriter.Workbook('file.xlsx')
sheet    = outfile.add_worksheet()
bold_red = outfile.add_format({'bold': True,'font_color':'red', 'underline': True})

sheet.write_rich_string(0,0,"This text in black, ",bold_red,"this one in red & bold, ","and this -probably- in other color")

outfile.close()

結果是一個 Excel 文件,其單元格在“A1”中包含以下文本:

在此處輸入圖像描述

我嘗試將變量輸入傳遞給write_rich_string ,但xlsxwriter.format.Format bold_red不能與字符串連接。

這是沒有 colors 時的樣子:

這是沒有顏色的樣子

這是預期的 output:

可變着色,取決於外部變量

在@jmcnamara 的這個鏈接中,我找到了答案:

“如果列表中有格式和段,您可以像這樣添加它們,使用標准 Python 列表解包語法:”

segments = ['This is ', bold, 'bold', ' and this is ', blue, 'blue']
worksheet.write_rich_string('A9', *segments)

因此,對於我的 dataframe 中的每個“文本”,將從外部鍵獲得其着色模式。 然后形成一個嵌入文本和格式的列表。 最后將此列表作為參數傳遞給write_rich_string

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM