python读写修改Excel之xlrd&xlwt&xlutils

py读写修改常用的三种方法

  • xlwt:用于写入 Excel 文件
  • xlrd:用于读取 Excel 文件
  • xlutils:用于操作 Excel 文件的实用工具,比如复制、分割、筛选等

0、安装模块

pip3 install xlrd xlwt xlutils

1. 写入excel

git:https://github.com/python-excel/xlwt/tree/master/examples

实现效果

上代码

from datetime import datetime

import xlwt

font0 = xlwt.Font()

# font0.name = 'Times New Roman' # 适用于字母或数字
font0.name = '宋体'  # 适用于中文,适配字体或者不指定字体才能体现出指定的颜色

# font0.colour_index = 1  # 白色
# font0.colour_index = 2  # 红色
# font0.colour_index = 3  # 绿色
# font0.colour_index = 4  # 蓝色
# font0.colour_index = 5  # 黄色
# font0.colour_index = 6  # 紫色
# font0.colour_index = 7  # 青色
# font0.colour_index = 8  # 黑色,比默认加黑,不加粗
font0.colour_index = 4  # 蓝色
font0.bold = True

style0 = xlwt.XFStyle()
style0.font = font0

# 创建样式对象:日期格式
style1 = xlwt.XFStyle()
style1.num_format_str = 'YYYY-MM-DD'

# 创建样式对象:字体居中对齐
style2 = xlwt.XFStyle()
al = xlwt.Alignment()
al.horz = 0x02 # 设置水平居中
al.vert = 0x01 # 设置垂直居中
style2.alignment = al

# 创建样式对象,设置日期格式与字体居中对齐
style3 = xlwt.XFStyle()
style3.num_format_str = 'YYYY-MM-DD'
style3.alignment = al

# 创建样式对象,设置字体居中 且 设置字体颜色
style4 = xlwt.XFStyle()
style4.alignment = al
style4.font = font0

now_time = datetime.now().strftime('%Y-%m-%d %X')
date_time = datetime.now().strftime('%Y-%m-%d')

# 创建表格
wb = xlwt.Workbook()

# 新建一个名为 Score Sheet 的表单页
score_sheet = wb.add_sheet('Score Sheet')

# 新建一个名为 Record Test Sheet 的表单页
record_test_sheet = wb.add_sheet('Record Test Sheet')

# 1、写入 Score Sheet 表单
# 设置 表头, 第一个参数是行,第二个参数是列
score_sheet.write(0, 0, '时间', style2)
score_sheet.write(0, 1, '班级', style2)
score_sheet.write(0, 2, '姓名', style2)
score_sheet.write(0, 3, '语文', style2)
score_sheet.write(0, 4, '数学', style2)
score_sheet.write(0, 5, '英语', style2)
score_sheet.write(0, 6, '理综', style2)
score_sheet.write(0, 7, '总分', style4)

# 按照位置添加数据
score_sheet.write(1, 0, datetime.now(), style3)
score_sheet.write(1, 1, '高三三班', style2)
score_sheet.write(1, 2, '桑岩', style2)
score_sheet.write(1, 3, 132, style2)
score_sheet.write(1, 4, 150, style2)
score_sheet.write(1, 5, 140, style2)
score_sheet.write(1, 6, 290, style2)
score_sheet.write(1, 7, xlwt.Formula("D2+E2+F2+G2"), style2)

score_sheet.write(2, 0, datetime.now(), style3)
score_sheet.write(2, 1, '高三三班', style2)
score_sheet.write(2, 2, '项天骐', style2)
score_sheet.write(2, 3, 140, style2)
score_sheet.write(2, 4, 150, style2)
score_sheet.write(2, 5, 132, style2)
score_sheet.write(2, 6, 280, style2)
score_sheet.write(2, 7, xlwt.Formula("D3+E3+F3+G3"), style2)

score_sheet.write(3, 0, datetime.now(), style3)
score_sheet.write(3, 1, '高三三班', style2)
score_sheet.write(3, 2, '向淮南', style2)
score_sheet.write(3, 3, 135, style2)
score_sheet.write(3, 4, 150, style2)
score_sheet.write(3, 5, 145, style2)
score_sheet.write(3, 6, 270, style2)
score_sheet.write(3, 7, xlwt.Formula("D4+E4+F4+G4"), style2)

# 2、写入 Record Test Sheet 表单
record_test_sheet.write(0, 0, '时间')
record_test_sheet.write(0, 1, '学科', style1)
record_test_sheet.write(0, 2, '成绩', style1)
record_test_sheet.write(1, 0, datetime.now(), style1)
record_test_sheet.write(1, 1, '语文', style2)
record_test_sheet.write(1, 2, 80)
record_test_sheet.write(2, 0, datetime.now(), style3)
record_test_sheet.write(2, 1, '数学', style2)
record_test_sheet.write(2, 2, 99)
record_test_sheet.write(3, 0, now_time, style2)
record_test_sheet.write(3, 1, '英语', style2)
record_test_sheet.write(3, 2, 98)

