Python read, write/append excel file Demo

不言
Release: 2018-05-04 15:52:17
Original
2008 people have browsed it

This article mainly introduces the Demo about Python reading and writing/appending excel files. It has certain reference value. Now I share it with you. Friends in need can refer to it

python The three toolkits for operating excel are as follows. Note that you can only operate .xls, not .xlsx.

• xlrd: Perform read-related operations on excel

• xlwt: Perform write-related operations on excel

• xlutils: Integration of excel read and write operations

These three toolkits can be downloaded directly using pip:

sudo pip install xlrd
sudo pip install xlwt
sudo pip install xlutils1
Copy after login

Defects of xlwt

xlwt can only create a brand new excel file , and then write the content and save the file. But in most cases what we want is to read an excel file and then modify or append it. In this case, xlutils is needed.

Simple use of xlutils

The following demo is to append content to an excel file:

#coding:utf-8

from xlrd import open_workbook
from xlutils.copy import copy


rexcel = open_workbook("collection.xls") # 用wlrd提供的方法读取一个excel文件
rows = rexcel.sheets()[0].nrows # 用wlrd提供的方法获得现在已有的行数
excel = copy(rexcel) # 用xlutils提供的copy方法将xlrd的对象转化为xlwt的对象
table = excel.get_sheet(0) # 用xlwt对象的方法获得要操作的sheet
values = ["1", "2", "3"]
row = rows
for value in values:
  table.write(row, 0, value) # xlwt对象的写方法,参数分别是行、列、值
  table.write(row, 1, "haha")
  table.write(row, 2, "lala")
  row += 1
excel.save("collection.xls") # xlwt对象的保存方法,这时便覆盖掉了原来的excel
Copy after login

Related recommendations:

Detailed explanation of reading and writing json files with python (with code)

Reading and writing Excel documents with Python

The above is the detailed content of Python read, write/append excel file Demo. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template