目录

上一个主题

1.5. 案例:根据XLSX生成HTML

下一个主题

1.7. 案例:生成统计表


1.6. 案例:使用电子表格生成章节结构

场景说明

根据电子表格内容生成Jupyter章节的结构。

解决思路

解决方法

>>> from pprint import pprint
>>> import openpyxl
>>> wb = openpyxl.load_workbook('contents.xlsx')
>>>
>>> sheet = wb.active
>>> # print(sheet.title)
>>>
>>> cnt_arr = []
>>> the_key = None
>>>
>>> sub_arr = []
>>> the_dic = {
>>>
>>> }
>>>
>>> tmpl = open('book_tmpl.md').read()
>>> for i in range(1, sheet.max_row + 1):
>>>     the_val = sheet.cell(row=i, column=1).value
>>>     if the_val:
>>>         pass
>>>     else:
>>>         continue
>>>
>>>     if the_val.startswith(' '):
>>>         sub_arr.append(the_val.strip())
>>>         pass
>>>     else:
>>>         the_key = the_val
>>>
>>>         the_dic['subs'] = sub_arr
>>>         cnt_arr.append(the_dic)
>>>
>>>         the_dic = {
>>>             'title': the_key
>>>         }
>>>
>>>         sub_arr = []
>>>
>>> the_dic['subs'] = sub_arr
>>> cnt_arr.append(the_dic)
>>> import os
>>> import sys
>>>
>>> outdir = 'xx_book'
>>> if os.path.exists(outdir):pass
>>> else: os.mkdir(outdir)
>>>
>>> chidx = 1
>>> for cnt in cnt_arr:
>>>     the_dirit = cnt.get('title')
>>>     if the_dirit:
>>>         the_dirit = the_dirit.strip()
>>>         the_dir = '{}/xx_ch{}0_{}'.format(outdir, str(chidx).zfill(2), the_dirit)
>>>     else:
>>>         continue
>>>     sub_files = cnt['subs']
>>>     if os.path.exists(the_dir):
>>>         pass
>>>     else:
>>>         os.mkdir(the_dir)
>>>     secindx = 1
>>>
>>>     with open( os.path.join(the_dir, 'chapter.md'), 'w') as fo:
>>>         fo.write(
>>>             tmpl.replace('xxxx',
>>>                          the_dirit)
>>>         )
>>>
>>>     for wfile in sub_files:
>>>         the_file = os.path.join(
>>>             the_dir, 'sec{}_{}.md'.format(
>>>                 secindx, wfile
>>>             )
>>>         )
>>>         with open(the_file, 'w') as fo:
>>>             fo.write(
>>>                 tmpl.replace('xxxx',
>>>                             wfile )
>>>             )
>>>         secindx = secindx + 1
>>>
>>>     chidx = chidx + 1

总结