Use Python to read and write Excel, pythonexcel
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 all the content of this article. I hope this article will help you in your study or work. I also hope to provide more support to the customer's home!