In the process of learning Python, we will encounter Excel reading and writing problems. At this point, we can use the XLWT module to write data to an Excel table and use the XLRD module to read data from Excel. Here's how to implement read and write to Excel using Python.
Python version: 3.5.2
Install the XLWT,XLRD two modules via Pip, if not installed:
Pip Install XLWT
Pip Install Xlrd
One, write to the Excel file:
#-*-Conding:utf-8-*-__author__ = ' Mayi ' #How to write to an Excel using XLWT moduleimport xlwt# creates a Wordbook object equivalent to creating an ex Cel file book = XLWT. Workbook (encoding = "Utf-8", style_compression = 0) #创建一个sheet对象, a sheet object corresponds to a table in an Excel file sheet = Book.add_sheet (" Sheet1 ", Cell_overwrite_ok = True) #向表sheet1中添加数据sheet. Write (0, 0," Englishname ") #其中," 0, 0 "Specify cells in the table," Englishname "is the content written to the cell sheet.write (1, 0," MaYi ") sheet.write (0, 1," Chinese name ") sheet.write (1, 1," ant ") #最后, Save the above operation to the specified Excel file Book.save ("Name.xls")
Second, the Excel file read operation:
#-*-conding:utf-8-*-__author__ = ' Mayi ' # How to-read from an Excel using xlrd m Oduleimport xlrd# Open the XLS file in the specified path, get the book object xls_file = "Name.xls" #打开指定文件book = Xlrd.open_workbook (xls_file) # Get sheet object by sheet index sheet1 = book.sheet_by_index (0) # # Gets the sheet name of the specified index # sheet1_name = Book.sheet_names () [0]# Print (sheet1_ Name) # # Sheet Sheet Object # sheet1 = Book.sheet_by_name (sheet1_name) # Gets the number of rows and columns # Total number of columns nrows = sheet1.nrows# number of column Ncols = Sheet1 . ncols# traversing the contents of the printed table for I in range (nrows): for J in Range (ncols): Cell_value = Sheet1.cell_value (i, j) print (Cell_value, end = "\ T") print ("")