getsavefilename
python编辑已存在的excel坑:BadZipFile:Fileisnotazipfile 背景-原代码如下,期望能⾃动创建excel,并且可以反复调⽤编辑:
import xlwt,os
from openpyxl.styles import Font, colors
class Write_excel(object):
"""修改excel数据"""
def __init__(self, filename):
self.filename = filename
def write(self, row_n, col_n, value):
wb=xlwt.Workbook()
sh=wb.add_sheet('Sheet1',cell_overwrite_ok=True)
red_style = xlwt.easyxf("font:colour_index red;")
green_style = xlwt.easyxf("font:colour_index green;")
# 判断值为错误时添加字体样式
if value in ['FAIL', 'ERROR'] or col_n == 12:
  sh.write(row_n - 1, col_n - 1, value, red_style)
elif value == 'PASS':
  ft = Font(color=colors.GREEN)
  sh.write(row_n - 1, col_n - 1, value, green_style)
else:
sh.write(row_n - 1, col_n - 1, value)
wb.save(self.filename)
if __name__ == "__main__":
wt = Write_excel("test111.xlsx")
wt.write(1, 1, "FAIL")
wt.write(2, 1, "PASS")
逻辑:使⽤xlwt模块创建excel,然后编辑内容,保存。
实际结果:仅保留最后⼀次写⼊结果。前⼀次的写⼊结果未能保存延续下来。
尝试调整⽅案-解决思路:创建excel前加⼊判断sits(file_name),表格已存在时直接打开编辑,不存在时才创建。
def write(i,j,value,filename):
if not ists(filename):
wbk = xlwt.Workbook()
sheet = wbk.add_sheet('sheet 1')
sheet.write(i,j,value)
wbk.save(filename)
else:
wb=load_workbook(filename)
sh =wb['Sheet1']
wb.save(filename)
write(1,1,'test text','test111.xlsx')
write(2,1,'test text','test111.xlsx')
实际结果报错:zipfile.BadZipFile: File is not a zip file,反复尝试过程中发现,我们在代码⾥创建的excel打开显⽰受损⽆法再次编辑,⽽在路径下⼿动创建的test111.xlsx就不会有这个问题。百度了下,搜索内容也不少,估计新⼿⼩⽩都碰到过。
为了能反复编辑已存在的excel⽂件并保存,需要xlwt、xlrd、xlutils组合起来使⽤,代码如下:
import xlwt,os,xlrd
py import copy
class Do_Excel:
def__init__(self,filename,sheetname='Sheet1'):
self.filename=filename
self.sheetname=sheetname
#读取excel,该部分可忽略
def excel_read(self,x, y):
data = xlrd.open_workbook(self.filename)
table = data.sheet_by_name(self.sheetname)
ll(x, y).value
#判断excel⽂件是否存在,不存在则创建,存在则直接打开编辑
def excel_create(self):
if not ists(self.filename):
data = xlwt.Workbook()
table = data.add_sheet(self.sheetname)
table.write(0, 0, 'id')
data.save(self.filename)
#综合xlwt/py,读写excel
  def write(self,i,j,value):
    l_create()
    rb = xlrd.open_workbook(self.filename)
    wb = copy(rb) #管道作⽤,通过get_sheet()获取的sheet有write()⽅法
    ws = wb.get_sheet(0) #1代表是写到第⼏个⼯作表⾥,从0开始算是第⼀个。
    ws.write(i, j, value) wb.save(self.filename)
Do_Excel('test111.xlsx').write(1,1,'sdcds')
Do_Excel('test111.xlsx').write(1,2,'ewewe')
再尝试多次调⽤,就都能写⼊保存成功了。
解决办法⼆:直接使⽤openpyxl的Workbook和load_workbook,简单直接rom openpyxl import Workbook,load_workbook
import os
class Do_Excel:
def__init__(self,filename,sheetname='Sheet1'):
self.filename=filename
self.sheetname=sheetname
def write(self,i,j,value):
if not ists(self.filename):
wb = Workbook()
sh = wb.create_sheet(self.sheetname)
else:
wb = load_workbook(self.filename)
sh = wb[self.sheetname]
wb.save(self.filename)
Do_Excel('test222.xlsx').write(1,1,'sdcds')
Do_Excel('test222.xlsx').write(1,2,'change')
Do_Excel('test222.xlsx').write(3,2,'pass')

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。