代码
import xlrd
import xlwt
from xlutils.copy import copy
def Excel_a(path,loc,data,sheet_num=0):
"追加方式写入Excel文件,data是二维列表,loc是左上角单元格位置【比如B5】仅支持26列"
try:
path = path.replace('\\','/')
workbook = xlrd.open_workbook(path) # 打开工作簿
print("成功读取文件!")
except:
raise err("加载文件失败!|"+path)
s_row = loc[1:]#行
s_row = int(s_row)-1
s_column = loc[0:1]#列
s_column = ord(s_column)-ord('A')
new_workbook = copy(workbook) # 将xlrd对象拷贝转化为xlwt对象
new_worksheet = new_workbook.get_sheet(sheet_num) # 获取转化后工作簿中的指定表格
for i in range(len(data)):
for j in range(len(data[i])):
new_worksheet.write(i+s_row, j+s_column, data[i][j]) # 追加写入数据,注意是从i+rows_old行开始写入
try:
path = path[:path.index(".")]+"_mod.xls"
new_workbook.save(path)
print("成功修改文件")
except:
raise err("修改文件失败")
class err(Exception):
"自定义异常"
def __init__(self,massage):
self.massage = massage
def __str__(self):
return self.massage
使用
参考资料: https://www.jianshu.com/p/a8391a2b8c6c
关键词: 追加方式写入Excel文件
输入: path, loc, data, sheet_num=0
path:文件路径 loc:开始写入的位置 data:要写入的二维列表 sheet_num:选择表格【0-n】
输出: 修改完成的文件,文件名为path+"_mod.xls"
示例:
Excel.Excel_a("C:\\Users\\Administrator\\Desktop\\情况1\\Case_1_result.xls","A2",data,1)
# 输出文件:C:\\Users\\Administrator\\Desktop\\情况1\\Case_1_result_mod.xls