您的位置:首页 > 编程语言 > Python开发

Write Excel files with Python using xlwt

2011-12-20 22:10 543 查看
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:

Now that the sheet is created, it’s very easy to write data to it.

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:

To change this behavior, use the
cell_overwrite_ok=True
kwarg when creating the worksheet, like so:

Now you can overwrite sheet 2 (but not sheet 1).

More goodies

xlwt allows you to format your spreadsheets on a cell-by-cell basis or by entire rows; it also allows you to add hyperlinks or even formulas. Rather than recap it all here, I encourage you to grab a copy of the source code, in
which you can find the examples directory. Some highlights from the examples directory in the source code:

dates.py
, which shows how to use the different date formats
hyperlinks.py
, which shows how to create hyperlinks (hint: you need to use a formula)
merged.py
, which shows how to merge cells
row_styles.py
, which shows how to apply styles to entire rows.

Non-trivial example

Here’s an example of some data where the dates not formatted well for easy import into Excel:

The first column has the day and month separated by a space. The second column is year-day, which we’ll ignore. The third column has the time. The data we’re interested in is in the 9th column (temperature). The goal is to have
a simple Excel file where the first column is date, and the second column is temperature.

Here’s a [heavily commented] script to do just that. It assumes that you have the data saved as
weather.data.exampl
e.

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: