I still haven't found a sheet.write_rich_text_merge()
method in the API which does what I need to do here, but I did find by experimenting an approach which appears to work. What you have to do is
- create your worksheet with the flag to allow cells to be overwritten
- write a dummy value to the range
- replace the content of the first cell in the range with the value sequence
For example:
import xlwt
book = xlwt.Workbook()
style = xlwt.easyxf("align: wrap true, horiz left, vert top")
comment_font = xlwt.easyfont("italic true, color_index green")
sheet = book.add_sheet("Merged Rich Text", cell_overwrite_ok=True)
sheet.col(0).width = sheet.col(1).width = 7500
drug_name = "atezolizumab"
comment = "For NCT01375842; No info available at this time"
segments = (drug_name, "\n", ("[%s]" % comment, comment_font))
other_names = ("anti-PD-L1 monoclonal antibody", "MPDL3280A", "RG7446")
sheet.write_merge(0, len(other_names) - 1, 0, 0, "", style)
sheet.row(0).set_cell_rich_text(0, segments, style)
for i, name in enumerate(other_names):
sheet.write(i, 1, name, style)
fp = open("repo.xls", "wb")
book.save(fp)
fp.close()
It would be preferable to have an API function which handled the merge and the rich text formatting with a single call, without the need to suppress the check for overwriting cells, but if you're always careful to test your code by temporarily commenting out the set_cell_rich_text()
call and removing the flag to allow cell overwriting, you'll still be able to catch bugs elsewhere in which cells are being overwritten by mistake.