快速入门

你可以处理这个sheet, bookapp层级:

  • mysheet.render_template(**data):替换占位符在mysheet

  • mybook.render_template(**data):替换所有工作表中的占位符mybook

  • myapp.render_template(template, output, **data):方便的包装器,它会在用值替换占位符之前复制一个模板工作簿。由于这种方法允许你与隐藏的 Excel 实例一起工作,因此它是生产中最常用的方法。

让我们通过一个典型的例子:首先创建以下 Python 脚本report.py:

# report.py
from pathlib import Path

import pandas as pd
import xlwings as xw

# We'll place this file in the same directory as the Excel template
this_dir = Path(__file__).resolve().parent

data = dict(
    title='MyTitle',
    df=pd.DataFrame(data={'one': [1, 2], 'two': [3, 4]})
)

# Change visible=False to run this in a hidden Excel instance
with xw.App(visible=True) as app:
    book = app.render_template(this_dir / 'mytemplate.xlsx',
                               this_dir / 'myreport.xlsx',
                               **data)
    book.to_pdf(this_dir / 'myreport.pdf')

然后创建以下名为的 Excel 文件mytemplate.xlsx:

../../_images/mytemplate.png

运行 Python 脚本(或从 Jupyter notebook 中运行代码):

python report.py

这将复制模板并通过将双大括号中的变量替换为来自 Python 变量的值来生成以下输出:

../../_images/myreport.png

如果你愿意,你也可以创建一个经典的 xlwings 工具来调用此脚本,或者使用像 PySimpleGUI 这样的框架设计一个 GUI 应用程序,并使用冷冻器(例如,PyInstaller)将其转换为可执行文件。然而,这超出了本教程的范围。

注意

默认情况下,如果模板中没有足够的空间容纳你的变量,xlwings Reports 会覆盖现有值。如果你想根据数组的高度动态调整行的位置,请使用框架.

注意

与 xlwings 不同,xlwings Reports 从未写入 pandas 数据框的索引。如果你想在 Excel 中显示索引,请使用df.reset_index(),参见数据框.

另见render_templates (API reference).

渲染工作簿和工作表

有时,渲染单个工作簿或工作表而不是使用myapp.render_template方法是有用的。这是一个存储为的工作簿Book1.xlsx:

../../_images/sheet_rendering1.png

运行以下代码:

import xlwings as xw

book = xw.Book('Book1.xlsx')
sheet = book.sheets['template'].copy(name='report')
sheet.render_template(title='A Demo!', table=[[1, 2], [3, 4]])
book.to_pdf()

首先复制模板工作表,然后填充它:

../../_images/sheet_rendering2.png

另见mysheet.render_template (API reference)mybook.render_template (API reference).

在版本0.22.0中添加。