文档介绍:Working with Excel files in Python
Reading Excel Files
All the examples shown below can be found in the xlrd directory of the course material.
Opening Workbooks
Workbooks can be loaded either from a file, an object or from a string:
Navigating a Workbook
Here is a simple example of workbook navigation:
The next few sections will cover the navigation of workbooks in more detail.
. Simplistix Ltd 2009
from mmap import mmap,ACCESS_READ
from xlrd import open_workbook
print open_workbook('')
with open('','rb') as f:
print open_workbook(
file_contents=mmap((),0,access=ACCESS_READ)
)
aString = open('','rb').read()
print open_workbook(file_contents=aString)
from xlrd import open_workbook
wb = open_workbook('')
for s in ():
print 'Sheet:',
for row in range():
values = []
for col in range():
((row,col).value)
print ','.join(values)
print
Page 8
Introspecting a Book
The object returned by open_workbook contains all information to do with
the workbook and can be used to retrieve individual sheets within the workbook.
The nsheets attribute is an integer containing the number of sheets in the workbook.
This attribute, bination with the sheet_by_index method, is the mon
way of retrieving individual sheets.
The sheet_names method returns a list of unicodes containing the names of all sheets in
the workbook. Individual sheets can be retrieved using these names by way of the
sheet_by_name function.
The results of the sheets method can be iterated over to retrieve each of the sheets in the
workbook.
The following example demonstrates these methods and attributes:
objects have other attributes relating to the content of the workbook that are
only rarely useful:
• codepage
• countries
• user_name
If you think you may need to use these attributes, please see the xlrd documentation.
. Simplistix Ltd