做公司项目碰到要读写excel (xslx),暂定要实现的功能如下:
1. 从json文件里解析数据
2.制作excel模板(有三行需要一个个单元格分开制作)
3.复制sheet页
使用的库如下,功能一目了然,不做详解:
import json,openpyxl import shutil,os from openpyxl.styles import Border, Side, Font, GradientFill, Alignment
写Cell(合并)方法如下:
def write_cell(ws,value,cell_range, border=Border(), fill=None, font=None, alignment=None): my_cell = ws[cell_range.split(":")[0]] my_cell.value = value style_range(ws, cell_range, border=border, fill=fill, font=font,alignment=al)
其中style_range ,主要就是写单元格的样式以及合并单元格
def style_range(ws, cell_range, border=Border(), fill=None, font=None, alignment=None): top = Border(top=border.top) left = Border(left=border.left) right = Border(right=border.right) bottom = Border(bottom=border.bottom) first_cell = ws[cell_range.split(":")[0]] if alignment: ws.merge_cells(cell_range) first_cell.alignment = alignment rows = ws[cell_range] if font: first_cell.font = font for cell in rows[0]: cell.border = cell.border + top for cell in rows[-1]: cell.border = cell.border + bottom for row in rows: l = row[0] r = row[-1] l.border = l.border + left r.border = r.border + right if fill: for c in row: c.fill = fill
样式如下:
thin = Side(border_style="thin", color="000000") border = Border(top=thin, left=thin, right=thin, bottom=thin) fill = GradientFill(stop=("D8E4BC", "D8E4BC")) font_b = Font(b=True,