鏈接地址:https://www.cnblogs.com/iamjianghao/p/10826297.html
# coding:utf-8 import xlrd from xlutils.copy import copy def fix_excel(index, name, infos): # 打開想要更改的excel文件,保留原格式 old_excel = xlrd.open_workbook('app/templates/xxx信息表.xls', formatting_info=True) # 將操作文件對象拷貝,變成可寫的workbook對象 new_excel = copy(old_excel) ws_info_map = {} for i in range(1, 13): if i == 7: continue if i > 7: ws_info_map[i] = infos[i - 2] continue ws_info_map[i] = infos[i - 1] # 獲得第一個sheet的對象,就是excel表中的sheet0,sheet1... ws = new_excel.get_sheet(int(index)) # 設置單元格的邊框,上下左右都是實線 borders = xlwt.Borders() borders.top = xlwt.Borders.THIN borders.bottom = xlwt.Borders.THIN borders.right = xlwt.Borders.THIN borders.left = xlwt.Borders.THIN # 設置單元格樣式 style = xlwt.XFStyle() # 將邊框屬性賦值給單元格樣式 style.borders = borders # 寫入數據 可以可以,就是這個模板了 for index, value in ws_info_map.items(): # 寫入單元格數據的時候,調用單元格的樣式設置 ws.write(index, 2, value, style=style) # 另存為excel文件,並將文件命名 new_excel.save(''.join(['./', name, '信息表', '.xls']))