python 读取excel & 往excel中写入内容 [xlrd, xlwt, xlutils]

import xlrd,xlwt
from xlutils.copy import copy

# 只能操作xls格式的(不能直接将xlsx中最后的x去掉来更改格式,可以将xlsx格式的文件另存为xls格式的),不能操作xlsx格式的
# 读取Excel文件内容
path = r"./测试文件.xls"
workBook1 = xlrd.open_workbook(path) #打开excel文件
sheet1 = workBook1.sheet_by_name("1-登录接口") #通过sheet名字获取响应的sheet
v1 = sheet1.cell(1,1).value #获取对应单元格里的数据
print(v1)

# 写入excel : 复制已有的excel
# existing的excel文件
path = r"./test_vic1.xls"
workBook1 = xlrd.open_workbook(path,formatting_info=True) #formatting_info=True 打开时保持原文件格式
book2 = copy(workBook1)     #复制已有的excel文件
sheet2 = book2.get_sheet(1) #通过sheet下标获取对应的sheet,下标从0开始

# 创建新的excel文件
newBook = xlwt.Workbook(encoding = 'utf-8')
# 创建新的sheet
sheet2 = newBook.add_sheet("testSheet")
sheet2.write(3,3,"今天是周三啦啦啦啦啦啦")

# 一定要有“保存" save这步
newBook.save(r"./testExcel_01.xls")
上一篇:python表格操作之xlrd和xlwt的用法


下一篇:使用python写入excel