python数据存储系列教程——xls文件的读写

时间:2022-09-04 19:23:33

全栈工程师开发手册 (作者:栾鹏)

python教程全解

python将数据存储到excel文件。本文不通过与操作excel办公软件而是偏向于excel文件的处理。如果你需要通过python控制excel软件可以参考http://blog.csdn.net/luanpeng825485697/article/details/78361633

使用xlwt库,点击下载xlwt库

使用xlrd库,点击下载xlrd库

安装python库的方法,可以参考 Python库的安装与卸载

然后就可以处理excel文件了。

python3.6下xls文件的读写

#coding:utf-8
#xls文件的读写
import xlwt
import xlrd


#将数据写入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中读取数据
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)