<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>scienceoss.com &#187; excel</title>
	<atom:link href="http://scienceoss.com/categories/excel/feed/" rel="self" type="application/rss+xml" />
	<link>http://scienceoss.com</link>
	<description>useful tidbits for using open source software in science</description>
	<lastBuildDate>Wed, 26 May 2010 03:34:19 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
		<item>
		<title>Write Excel files with Python using xlwt</title>
		<link>http://scienceoss.com/write-excel-files-with-python-using-xlwt/</link>
		<comments>http://scienceoss.com/write-excel-files-with-python-using-xlwt/#comments</comments>
		<pubDate>Sun, 20 Sep 2009 17:29:12 +0000</pubDate>
		<dc:creator>ryan</dc:creator>
				<category><![CDATA[excel]]></category>
		<category><![CDATA[other software]]></category>
		<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://scienceoss.com/?p=232</guid>
		<description><![CDATA[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&#8217;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 [...]]]></description>
			<content:encoded><![CDATA[<p>In a <a href="http://scienceoss.com/read-excel-files-from-python/">previous post</a> (which turned out to be pretty popular) I showed you how to read Excel files with Python.  Now for the reverse: writing Excel files.</p>
<p>First, you&#8217;ll need to install the <a href="http://pypi.python.org/pypi/xlwt">xlwt</a> package by John Machin.</p>
<h3>The basics</h3>
<p>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:</p>
<pre class="brush: python; title: ; notranslate">
import xlwt
wbk = xlwt.Workbook()
sheet = wbk.add_sheet('sheet 1')
</pre>
<p>Now that the sheet is created, it&#8217;s very easy to write data to it.</p>
<pre class="brush: python; title: ; notranslate">
# indexing is zero based, row then column
sheet.write(0,1,'test text')
</pre>
<p>When you&#8217;re done, save the workbook (you don&#8217;t have to close it like you do with a file object)</p>
<pre class="brush: python; title: ; notranslate">
wbk.save('test.xls')
</pre>
<h3>Digging deeper</h3>
<h4>Overwriting cells</h4>
<p>Worksheet objects, by default, give you a warning when you try to overwrite:</p>
<pre class="brush: python; title: ; notranslate">
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
</pre>
<p>To change this behavior, use the <code>cell_overwrite_ok=True</code> kwarg when creating the worksheet, like so:</p>
<pre class="brush: python; title: ; notranslate">
sheet2 = wbk.add_sheet('sheet 2', cell_overwrite_ok=True)
sheet2.write(0,0,'some text')
sheet2.write(0,0,'this should overwrite')
</pre>
<p>Now you can overwrite sheet 2 (but not sheet 1).</p>
<h4>More goodies</h4>
<pre class="brush: python; title: ; notranslate">
# 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)
</pre>
<p>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:</p>
<ul>
<li><code>dates.py</code>, which shows how to use the different date formats</li>
<li><code>hyperlinks.py</code>, which shows how to create hyperlinks (<em>hint: you need to use a formula</em>)</li>
<li><code>merged.py</code>, which shows how to merge cells</li>
<li><code>row_styles.py</code>, which shows how to apply styles to entire rows.</li>
</ul>
<h3>Non-trivial example</h3>
<p>Here&#8217;s an example of some data where the dates not formatted well for easy import into Excel:</p>
<pre class="brush: plain; title: ; notranslate">
20 Sep, 263, 1148,   0,   1,   0,   0,   1,   12.1,   13.9, 1+1, 19.9
 20 Sep, 263, 1118,   0,   1,   0, 360,   0,   14.1,   15.3, 1+1, 19.9
 20 Sep, 263, 1048,   0,   1,   0,   0,   0,   14.2,   15.1, 1+1, 19.9
 20 Sep, 263, 1018,   0,   1,   0, 360,   0,   14.2,   15.9, 1+1, 19.9
 20 Sep, 263, 0948,   0,   1,   0,   0,   0,   14.4,   15.3, 1+1, 19.9
</pre>
<p>The first column has the day and month separated by a space.  The second column is year-day, which we&#8217;ll ignore.  The third column has the time. The data we&#8217;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.</p>
<p>Here&#8217;s a [heavily commented] script to do just that.  It assumes that you have the data saved as <code>weather.data.exampl</code>e.</p>
<pre class="brush: python; title: ; notranslate">
'''
Script to convert awkwardly-formatted weather data
into an Excel spreadsheet using Python and xlwt.
'''

from datetime import datetime
import xlwt

# Create workbook and worksheet
wbk = xlwt.Workbook()
sheet = wbk.add_sheet('temperatures')

# Set up a date format style to use in the
# spreadsheet
excel_date_fmt = 'M/D/YY h:mm'
style = xlwt.XFStyle()
style.num_format_str = excel_date_fmt

# Weather data has no year, so assume it's the current year.
year = datetime.now().year

# Convert year to a string because we'll be
# building a date string below
year = str(year)

# The format of the date string we'll be building
python_str_date_fmt = '%d %b-%H%M-%Y'

row = 0  # row counter
f = open('weather.data.example')
for line in f:
    # separate fields by commas
    L = line.rstrip().split(',')

    # skip this line if all fields not present
    if len(L) &lt; 12:
        continue

    # Fields have leading spaces, so strip 'em
    date = L[0].strip()
    time = L[2].strip()

    # Datatypes matter. If we kept this as a string
    # in Python, it would be a string in the Excel sheet.
    temperature = float(L[8])

    # Construct a date string based on the string
    # date format  we specified above
    date_string = date + '-' + time + '-' + year

    # Use the newly constructed string to create a
    # datetime object
    date_object = datetime.strptime(date_string,
                                    python_str_date_fmt)

    # Write the data, using the style defined above.
    sheet.write(row,0,date_object, style)
    sheet.write(row,1,temperature)

    row += 1

wbk.save('reformatted.data.xls')
</pre>
<p>Still curious? Other questions?  Check out the <a href="http://groups.google.com/group/python-excel?pli=1">python-excel google group </a>!  Also check out <a href="http://pypi.python.org/pypi/xlutils">xlutils</a> for more functionality, which I plan to play around with next.</p>
]]></content:encoded>
			<wfw:commentRss>http://scienceoss.com/write-excel-files-with-python-using-xlwt/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
	</channel>
</rss>

