如何使用Python的Docxtpl创建动态行表格?
Alright, let's walk through how to create tables that automatically expand to match your list data using docxtpl. This is such a common use case, and docxtpl (which leverages Jinja2 under the hood) makes it really straightforward once you nail the template setup.
Step 1: Install docxtpl
First, make sure you have the library installed. Run this in your terminal:
pip install docxtpl
Step 2: Set Up Your Word Template
You'll need a base Word document (let's name it template.docx) to define the table structure. Here's exactly how to configure it:
- Open a new Word doc and insert a table with 3 columns.
- The first row is your static header:
- Cell 1:
Name - Cell 2:
Age - Cell 3:
Job
- Cell 1:
- The second row is your dynamic data row—this is where the loop logic goes:
- In Cell 1: Type
{% for user in user_list %}{{ user.name }} - In Cell 2: Type
{{ user.age }} - In Cell 3: Type
{{ user.job }}{% endfor %}
- In Cell 1: Type
This setup tells docxtpl to repeat the entire second row for every item in your user_list dataset.
Step 3: Write the Python Code
Now let's tie it all together with code that loads the template, passes your data, and generates the final document.
from docxtpl import DocxTemplate # Your sample data (works with any length—n items will create n table rows) user_dict = [ {"name": "Person 1", "age": 25, "job": "Software Engineer"}, {"name": "Person 2", "age": 30, "job": "Data Analyst"}, {"name": "Person 3", "age": 28, "job": "Product Manager"}, {"name": "Person 4", "age": 32, "job": "UX Designer"} ] # Load your template file doc = DocxTemplate("template.docx") # Map your data to the variable name used in the template context = {"user_list": user_dict} # Render the template with your data doc.render(context) # Save the finished document doc.save("dynamic_table_output.docx")
Bonus: Handle Edge Cases
- Empty Data List: If your
user_dictis empty, the table will only show the header. To add a friendly fallback, modify your template like this:{% if user_list %} {% for user in user_list %}{{ user.name }} | {{ user.age }} | {{ user.job }}{% endfor %} {% else %} No users to display | | {% endif %} - Alternating Row Colors: For better readability, use Jinja2's
loopvariable to apply conditional styling (you'll need to define styles in Word first, then reference them):{% for user in user_list %} {% if loop.index % 2 == 0 %} {{ user.name }} {% else %} {{ user.name }} {% endif %} {% endfor %}
That's all there is to it! Run the code, and your output document will have a table with exactly as many rows as items in your list.
内容的提问来源于stack exchange,提问作者Sanju Jayachandran

