有时候我们可以把一些简单的数据存储进Excel文件中,比如我们的我们爬取了某网站的用户ID,昵称,我们可以存储进Excel中。
环境安装
xlwt,xlrd是python读写操作excel的模块,你可以使用pip或者源码安装:
pip install xlwt
pip install xlrd
或者通过源码安装
下载后安装即可
sudo python setup.py intall
那么我们怎么读写excel呢?怎么解决中文报错呢?我这里总结了所有方法,大家直接运行就可以了,有注释;由于官方的解释很详细,我这里只是大概介绍一下。
# -*- coding: utf-8 -*-
import xlwt
import xlrd
import sys
reload(sys)
sys.setdefaultencoding('utf8')
class Excel(object):
def __init__(self, usename,password):
self.usename = usename
self.password = password
# 设置表头
def WriteSheetRow(self,sheet,rowValueList,rowIndex,isBold):
i = 0
style = xlwt.easyxf('font: bold 1')
#style = xlwt.easyxf('font: bold 0, color red;')#红色字体
#style2 = xlwt.easyxf('pattern: pattern solid, fore_colour yellow; font: bold on;') # 设置Excel单元格的背景色为黄色,字体为粗体
for svalue in rowValueList:
strValue = unicode(str(svalue),'utf-8')
if isBold:
sheet.write(rowIndex,i,strValue,style)
else:
sheet.write(rowIndex,i,strValue)
i = i + 1
# 写入excel
def write(self):
wb = xlwt.Workbook()
# 表名
ws = wb.add_sheet('setno')
headList = ['ID','电话','姓名']
rowIndex = 0
self.WriteSheetRow(ws,headList,rowIndex,True)
# ws.write(0, 0, 1234.56, style0)
# ws.write(1, 0, datetime.now(), style1)
ws.write(1, 0, "1")
ws.write(1, 1, "15512342222")
ws.write(1, 2, "李雷".decode('utf-8'))
ws.write(2, 0, "2")
ws.write(2, 1, "15512342222")
ws.write(2, 2, "韩梅梅".decode('utf-8'))
wb.save('setno.xlsx')
def read(self):
data = xlrd.open_workbook("setno.xlsx")
table = data.sheets()[0]
nrows = table.nrows #行数
ncols = table.ncols #列数
for i in xrange(0,nrows):
rowValues= table.row_values(i) #某一行数据
for item in rowValues:
print item
if __name__ == "__main__":
excel = Excel("1","2")
excel.write()