Jump to content
Search In
  • More options...
Find results that contain...
Find results in...

Export underlined text into .xlsx with Python

I'm writing a program using Python 3.7 that needs to export cells into an Excel document with part of the text in each cell underlined.

To form the Excel document I'm currently using the openpyxl library, which, as far as I have been able to find, has the ability to style cell by cell, but not just portions of text inside the cells - I've also looked into using xlsxwriter, which has one picture that looks like it may have been able to format on the string level, but nothing in the documentation. I'm open to using any export solution though.

I've also tried using U+0332, combining low line, between characters but since I'm working partially with Chinese text it does not render correctly.

 

Text is scraped using Beautiful Soup 4 and portions that needed to be underlined could be enclosed in <u> tags if needed. If there is a macro or number format that I could use to remove the tags and replace them with an underline that would also work great for my use case.

 

Thanks for your help in advance!

 

Edit:

So looking at the Excel object model it looks like the smallest object you can really work with is a range of one cell, not content inside the cell. Fairly certain that there isn't a Python library that can format pieces of the string, going to try to write something in VBA. Direction on that would also be appreciated.

Edited by AnAverageName
Added details
Link to comment
Share on other sites

Link to post
Share on other sites

This is possible in xlsxwriter, using write_rich_string. The format precedes the text arg to be formatted.  

 

import xlsxwriter
workbook = xlsxwriter.Workbook('test.xlsx')
worksheet = workbook.add_worksheet()
underline = workbook.add_format({'underline': True})
worksheet.write_rich_string(0, 0, 'under', underline, 'line') # 'line' is underlined, 'under' is not.
worksheet.write_rich_string('A2', underline, 'under', 'line') # 'under' is underlined, 'line' is not.
workbook.close()

image.png.1ac75f9878dbb483eb830c546022f6ed.png

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share


×