1. Introduction
Use Python to read, write, modify excel need to use xlrd, xlwt and xlutils modules, these modules can be installed using pip.
Second, read excel
1 import xlrd 2 book = xlrd.open_workbook ('app_student.xls') 3 sheet = book.sheet_by_index (0) # get the sheet page according to the subscript 4 sheet = book.sheet_by_name ('sheet1') # get according to the sheet name Sheet page 5 print (sheet.cell (0,0)) # Specify rows and columns in excel to get data 6 print (sheet.cell (0,0) .value) # Add value directly to the cell Value 7 print (sheet.row_values (0)) # Get the content of the first few rows and put it in a list 8 print (sheet.col_values (0)) # Get the data of the first few columns and put it in a list 9 print (sheet.nrows) # Get the total number of rows in excel 10 print (sheet.ncols) # Get the total number of columns in excle 11 # Loop to get each row of data 12 for i in range (sheet.nrows): 13 print (sheet.row_values (i)) 14 # Loop to get the data of each column 15 for i in range(sheet.ncols): 16 print(sheet.col_values(i))
Three, write excel
1 import xlwt 2 book = xlwt.Workbook () # create a new excel 3 sheet = book.add_sheet ('sheet1') # add sheet page 4 sheet.write (0,0, 'name') # written content, front The two elements represent the row and column 5 sheet.write (0,1, 'age') 6 sheet.write (0,2, 'sex') 7 book.save ('stu.xls') # save excel, end Be sure to use .xls
Fourth, modify excel
1 import xlrd 2 from xlutils import copy # The xlutils module import method needs to be used this way, and direct import modules cannot be used 3 book = xlrd.open_workbook ('stu.xls') # Use the xlrd module first, open an excel 4 new_book = copy.copy (book) # Use the copy method in the xlutils module to copy an excel 5 sheet = new_book.get_sheet (0) # Get sheet page 6 lis = ['number', 'name', 'sex', 'age', ' Address', 'class',' mobile number ',' gold coin ') 7 # Use enumerate to directly get the subscript and value of the list element for cyclic writing excel 8 for col, filed in enumerate (lis): 9 print (col, filed) 10 sheet.write (0, col, filed) 11 new_book.save ('stu.xls')