6-5 How to read and write excel files

>>> import xlrd,xlwt

First, read excel

1. Open an excel (read mode)

>>> book = xlrd.open_workbook(r " C:\video\python efficient practice skills notes\6 topics related to data encoding and processing\6-6.xls " )    #Open an excel in read mode, read an excel first instance Make a workbook 
>>> book.sheets() #View         each sheet of excel 
[<xlrd.sheet.Sheet object at 0x02CD7270>, <xlrd.sheet.Sheet object at 0x02CD7530>, <xlrd.sheet.Sheet object at 0x02CD7590> ]

2. Open a sheet

>>> book.sheet_by_index(0)
<xlrd.sheet.Sheet object at 0x02CD7270>
>>> sheet0 =book.sheet_by_index(0) #Open   a table by index 
>>> sheet0.nrows #Number             of rows in the table
4
>>> sheet0.ncols #The             number of columns in the table
4
>>> sheet0.name #name                 of sheet 
u ' \u6210\u7ee9 ' 
>>> print sheet0.name
score

3. Get a table in the table

>>> cell = sheet0.cell(0,0) #Get         a cell in the table and select it by coordinates

>>> cell      #The print result shows that it is of text (text) type, and the content is u'\u59d3\u540d' (unicode of grades) 
text:u ' \u59d3\u540d ' 
>>> cell.ctype #View                 cell content The type of which the result is a cell type, which is defined in xlrd.XL_CELL_  
1
>>> xlrd.XL_CELL_TEXT #The             type of text content is 1
1

>>> print cell.value
Name

>>> cell = sheet0.cell(1,2) #Take         the table with coordinates (1,2) 
>>>                 cell #The cell type is number and the content is 99.0
number:99.0

>>> cell.ctype
2
>>> xlrd.XL_CELL_NUMBER
2
>>> cell.value
99.0

4. View the entire line

>>> sheet0.row(1) #Get     the content of 1 row, the parameter is the row number, and return a list. Each object is a cell object 
[text:u ' \u674e\u96f7 ' , number:95.0, number:99.0, number:96.0 ]
 >>> sheet0.row_values(1) #Get     the content of 1 row (without content The signature of the type, directly the content) returns a list 
[u ' \u674e\u96f7 ' , 95.0, 99.0, 96.0 ]

>>> sheet0.row_values(1,1) #Get     1 row content, starting from item 1, with slice function 
[95.0, 99.0, 96.0]
>>> help(sheet0.row_values)
Help on method row_values in module xlrd.sheet:

row_values(self, rowx, start_colx=0, end_colx=None) method of xlrd.sheet.Sheet instance
Returns a slice of the values of the cells in the given row.
help(sheet0.row_values)

5. View the entire column, similar to the row row operation

>>> sheet0.col(1)
[text:u'\u8bed\u6587', number:95.0, number:98.0, number:94.0]
>>> sheet0.col_values(1)
[u'\u8bed\u6587', 95.0, 98.0, 94.0]
>>> sheet0.col_values(1,1)
[95.0, 98.0, 94.0]

6. Add a cell

>>> help(sheet0.put_cell)
Help on method put_cell_unragged in module xlrd.sheet:

put_cell_unragged(self, rowx, colx, ctype, value, xf_index) method of xlrd.sheet.Sheet instance
help(sheet0.put_cell)

The parameters are, line number, column number, content type, value, xf_index is the font, alignment and other formats (can be filled in None)

Second, write excel

1. #To write an excel, you must first instantiate a workbook

>>> wbook = xlwt.Workbook()         #Note the difference with xlrd

2. Add a sheet, the parameter is the sheet name

>>> wsheet1 = wbook.add_sheet('sheet1') 

3. Write a cell

>>> help(wsheet1.write)
Help on method write in module xlwt.Worksheet:

write(self, r, c, label='', style=<xlwt.Style.XFStyle object>) method of xlwt.Worksheet.Worksheet instance
This method is used to write a cell to a :class:`Worksheet`.
help(wsheet1.write)

4. Save excel to file

>>> help(wbook.save)
Help on method save in module xlwt.Workbook:

save(self, filename_or_stream) method of xlwt.Workbook.Workbook instance
    This method is used to save the Workbook to a file in native Excel
    format.
    
    :param filename_or_stream:
      This can be a string containing a filename of
      the file, in which case the excel file is saved to disk using the name
      provided. It can also be a stream object with a write method, such as
      a :class:`~io.StringIO`, in which case the data for the excel
      file is written to the stream.
help(wbook.save)

Add a total score to the rightmost column of 6-6.xls. Note that xlrd can add a column, but it does not have the function of saving. The script file code is:

# -*- coding: cp936 -*-


import xlrd,xlwt

rbook = xlrd.open_workbook(r ' C:\video\python efficient practice skills notes\6 topics related to data encoding and processing\6-6.xls ' )
rsheet = rbook.sheet_by_index(0) #Open     sheet 
nc = rsheet.ncols #Get             the number of columns 
nr = rsheet.nrows #Get             the number of rows 
rsheet.put_cell(0,nc,xlrd.XL_CELL_TEXT,u ' total score ' ,None)   # Place a cell, the content format is text, and the content is the total score for row in xrange(1,nr):             #Iterate each row of the table (except the title bar) 
    t = sum(rsheet.row_values(row,1))          #Get The value of the row and sum (except the title column)         
    rsheet.put_cell(row,nc,xlrd.XL_CELL_NUMBER,t,None) #Place a cell in each row, the content is the calculated sum value





wbook = xlwt.Workbook() #Create             an excel 
wsheet = wbook.add_sheet(rsheet.name) #Add         a sheet name to read the name of the sheet 
style = xlwt.easyxf( ' align: vertical center,horizontal center ' ) #Define unit The format of the grid is prepared for write. Unlike put_cell, put_cell can pass None, but write cannot.

for row in xrange(rsheet.nrows):
     for col in xrange(rsheet.ncols): #Iteratively         read each row and column of the sheet, and iterate each cell, because when writing, you can only write to the cells one by one, not Write the whole row 
        cell = rsheet.cell_value(row,col) #Get the content of the cell that reads the sheet 
        wsheet.write(row,col,cell,style) #Write and write the sheet cell 

wbook.save(r ' C:\ Video\python efficient practice skills notes\6 topics related to data encoding and processing\6-6output.xlsx ' )             #Save excel as

The output format is:

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325073253&siteId=291194637