Prime numbers matrix and coloring with Python and xlsxwriter

About 4 years ago, I wrote an article about prime numbers in Excel and their visualisation with VBA – vba-function-in-excel-to-check-prime-numbers. Pretty much, it displays the prime numbers in a 10 x N matrix, starting from 1 and finishing at N:

So, in this article, I will do exactly the same thing with Python and the xlsxwriter library. So, let’s try to summarize the task:

  • write a matrix with 10 cells per row
  • format these cells as follows:
    • centre them
    • color them in green and bold them, if the cell contains prime number

That’s all. For the writing of the matrix, it is quite important to note, that in Python the first column and first row of Excel is with index 0. Which is not the case in the Excel library of VBA. Thus, the following code, writing to 0th row and 0th column in Excel through Python is actually working:

And providing what is expected, with “A1” being on the 0th column and 0th row:

Once this is fixed in our task, the only problem left is the format. To be honest, although the documentation of the xlswriter is quite well written, it still took me some time to fix it. Anyway, the format is presented as a dictionary with the format parameters being the keys:

At the end, fixing the columns at a specific width in excel is a 1 liner as expected – wks.set_column(0,9,3.22). Of course, starting from the 0th column. And 3.22 is the width, that is quite ok to display a 3 digit number.

This is how the complete python code looks like:

Code in GitHub here.

Tagged with: , , , , , , , , , ,