When learning Python, we will encounter the Excel read/write problem. In this case, we can use the xlwt module to write data into an Excel table and use the xlrd module to read data from Excel. The following describes how to use Python to read and write Excel files. When learning Python, we will encounter the Excel read/write problem. In this case, we can use the xlwt module to write data into an Excel table and use the xlrd module to read data from Excel. The following describes how to use Python to read and write Excel files.
Python version: 3.5.2
Install the xlwt and xlrd modules using pip, if not:
Pip install xlwt
Pip install xlrd
1. write an Excel file:
#-*-Conding: UTF-8-*-_ author _ = 'mayi' # How to write to an Excel using xlwt moduleimport xlwt # Create a Wordbook object, it is equivalent to creating an Excel file book = xlwt. workbook (encoding = "UTF-8", style_compression = 0) # Create a sheet object. a sheet object corresponds to a table sheet in the Excel file. add_sheet ("sheet1", cell_overwrite_ OK = True) # Add data sheet to table sheet1. write (0, 0, "EnglishName") # where "0, 0" specifies the cells in the table, and "EnglishName" is the content sheet written to the cell. write (1, 0, "MaYi") sheet. write (0, 1, "Chinese name") sheet. write (1, 1, "ant") # finally, save the above operations to the specified Excel file book. save ("name.xls ")
2. read Excel files:
#-*-Conding: UTF-8-*-_ author _ = 'mayi' # How to read from an Excel using xlrd moduleimport xlrd # Open the xls file in the specified path, obtain the book object xls_file = "name.xls" # Open the specified file book = xlrd. open_workbook (xls_file) # obtain the sheet object sheet1 = book through the sheet index. sheet_by_index (0) # obtain the sheet name of the specified index # sheet1_name = book. sheet_names () [0] # print (sheet1_name) # obtain the sheet object using the sheet name # sheet1 = book. sheet_by_name (sheet1_name) # obtain the number of rows and columns # total number of rows nrows = sheet1.nrows # total number of columns ncols = sheet1.ncols # traverse the content in the print table for I in range (nrows ): for j in range (ncols): cell_value = sheet1.cell _ value (I, j) print (cell_value, end = "\ t") print ("")
The above is a detailed description of how to use Python to read and write Excel. For more information, see other related articles in the first PHP community!