《在Python中的EXCEL应用》Working with Excel files in Python
Working with Excel files in PythonReading Excel FilesAll the examples shown below can be found in the xlrd directory of the course material.Opening WorkbooksWorkbooks can be loaded either from a file, an mmap.mmap object or from a string:Navigating a WorkbookHere is a simple example of workbook navigation:The next few sections will cover the navigation of workbooks in more detail.. Simplistix Ltd 2009from mmap import mmap,ACCESS_READfrom xlrd import open_workbookprint open_workbook('simple.xls')with open('simple.xls','rb') as f:print open_workbook(file_contents=mmap(f.fileno(),0,access=ACCESS_READ))aString = open('simple.xls','rb').read()print open_workbook(file_contents=aString)open.pyfrom xlrd import open_workbookwb = open_workbook('simple.xls')for s in wb.sheets():print 'Sheet:',for row in range(s.nrows):values = []for col in range(s.ncols):values.append(s.cell(row,col).value)print ','.join(values)printsimple.pyPage 8Introspecting a BookThe xlrd.Book object returned by open_workbook contains all information to do withthe 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, in combination with the sheet_by_index method, is the most commonway of retrieving individual sheets.The sheet_names method returns a list of unicodes containing the names of all sheets inthe workbook. Individual sheets can be retrieved using these names by way of thesheet_by_name function.The results of the sheets method can be iterated over to retrieve each of the sheets in theworkbook.The following example demonstrates these methods and attributes:xlrd.Book objects have other attributes relating to the content of the workbook that areonly rarely useful:? codepage? countries? user_nameIf you think you may need to use these attributes, please see the xlrd documentation.. Simplistix Ltd 2009from xlrd import open_workbookbook = open_workbook('simple.xls')print book.nsheetsfor