1.首先将数据写入到excel
import csv
import xlwt
def write_data_to_excel(unique_data_list): """unique_data_list:[{},{},{}]""" header_list = [] for heades in list(unique_data_list[0].keys()): header_list.append(heades) with open('test.csv','a',newline='',encoding='utf-8') as f: writer = csv.DictWriter(f, fieldnames=header_list) writer.writeheader() for temp_dict in unique_data_list: temp_list = [] temp_list.append(temp_dict) # writer.writerows(unique_data_list) writer.writerows(temp_list)
2.创建excel各种样式
#1 创建单元格背景颜色样式(颜色可自行查阅对应的数字编号,下面字体同理)
def create_bg_style(): #创建一个样式对象,初始化样式 style style = xlwt.XFStyle() #设置背景颜色 pattern = xlwt.Pattern() pattern.pattern = xlwt.Pattern.SOLID_PATTERN pattern.pattern_fore_colour = 4 style.pattern = pattern # 将背景颜色加到表格样式中 return style
#2 设置字体样式
def create_font_style(): """设置字体样式""" style = xlwt.XFStyle() font = xlwt.Font() font.name = 'Calibri' #设置字体 font.colour_index = 4 #设置字体颜色 font.height = 400 #字体大小 font.bold = True #字体是否为粗体 font.italic = True #字体是否为斜体 font.underline = True #字体是否有下滑线 style.font = font return style
#3 设置水平位置
def set_position(): """设置位置""" style = xlwt.XFStyle() alignment = xlwt.Alignment() alignment.horz = 1 #设置水平位置,0是左对齐,1是居中,2是右对齐 #设置自动换行 alignment.wrap = 1 style.alignment = alignment
#4 设置边框
def set_border(): """设置边框""" style = xlwt.XFStyle() borders = xlwt.Borders() #DASHED虚线, NO_LINE没有,THIN实线 borders.left = xlwt.Borders.DASHED borders.right = xlwt.Borders.DASHED borders.top = xlwt.Borders.DASHED borders.bottom = xlwt.Borders.DASHED borders.left_colour = 1 borders.right_colour = 1 borders.top_colour = 1 borders.bottom_colour = 1 style.borders = borders