Python:操作 excel -> part1

数据为:

dict_value = 
{'张三-语文': 64, '李四-语文': 70, '王五-语文': 82, '赵六-语文': 8,
'张三-数学': 0, '李四-数学': 64, '王五-数学': 34, '赵六-数学': 4,
'张三-英语': 22, '李四-英语': 84, '王五-英语': 70, '赵六-英语': 16,
'李四-体育': 90, '王五-体育': 78, '赵六-英语': 72}

xlwt 主要是用来写 excel 文件

pip install xlwt

def get_cell(rows, cols, name):
    row = rows.index(name.split("-")[1]) + 1
    col = cols.index(name.split("-")[0]) + 1
    return row, col


import xlwt

list_rows = list()
list_cols = list()
wbk = xlwt.Workbook()

sheet = wbk.add_sheet('Sheet')
for key in dict_value:
    key_product = key.split("-")[0]
    key_people = key.split("-")[1]
    if key_people not in list_rows:
        list_rows.append(key_people)
    if key_product not in list_cols:
        list_cols.append(key_product)

for row in list_rows:
    sheet.write(list_rows.index(row) + 1, 0, row)
for col in list_cols:
    sheet.write(0, list_cols.index(col) + 1, col)

for key in dict_value:
    row, col = get_cell(list_rows, list_cols, key)
    sheet.write(row, col, int(dict_value.get(key)))
wbk.save('test.xls')

此时表数据为:
这里写图片描述

xlrd 可以用来读文件

pip install xlrd

import xlrd

workbook = xlrd.open_workbook(u'test.xls')

sheet_names = workbook.sheet_names()

sheet = workbook.sheet_by_name("Sheet")
rows = sheet.row_values(0, 1)
cols = sheet.col_values(0, 1)
print(rows)
print(cols)
print("--" * 40)
for row in rows:
    print(row)
    for col in cols:
        print(col, sheet.col_values(rows.index(row) + 1, cols.index(col) + 1, cols.index(col) + 2))

输出结果:

['张三', '李四', '王五', '赵六']
['语文', '数学', '英语', '体育']
--------------------------------------------------------------------------------
张三
语文 [64.0]
数学 [0.0]
英语 [22.0]
体育 ['']
李四
语文 [70.0]
数学 [64.0]
英语 [84.0]
体育 [90.0]
王五
语文 [82.0]
数学 [34.0]
英语 [70.0]
体育 [78.0]
赵六
语文 [8.0]
数学 [4.0]
英语 [72.0]
体育 ['']
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值