簡體   English   中英

Xlsx Writer:在單個單元格中以多種格式編寫字符串

[英]Xlsx Writer: Writing strings with multiple format in a single cell

我有一個帶有多個分號的字符串。

'firstline: abc \n secondline: bcd \n thirdline: efg'

我想使用Xlsx Writer在excel單元格中編寫此字符串,如下所示。

第一行 :abc
第二行 :bcd
第三行 :efg

這就是我所做的。

description_combined = 
    '''
    firstline: abc
    secondline: bcd
    thirdline: efg
    '''
    spanInserted = []
    spanInserted = description_combined.split("\n")
    result = ''

    for spans in spanInserted:
        strr1 =  '{}:'.format(spans.split(":")[0])
        strr2 = spans.split(":")[1]
        result += '''bold , "{}" , "{}" ,'''.format(str(strr1),str(strr2))

    result = result[:-1]
    # print result

    worksheet.write_rich_string('A1', result)  


這是我在excel單元中得到的結果:

粗體,“ firstline:”,“ abc”,bold,“ secondline:”,“ bcd”,bold,“ thirdline:”,“ efg”

write_string()方法將列表作為參數,但是您正在傳遞字符串。

您應該使用類似這樣的方式來傳遞字符串和格式列表:

result = [bold, 'firstline: ',  'abc',
          bold, 'secondline: ', 'bcd',
          bold, 'thirdline: ',  'efg']

worksheet.write_rich_string('A1', *result)

但是,如果您還希望對文本進行換行,則需要在列表末尾添加text_wrap單元格格式,並在希望換行的位置添加換行符。 像這樣:

import xlsxwriter

workbook = xlsxwriter.Workbook('rich_strings.xlsx')
worksheet = workbook.add_worksheet()

worksheet.set_column('A:A', 20)
worksheet.set_row(0, 60)

bold = workbook.add_format({'bold': True})
text_wrap = workbook.add_format({'text_wrap': True, 'valign': 'top'})

result = [bold, 'firstline: ',  'abc\n',
          bold, 'secondline: ', 'bcd\n',
          bold, 'thirdline: ',  'efg']

result.append(text_wrap)

worksheet.write_rich_string('A1', *result)

workbook.close()

輸出:

在此處輸入圖片說明

jmcnamara的解決方案效果很好。 我發布了類似的可能解決方案,但是很動態。

import xlsxwriter
workbook = xlsxwriter.Workbook("<your path>")
worksheet = workbook.add_worksheet()
# add style for first column
cell_format = workbook.add_format({'bold': True})
text_wrap = workbook.add_format({'text_wrap': True, 'valign': 'top'})
data = []
description_combined = 'firstline: abc \n secondline: bcd \n thirdline: efg'
# prepare list of list
for item in description_combined.split("\n"):
    data.append(cell_format)
    data.append(item.split(":")[0].strip() + ":")
    data.append(item.split(":")[1] + "\n")

# write data in one single cell
data.append(text_wrap)

worksheet.write_rich_string('A1', *data)

workbook.close()

希望對您有所幫助

暫無
暫無

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

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