1

Following up on an earlier question about a subset of the functionality I need, I'm trying to put rich text in a merged cell of an Excel worksheet created using the xlwt package. I know about sheet.write_merge() and (with the help of that earlier question) I found sheet.write_rich_text() but there doesn't appear to be a way to do both. Excel supports it, so at least in theory it should be possible for xlwt to do it. Is the functionality there and I just haven't found it?

Thanks!

Community
  • 1
  • 1
Bob Kline
  • 304
  • 1
  • 14

1 Answers1

1

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

  1. create your worksheet with the flag to allow cells to be overwritten
  2. write a dummy value to the range
  3. 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.

Bob Kline
  • 304
  • 1
  • 14