# 保存表格,这里应该是覆盖写,注意每次都是覆盖所有表单内容,建议每次生成的表单加上时间版本区分
# wb.save('example.xls')
wb.save('example-{0}.xls'.format(date_time))

2、读 Excel

git:https://github.com/python-excel/xlrd

实现效果,读取sheet 表单内容

数值 类型 说明
0 empty
1 string 字符串
2 number 数字
3 date 日期
4 boole 布尔值
5 error 错误

代码

import xlrd

# 打开 xls文件
wb = xlrd.open_workbook("example-2021-03-09.xls")

# 获取并打印 sheet 数量
print("sheet 数量:", wb.nsheets)     # sheet 数量: 2

# 获取并打印 sheet 名称
print("sheet 名称:", wb.sheet_names())  # sheet 名称: ['Score Sheet', 'Record Test Sheet']

# 根据 sheet 索引获取内容
sh1 = wb.sheet_by_index(0)
# 或者
# 也可根据 sheet 名称获取内容
# sh = wb.sheet_by_name('Score Sheet')

# 获取并打印该 sheet 行数和列数
print(u"sheet: %s表单 共 %d 行 %d 列" % (sh1.name, sh1.nrows, sh1.ncols))   # sheet: Score Sheet表单 共 4 行 8 列

# 获取并打印某个单元格的值
print("第一行第二列的值为:", sh1.cell_value(0, 1))    # 第一行第二列的值为: 班级

# 获取整行或整列的值
row_info = sh1.row_values(0)  # 获取第一行内容
col_info = sh1.col_values(1)  # 获取第二列内容

# 打印获取的行列值
print("第一行的值为:", row_info)   # 第一行的值为: ['时间', '班级', '姓名', '语文', '数学', '英语', '理综', '总分']
print("第二列的值为:", col_info)   # 第二列的值为: ['班级', '高三三班', '高三三班', '高三三班']

# 获取单元格内容的数据类型,注意这里的值 另有含义
print("第二行第一列的【值类型】为:", sh1.cell(1, 0).ctype)   # 第二行第一列的【值类型】为: 3

# 遍历所有表单内容
for sh in wb.sheets():
  for r in range(sh.nrows):

    # 输出指定行内容,这里包含原有类型指定,不能直接获取到指定列的值
    row_val_list = sh.row(r)
    print(row_val_list)
    # [text:'时间', text:'班级', text:'姓名', text:'语文', text:'数学', text:'英语', text:'理综', text:'总分']

    # 遍历行内,输出当前行内的所有列值
    col_val_list = [col_val.value for col_val in row_val_list]
    print(col_val_list)

3、修改 Excel

修改 Excel 是通过 xlutils 库的 copy 方法将原来的 Excel 整个复制一份,然后再做修改操作,最后再保存

修改前

修改后

上代码

import xlrd
from xlutils.copy import copy

# 打开 excel 文件, 带格式复制
read_book = xlrd.open_workbook("example-2021-03-09.xls", formatting_info=True)

# 复制一份
wb = copy(read_book)

# 选取第一个表单
sh1 = wb.get_sheet(0)

# 在第五行新增写入数据
sh1.write(4, 0, '2020-12-16')
sh1.write(4, 1, '高三三班')
sh1.write(4, 2, '小鱼仙倌儿')
sh1.write(4, 3, 150)
sh1.write(4, 4, 150)
sh1.write(4, 5, 150)
sh1.write(4, 6, 300)

# 选取第二个表单
sh2 = wb.get_sheet(1)

# 替换总成绩数据
sh2.write(1, 2, 100)

# 保存
wb.save('example-2021-03-09.xls')

注意,复制 xls这里有格式问题

似乎没有任何简单的方法可以保留单元格的格式;它总是被吹走并设置为空白。

https://www.coder.work/article/80896

https://zhuanlan.zhihu.com/p/128674458

附录

参考:http://www.ityouknow.com/python/2019/12/29/python-excel-103.html

官网:http://www.python-excel.org/

