Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@kokumura
Last active March 18, 2021 11:33
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kokumura/c44970102e1f33685152 to your computer and use it in GitHub Desktop.
Save kokumura/c44970102e1f33685152 to your computer and use it in GitHub Desktop.
xlsxファイルの各セルにjinja2テンプレートを適用するやつ
#!/usr/bin/env python
# -*- coding:utf8 -*-
import optparse
import sys
from contextlib import closing
import yaml
import jinja2
from openpyxl import load_workbook
def load_param_file(path):
with closing(open(path)) as f:
return yaml.load(f.read().decode('UTF-8'))
def replace_xl_workbook(template_path, dest_path, param):
print template_path, dest_path
wb = load_workbook(template_path)
for ws in wb.worksheets:
for ri, row in enumerate(ws.iter_rows()):
text_cells = list(cell for cell in row if cell.value and isinstance(cell.value, basestring))
for cell in text_cells:
cell.value = jinja2.Template(cell.value).render(param)
wb.save(dest_path)
def main(cmd_args):
print cmd_args
source_path = cmd_args.pop(0)
dest_path = cmd_args.pop(0)
param = dict()
for item in cmd_args:
param.update(load_param_file(item))
replace_xl_workbook(source_path, dest_path, param)
if __name__ == '__main__':
usage = """\
usage: %prog source.xlsx dest.xlsx [param_files ...]
"""
main(sys.argv[1:])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment