Using Python to read and write operations with the same Excel (Xlrd,xlwt,xlutils)

Source: Internet
Author: User

Recently began to learn Python, want to do simple automated test, need to read and write Excel, and then found XLRD to read the Excel file, using XLWT to generate Excel files (you can control the format of cells in Excel), it is important to note that Reading Excel with XLRD cannot operate on it: the Xlrd.open_workbook () method returns XLRD. Book type, which is read-only and cannot be manipulated. and XLWT. Workbook () returns the XLWT. The workbook type of Save (filepath) method can save an Excel file.


So it's easy to handle reading and generating Excel files, but making changes to an existing Excel file can be tricky. However, there is also a xlutils (dependent on xlrd and XLWT) that provides the ability to copy the contents of an Excel file and modify the file. Its reality is only in xlrd. There was a pipeline between book and Xlwt.workbook.


The following is the sample code:


Import XLWT

Import xlrd

From xlutils.copy Import copy


#使用xlrd读取指定excel工作中的指定表格的值并返回

def excel_read (doc,table,x,y):

data = Xlrd.open_workbook (DOC)

Table = data.sheet_by_name (table)

return Table.cell (x, y). Value


#使用xlwt创建指定excel工作中的指定表格的值并保存

def excel_create (Sheet,value):

data = XLWT. Workbook ()

Table = Data.add_sheet (sheet)

Table.write (1,4,value)

Data.save (' Demo.xls ')


#三个结合操作同一个excel

RB = Xlrd.open_workbook (' Demo.xls ')

#管道作用

WB = Copy (RB)

#通过get_sheet () Gets the sheet has the write () method

WS = Wb.get_sheet (1) #1代表是写到第几个工作表里, starting from 0 is the first one.

Ws.write (1, 6, ' changed! ')

Wb.save (' Demo.xls ')


Use Python to read and write operations to the same Excel (Xlrd,xlwt,xlutils)

Related Article

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.