目录
预览效果:
首先我们的excel是我们在前一节
【Python】生成Excel 写入内容-操作Excel、Word、CSV(1)(保姆级图文注释+测试代码+api例程)
文章中用代码生成的
现在我们修改excel
API说明:
打开我们 python写入的excel.xls 文件
- 参数1 excel文件对象名字
- 参数2 excel文件名字
复制一份新的excel数据
- 参数1 新复制得到的excel文件对象名字
- 参数2 原来的excel文件对象名字
替换单元格的值和在sheet里面写入内容是一样的
- 参数1 表单页对象名
- 参数2 行(从0开始计算)
- 参数3 列(从0开始计算)
- 参数4 写入单元格的内容
如下图,写入的姓名单元格A1坐标在Python中是0,0
sheet_1.write(0, 0, ‘姓名’)
基本例程
修改 Excel 是通过 xlutils 库的 copy 方法将原来的 Excel 整个复制一份,然后再做修改操作,最后再保存。
# @Time : 2022/1/11 16:12
# @Author : 南黎
# @FileName: 1.3修改 excel.py
import xlrd
from xlutils.copy import copy
# 打开 excel 文件
read_excel = xlrd.open_workbook("python写入excel.xls")
# 复制一份
my_xls = copy(read_excel)
# 选取第一个表单
sheet_1 = my_xls.get_sheet(0)
# 在第五行新增写入数据
sheet_1.write(4, 0, '丁')
sheet_1.write(4, 1, '数据结构')
sheet_1.write(4, 2, '路由与交换技术')
sheet_1.write(4, 3, 60)
# 选取第二个表单
sheet_1 = my_xls.get_sheet(1)
# 替换总成绩数据
sheet_1.write(1, 0, 362)
# 功能说明:获取文件名称的函数 根据获取的当前时间确定格式化的文件名
# 返回值:str的文件名
import time
def get_data_name():
data_time=time.strftime('%m-%d-%H-%M-%S', time.localtime())#格式化获取的当地时间
data_name=data_time
return data_name+"-"
# 保存
my_xls.save(get_data_name()+'python写入excel.xls')#前面加上了时间前缀用以区分新老文件
总结
大家喜欢的话,给个👍,点个关注!继续跟大家分享敲代码过程中遇到的问题!
所有文件已经上传至码云
https://gitee.com/miao-zehao/python_to_-excel-and-word-and-csv/tree/master/