Explain how to read and write Excel using Python

Source: Internet
Author: User
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 ("") 

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.