Python如何读取和写入Excel数据

发布时间:2021-09-04 15:58:27 作者:chen
来源:亿速云 阅读:704

这篇文章主要介绍“Python如何读取和写入Excel数据”,在日常操作中,相信很多人在Python如何读取和写入Excel数据问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”Python如何读取和写入Excel数据”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

使用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')

到此,关于“Python如何读取和写入Excel数据”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!

推荐阅读:
  1. python读取和写入excel表格的方法
  2. 详解Python如何实现读取并写入Excel文件

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

python

上一篇:Java语言中的四种引用区别

下一篇:MySQL中的隐藏列的具体查看方法

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》