python操作excel文件
前提是要有 采集阈值报表.xls 这个文件,并且不是打开状态,要不会报错
def set_style(name, height): """ 设置单元格样式 """ style = xlwt.XFStyle() # 初始化样式 font = xlwt.Font() # 为样式创建字体 font.name = name # 'Times New Roman' font.bold = False font.color_index = 4 font.height = height style.font = font return style def write_xls(): """写入Excel""" data_post_list = data_post_list() #此处为数据 格式为列表包字典 [{'a':1,'b':2,'c':3,'d':4,'e':5,'f':6,'g':7},{'a':1,'b':2,'c':3,'d':4,'e':5,'f':6,'g':7}] # 创建工作簿 f = xlwt.Workbook() # 创建sheet1 sheet1 = f.add_sheet(u'sheet1', cell_overwrite_ok=True) # 创建sheet # 表格样式 default = set_style('Times New Roman', 240) # 生成表头 row0 = [u'设备名称', u'设备IP', u'监测点', u'采集频率', u'当前值', u'最新采集时间', u'危险阈值', u'故障阈值'] for i in range(0, len(row0)): sheet1.write(0, i, row0[i], default) sheet1.col(i).width = 256 * 25 # 设置列宽 # 写Excel row_index = 1 for i in data_post_list: col_index = 0 for j in i: sheet1.write(row_index, col_index, i[j], default) col_index = col_index + 1 row_index = row_index + 1 # 保存文件 t = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time())) savepath = r'/data/app/DOIM/Server/webexpress/hdoc/tmp/' + t + '采集阈值报表.xls' f.save(savepath) return mx_success('请求成功!写入Excel成功!文件:', t + '采集阈值报表.xls')