全栈工程师开发手册 (作者:栾鹏)
python将数据存储到excel文件。本文不通过与操作excel办公软件而是偏向于excel文件的处理。如果你需要通过python控制excel软件可以参考http://blog.csdn.net/luanpeng825485697/article/details/78361633
使用xlwt库,点击下载xlwt库 或者pip install xlwt
使用xlrd库,点击下载xlrd库 或者pip install xlrd
使用xlutils库,使用pip install xlutils安装
安装python库的方法,可以参考 Python库的安装与卸载
然后就可以处理excel文件了。
xlwt的缺陷
xlwt只能创建一个全新的excel文件,然后对这个文件进行写入内容以及保存。但是大多数情况下我们希望的是读入一个excel文件,然后进行修改或追加,这个时候就需要xlutils了。
python3.6下xls文件的读写
#xls文件的读写
import xlwt
import xlrd
import xlutils
#将数据写入xls
workbook=xlwt.Workbook(encoding='utf-8') #文件编码
booksheet=workbook.add_sheet('Sheet 1', cell_overwrite_ok=True) #表名,是否覆盖
DATA=(('学号','姓名','年龄','性别','成绩'),
('1001','A','11','男','12'),
('1002','B','12','女','22'),
('1003','C','13','女','32'),
('1004','D','14','男','52'),
)
for i,row in enumerate(DATA): #迭代
for j,col in enumerate(row): #迭代
booksheet.write(i,j,col) #写入单元格
workbook.save('test.xls') #保存成文件
#将数据追加到xls
from xlrd import open_workbook
from xlutils.copy import copy
rexcel = open_workbook("test.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("test.xls") # xlwt对象的保存方法,这时便覆盖掉了原来的excel
#从xls中读取数据
fname = "test.xls"
data = xlrd.open_workbook(fname)
shxrange = range(data.nsheets)
try:
sh = data.sheet_by_name("Sheet 1")
nrows = sh.nrows
ncols = sh.ncols
print("hang %d, ncols %d" % (nrows, ncols))
for row_index in range(sh.nrows):
for col_index in range(sh.ncols):
print(sh.cell(row_index, col_index).value,end='')
print('')
except:
print("no sheet in %s named Sheet1" % fname)