到此这篇关于python读写修改Excel之xlrd&xlwt&xlutils的文章就介绍到这了,更多相关python读写修改Excel内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • Python玩转Excel的读写改实例

    摘要: 利用xlrd读取excel 利用xlwt写excel 利用xlutils修改excel 利用xlrd读取excel 先需要在命令行中pip install xlrd:读取xls文件的流程为: 加载文件->选中第几个表格->按先行后列的顺序读 通用demo import xlrd filename = "test.xls" #文件路径 wb = xlrd.open_workbook(filename) #加载这个xls文件 sh = wb.sheet_by_index

  • 使用Python对Excel进行读写操作

    学习Python的过程中,我们会遇到Excel的读写问题.这时,我们可以使用xlwt模块将数据写入Excel表格中,使用xlrd模块从Excel中读取数据.下面我们介绍如何实现使用Python对Excel进行读写操作. Python版:3.5.2 通过pip安装xlwt,xlrd这两个模块,如果没有安装的话: pip install xlwt pip install xlrd 一.对Excel文件进行写入操作: # -*- conding:utf-8 -*- __author__ = 'mayi

  • Python读写Excel文件的实例

    最近由于经常要用到Excel,需要根据Excel表格中的内容对一些apk进行处理,手动处理很麻烦,于是决定写脚本来处理.首先贴出网上找来的读写Excel的脚本. 1.读取Excel(需要安装xlrd): #-*- coding: utf8 -*- import xlrd fname = "reflect.xls" bk = xlrd.open_workbook(fname) shxrange = range(bk.nsheets) try: sh = bk.sheet_by_name(

  • python实现excel读写数据

    本文实例为大家分享了python操作EXCEL的实例源码,供大家参考,具体内容如下 读EXCEL的操作:把excel的数据存储为字典类型 #coding=utf8 #导入读excel的操作库 import xlrd class GenExceptData(object): def __init__(self): try: self.dataDic={} #打开工作薄 self.wkbook= xlrd.open_workbook("Requirement.xls") #获取工作表&qu

  • Python3使用pandas模块读写excel操作示例

    本文实例讲述了Python3使用pandas模块读写excel操作.分享给大家供大家参考,具体如下: 前言 Python Data Analysis Library 或 pandas 是基于NumPy 的一种工具,该工具是为了解决数据分析任务而创建的.Pandas 纳入了大量库和一些标准的数据模型,提供了高效地操作大型数据集所需的工具,能使我们快速便捷地处理数据.本文介绍如何用pandas读写excel. 1. 读取excel 读取excel主要通过read_excel函数实现,除了pandas

  • 零基础使用Python读写处理Excel表格的方法

    引 由于需要解决大批量Excel处理的事情,与其手工操作还不如写个简单的代码来处理,大致选了一下感觉还是Python最容易操作. 安装库Python环境 首先当然是配环境,不过选Python的一个重要原因就是Mac内是自带Python环境的,不需要额外的配置环境,省下了一笔工作,如果你用的是Windows系统,那就还需要配置一下Python的环境了,我Mac的Python版本是2.7. 第三方库 Python自己是不支持直接操作Excel的,但是Python强大之处就在于有大量好用的第三方库,这

  • Python使用Pandas读写Excel实例解析

    这篇文章主要介绍了Python使用Pandas读写Excel实例解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 Pandas是python的一个数据分析包,纳入了大量库和一些标准的数据模型,提供了高效地操作大型数据集所需的工具. Pandas提供了大量能使我们快速便捷地处理数据的函数和方法. Pandas官方文档:https://pandas.pydata.org/pandas-docs/stable/ Pandas中文文档:https:/

  • Python读写Excel文件方法介绍

    一.读取excel 这里介绍一个不错的包xlrs,可以工作在任何平台.这也就意味着你可以在Linux下读取Excel文件. 首先,打开workbook: 复制代码 代码如下: import xlrd wb = xlrd.open_workbook('myworkbook.xls') 检查表单名字: 复制代码 代码如下: wb.sheet_names() 得到第一张表单,两种方式:索引和名字 复制代码 代码如下: sh = wb.sheet_by_index(0) sh = wb.sheet_by

  • python使用xlrd模块读写Excel文件的方法

    本文实例讲述了python使用xlrd模块读写Excel文件的方法.分享给大家供大家参考.具体如下: 一.安装xlrd模块 到python官网下载http://pypi.python.org/pypi/xlrd模块安装,前提是已经安装了python 环境. 二.使用介绍 1.导入模块 复制代码 代码如下: import xlrd 2.打开Excel文件读取数据 复制代码 代码如下: data = xlrd.open_workbook('excelFile.xls') 3.使用技巧 获取一个工作表

  • 用python读写excel的方法

    本文实例讲述了用python读写excel的方法.分享给大家供大家参考.具体如下: 最近需要从多个excel表里面用各种方式整理一些数据,虽然说原来用过java做这类事情,但是由于最近在学python,所以当然就决定用python尝试一下了.发现python果然简洁很多.这里简单记录一下.(由于是用到什么学什么,所以不算太深入,高手勿喷,欢迎指导) 一.读excel表 读excel要用到xlrd模块,官网安装(http://pypi.python.org/pypi/xlrd).然后就可以跟着里面

随机推荐