1. 程式人生 > 其它 >python操作excel檔案

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')