Python Learning-Common Module 8-manipulating Excel, writing, checking, and changing

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.