Home » excel » Using Jython to Export to Formatted Excel File

Using Jython to Export to Formatted Excel File

Posted by: admin May 14, 2020 Leave a comment


I’m doing some testing, and I want the results to be outputted to an Excel sheet. It is very simple data – only whether it passed or failed:

test1   PASSED
test2   FAILED

I am able to export into a csv file like so:

f = open('TestResults.csv', 'a')
f.write(test + "," + status)

This creates a 2 column table, the first column being the test name, and the second being whether it passed or failed (the status). However, I would like to format the output so that a row with “PASSED” will turn green, and a row with “FAILED” will turn red. I don’t think .csv files can contain formatting like that, so it would probably need convert it in some way.

I tried saving the file with the format, but it is always removed the next time I open it.

If possible, I would prefer doing this without downloading an external module.


How to&Answers:

The CSV (comma separated values) file format does not support formatting.
You can use XLSXWriter to create a native Excell document that supports formatting. There is pretty good documentation on their website.

I know you prefer not to use any external modules, but this is the only solution I have.

Good luck!


Since the main purpose of this is to have a visual of the results, I decided to send it to an html file; with html, I was able to format everything in a way that was easy to read.

While this may not be the most efficient way of doing this, in order to add a new row each time, I created a string in my jython code that contained the html code required to create a new row – then I plugged in the information. If anyone is curious, here’s how the html string looks in the jython code:

    pageTemplate = "<!DOCTYPE html PUBLIC '-//W3C//DTD HTML 4.01 Transitional//EN'>" \
    "<html>" \
    "<head>" \
    "<style type='text/css'>" \
    "p {margin: 0em 0 0em 0}" \
    "</style>" \
    "<meta content='text/html; charset=ISO-8859-1'" \
    "http-equiv='content-type'>" \
    "<title>LogFile</title>" \
    "</head>" \
    "<body>" \
    "<p><a href='%s.%s.png'>%s</a>%s%s</p>" \
    "</body>" \

    #color codes the status
    if status == "PASSED":
        status_colored = "<font color='green'>PASSED</font>"
        status_colored = "<font color='red'>FAILED</font>"

    rest = self.delim + test + self.delim + comment + "\n"
    dir = os.path.join(self.path,stamp)

    #save new information to the logfile
    contents = pageTemplate % (dir, status, stamp, self.delim + status_colored, rest)
    logfile = open(self.csvpath, 'a')

The missing information is declared elsewhere in the code. Also, the headers were hardcoded into the html file itself, not through the Jython code.