First, write Excel
Import XLWT #只能写excel
Book = XLWT. Workbook () #创建excel
Sheet = book.add_sheet (' sru_info ') #加一个sheet页
Sheet.write (0,0, ' student number ')
Sheet.write (0,1, ' Student name ')
Sheet.write (0,2, ' score ')
Sheet.write (1, 0, ' 1 ')
Sheet.write (1, 1, ' Li Guang ')
Sheet.write (1, 2, ' 98.2 ')
Book.save (' Stu.xls ')
Second, view Excel
Import xlrd #只能读excel
# 1. Open Excel
Book = Xlrd.open_workbook (' Lyn.xls ') #打开一个excel
Print (book.nsheets) #获取到excel里面总共有多少个sheet页
Sheet = book.sheet_by_index (0) #获取sheet页, retrieved by index, page
# book.sheet_by_name (' Sheet1 ') #根据sheet页的名字获取
# Here's how to get the data
# Specify rows and columns to get the contents of a cell
Print (Sheet.cell (0,0). Value) #. Value makes the obtained data normal
Print (Sheet.cell (1,0). Value)
# Get the data for a row
Print (sheet.row_values (0))
Print (Sheet.row_values (1))
# get Sheet page total number of lines
Print (sheet.nrows)
# Get the data for a column
Print (sheet.col_values (0))
Print (Sheet.col_values (1))
# get Sheet page total number of columns
Print (Sheet.ncols)
Third, modify Excel
# ideas
# 1, open the original Excel
# 2, copy a new Excel
# 3, Get a sheet page
# 4, modify Excel
# To modify more data, you can cycle through the changes
# 5, close Excel
Import xlrd
From xlutils Import copy
# copy.copy () #要用这个方法复制原来的文件
Book1 = Xlrd.open_workbook (' Lyn.xls ') #打开原来的excel
New_book =copy.copy (Book1) #拷贝一个新的excel
Sheet = new_book.get_sheet (0) #获取一个sheet页
# Modify Excel
Sheet.write (1, 3, ' 18 ')
Sheet.write (1, 1, ' Xiao ')
New_book.save (' Lyn.xls ') #关闭excel
Python Learning-Common Module 8-manipulating Excel, writing, checking, and changing