In
a previous
post (which turned out to be pretty popular) I
showed you how to read Excel files with Python. Now for the
reverse: writing Excel files.
First, you’ll need to
install the xlwt package
by John Machin.
The basics
In order to write data
to an Excel spreadsheet, first you have to initialize a Workbook
object and then add a Worksheet object to that Workbook. It goes
something like this:
import
xlwt
wbk
=
xlwt.Workbook()
sheet
=
wbk.add_sheet('sheet
1')
|
Now that the sheet is
created, it’s very easy to write data to it.
# indexing is zero based, row then column
sheet.write(0,1,'test
text')
|
When you’re done, save
the workbook (you don’t have to close it like you do with a file
object)
Digging deeper
Overwriting cells
Worksheet objects, by
default, give you a warning when you try to overwrite:
sheet.write(0,0,'test')
sheet.write(0,0,'oops')
# returns error:
# Exception: Attempt to overwrite cell: sheetname=u'sheet 1' rowx=0
colx=0
|
To change this behavior,
use the cell_overwrite_ok=True kwarg
when creating the worksheet, like so:
sheet2
=
wbk.add_sheet('sheet
2',
cell_overwrite_ok=True)
sheet2.write(0,0,'some
text')
sheet2.write(0,0,'this
should overwrite')
|
Now you can overwrite
sheet 2 (but not sheet 1).
More goodies
# Initialize a style
style
=
xlwt.XFStyle()
# Create a font to use with the style
font
=
xlwt.Font()
font.name
=
'Times New Roman'
font.bold
=
True
# Set the style's font to this new one you set up
style.font
=
font
# Use the style when writing
sheet.write(0,
0,
'some bold Times text',
style)
|