Python and Excel together¶
%%bash
which python
python --version
pip --version
/opt/hostedtoolcache/Python/3.7.8/x64/bin/python
Python 3.7.8
pip 20.2 from /opt/hostedtoolcache/Python/3.7.8/x64/lib/python3.7/site-packages/pip (python 3.7)
Installing packages¶
pip
is a tool that we can use to install packages. Sometimes people refer to packages as libraries.
Naming things in computer development is hard.
Tip: Jargon exists. Try to ask questions if you find a word confusing.
Let’s install the xlsxwriter
package. GitHub Docs
%%bash
pip install --user xlsxwriter
Requirement already satisfied: xlsxwriter in /opt/hostedtoolcache/Python/3.7.8/x64/lib/python3.7/site-packages (1.3.2)
WARNING: You are using pip version 20.2; however, version 20.2.1 is available. You should consider upgrading via the '/opt/hostedtoolcache/Python/3.7.8/x64/bin/python -m pip install --upgrade pip' command.
# Getting started with Excel
import xlsxwriter
Limitations¶
xlsxWriter can only create new files. It cannot read or modify existing files.
# Create an new Excel file and add a worksheet.
workbook = xlsxwriter.Workbook('demo.xlsx')
worksheet = workbook.add_worksheet()
# Widen the first column to make the text clearer.
worksheet.set_column('A:A', 20)
0
# Add a bold format to use to highlight cells.
bold = workbook.add_format({'bold': True})
# Write some simple text.
worksheet.write('A1', 'Hello')
0
# Text with formatting.
worksheet.write('A2', 'World', bold)
0
# Write some numbers, with row/column notation.
worksheet.write(2, 0, 123)
worksheet.write(3, 0, 123.456)
0
# Insert an image.
worksheet.insert_image('B5', 'logo.png')
/opt/hostedtoolcache/Python/3.7.8/x64/lib/python3.7/site-packages/xlsxwriter/worksheet.py:1202: UserWarning: Image file 'logo.png' not found. warn("Image file '%s' not found." % force_unicode(filename))
-1
workbook.close()