1、安装xlrd模块,
pip install xlrd,成功后
2、 打开exlce表格
data = xlrd.open_workbook('test.xlsx')
table = data.sheets()[0] # 通过索引顺序获取sheet
table = data.sheet_by_index(0) # 通过索引顺序获取
table = data.sheet_by_name(u'Sheet1') # 通过名称获取
nrows = table.nrows # 获取总行数
ncols = table.ncols # 获取总列数
# 获取一行或一列的值,参数是第几行
print table.row_values(0) # 获取第一行值
print table.col_values(0) # 获取第一列值
3、在excel中,第一行为标题,也就是对应字典里面的key值,如:username,password
excel数据中有纯数字的话一定要设置单元格格式--》文本格式,要不然读取的数据是浮点数
1.读数据
多个字典的list类型数据,第一行数据就是字典里的key值,从第二行开始一一对应value值
# coding:utf-8
import xlrd
class ExcelUtil():
def __init__(self, Path, sName):
self.data = xlrd.open_workbook(Path)
self.table = self.data.sheet_by_name(sName)
# 获取第一行作为key值
self.keys = self.table.row_values(0)
# 获取总行数
self.rowNum = self.table.nrows
# 获取总列数
self.colNum = self.table.ncols
def dict_data(self):
if self.rowNum <= 1:
print("总行数小于1")
else:
r = []
j=1
for i in range(self.rowNum-1):
s = {}
# 从第二行取对应values值
values = self.table.row_values(j)
for x in range(self.colNum):
s[self.keys[x]] = values[x]
r.append(s)
j+=1
return r
if __name__ == "__main__":
data = ExcelUtil("D:test.xlsx", "Sheet1")
print data.dict_data()
2.写数据
from openpyxl import load_workbook
"""每次写入都会覆盖之前的内容"""
#加载excel,注意路径要与脚本一致
wb = load_workbook('test.xlsx')
#激活excel表
sheet = wb.active
#向excel中写入表头
sheet['a1'] = '序号'
sheet['b1'] = '姓名'
sheet['c1'] = '价格'
#向excel中写入对应的value
sheet.cell(row=2, column=1).value = '1'
sheet.cell(row=2, column=2).value = 'test1'
sheet.cell(row=2, column=3).value = 100
sheet.cell(row=3, column=1).value = '2'
sheet.cell(row=3, column=2).value = 'test2'
sheet.cell(row=3, column=3).value = 200
wb.save('test.xlsx')
或者
wb = load_workbook('test.xlsx')
# 激活excel表
sheet = wb.active
Data = [{"id": 1, "name": "test1", "price": 100}, {"id": 2, "name": "test2", "price": 200},
{"id": 3, "name": "test3", "price": 300}, ]
sheet.append(['序号', '姓名', '价格']) # 添加表头
[sheet.append([i["id"], i["name"], i["price"]]) for i in Data]
wb.save('test.xlsx')
标签:web,sheet,--,self,excel,table,data,row From: https://www.cnblogs.com/SparkProgram/p/17401972.html