python学习pythonpython_pycham

Python学习九十一天:Python操作Excel

2019-05-23  本文已影响9人  暖A暖

使用python来操作Excel需要用到xlrd和xlwt这两个库,作用是在python中读取和写入excel数据,使用前需要安装和import导入;

1.Python 读 excel数据

import xlrd
from pprint import pprint
staff_excel = xlrd.open_workbook('./staff.xlsx')
# 获取这个表中,sheet工作簿的名称
print(staff_excel.sheet_names())

# 通过名字拿到对应的工作簿
sheet = staff_excel.sheet_by_name('员工基本信息')

# 显示表格的行数,和列数
print(sheet.nrows)
print(sheet.ncols)

# 读取第二行的所有cell中的内容
print(sheet.row_values(2))


# 获取第2行,第0列的值
print(sheet.cell(2,0).value)
print(sheet.cell_value(2,0))

data_type = sheet.cell(2,2).ctype
print(data_type)
if data_type is 3:
    # 返回一个元组
    # ret = xlrd.xldate_as_tuple(sheet.cell_value(1,2),staff_excel.datemode)
    # 将excel表中时间转换为python中的时间
    ret = xlrd.xldate_as_datetime(sheet.cell_value(1,2), staff_excel.datemode)  
    print(ret.strftime('%Y-%m-%d'))

2.将Excel数据转换为json写入到文件

json_list = []
keys = sheet.row_values(0)
print(keys)
for index_r in range(1,sheet.nrows): # [1,2]
    # 这个字典必须是局部变量
    line = {}
    for index_c in range(sheet.ncols): # [0, 3]
        # 拿到类型
        cell_type = sheet.cell(index_r, index_c).ctype
        # 拿到值
        cell_value = sheet.cell(index_r, index_c).value
        # 如果是时间类型
        if cell_type is 3:
            cell_value = xlrd.xldate_as_datetime(cell_value, staff_excel.datemode).strftime('%Y-%m-%d')
        line[keys[index_c]] = cell_value
    else:
        json_list.append(line)
pprint(json_list, indent=4)
with open('staff.json', 'a+',) as f:
    f.write(json.dumps(json_list, ensure_ascii=False))

3.将json文件重新写入Excel

# 创建一个Excel对象文件
new_staff = xlwt.Workbook()
staff_sheet = new_staff.add_sheet('xkd员工信息')
with open('staff.json') as f:
    # 返回一个列表
    data = json.load(f)
# 获取Excel中的第一行
item = data[0]
# 获取Excel中的值
column_values = []
for item in data:
    column_values.append(item.values())
# 写入第一行
for i,key in enumerate(item.keys()):
    print(key)
    staff_sheet.write(0, i, label=key)
# 写入其他的行
for i,column in enumerate(column_values):
    for j,column_value in enumerate(column):
        staff_sheet.write(i+1, j, label=column_value)
new_staff.save('./new_staff.xls')

参考:https://www.9xkd.com/user/plan-view.html?id=9228840680

上一篇下一篇

猜你喜欢

热点阅读