Installing openpyxl and get it working

Posted on Wednesday, February 5, 2020









I have a need to create some xls files on the fly.  I want to do this with a simple python program so I am going to start with openPyXL and see what it can do.

In this article I am just going to get openPyXL installed and up and running.





Ubuntu 18.04


First install python-pippyth

First install pip


  > sudo apt install python3-pip


Now use pip to install openpyxl


  > pip3 install openpyxl








Simple python script to create xls file





  > vi createxls.py


And place the following in it



#!/usr/bin/env python3

import openpyxl
from openpyxl import Workbook

#############################################
#  MAIN
#############################################
if __name__ == '__main__':


   wb = Workbook()

   # grab the active worksheet
   ws_01 = wb.active

   #Set the title of the worksheet
   ws_01.title = "First Sheet"

   #place a few values in
   ws_01['A1'] = 1
   ws_01['B2'] = 2
   ws_01['C3'] = 3

   #Save it in an Excel fie
   wb.save("test_01.xlsx")





Now chmod it and run it



  > chmod u+x createxls.py
  > ./createxls.py


Now open it up





Boom




  > vi createxls2.py


And place the following in it



#!/usr/bin/env python3

import openpyxl
from openpyxl import Workbook



#############################################
#  MAIN
#############################################
if __name__ == '__main__':


   wb = Workbook()

   # grab the active worksheet
   ws_01 = wb.active

   #Set the title of the worksheet
   ws_01.title = "First Sheet"

   #place a few values in
   ws_01['A1'] = 1
   ws_01['B2'] = 2
   ws_01['C3'] = 3

   ws_02 = wb.create_sheet()
   ws_02.title = "Second Sheet"

   for row in  range (1, 6):
     for col in range (1, 4):
       value = row*col
       ws_02.cell(row, col, value)



   #Save it in an Excel fie
   wb.save("test_02.xlsx")



Now chmod it and run it



  > chmod u+x createxls2.py
  > ./createxls2.py


Now open it up




Boom






No comments:

Post a Comment