Αναφορά αρχείων OfficeΕξαρτάται από τον τρόπο ρύθμισης του Ivy
Ivy’s Python sandbox environment has python-docx, python-pptx, openpyxl and XlsxWriter, so the assistant, and code you run, can make real Word, PowerPoint and Excel files. Every example on this page runs in that environment, in order, in one folder.
A file written under /workspace is saved to the space after the step. Saving to the path a file already has makes a new version of it, which is how an edit should be saved: make a copy only when the person asks for one. Keep drafts and checks in /tmp, which is never saved.
Start from a template
A space keeps its templates in a top-level templates folder: templates/report.docx, templates/deck.pptx, templates/budget.xlsx or any other name. When one fits, start from a copy of it rather than from an empty file, so the result has the organisation’s fonts, colours, slide masters and page setup. Find them in /workspace/.ivy/index.tsv; one that isn’t copied in yet needs load_into_sandbox. With several that fit, pick by name or ask. Never change the template itself unless asked.
import shutil
from pathlib import Path
Path("Reports").mkdir(exist_ok=True)
shutil.copy("templates/report.docx", "Reports/Q3 report.docx")
Word documents
Use the styles the document or template defines (Title, Heading 1, List Bullet, Table Grid and its own) instead of setting fonts run by run. A style name the template doesn’t define raises KeyError; list them with [s.name for s in doc.styles].
import matplotlib.pyplot as plt
from docx import Document
from docx.shared import Cm
plt.figure(figsize=(6, 3))
plt.bar(["Q1", "Q2", "Q3"], [120, 135, 150])
plt.savefig("/tmp/revenue.png", dpi=200, bbox_inches="tight")
doc = Document("Reports/Q3 report.docx")
doc.add_heading("Q3 report", level=0)
doc.add_heading("Summary", level=1)
doc.add_paragraph("Revenue grew for the third quarter in a row.")
doc.add_paragraph("New customers in two regions", style="List Bullet")
table = doc.add_table(rows=1, cols=2, style="Table Grid")
table.rows[0].cells[0].text, table.rows[0].cells[1].text = "Quarter", "Revenue"
for quarter, revenue in [("Q1", "120"), ("Q2", "135"), ("Q3", "150")]:
row = table.add_row().cells
row[0].text, row[1].text = quarter, revenue
doc.add_picture("/tmp/revenue.png", width=Cm(15))
doc.add_page_break()
doc.save("Reports/Q3 report.docx")
To edit, open the file, change what was asked and save it to the same path. Replace text inside runs so their formatting stays; paragraph.text = … drops the paragraph’s runs and their formatting. A phrase split across runs takes the formatting of the run it starts in, and the text around it keeps its own.
from docx import Document
def replace(paragraph, old, new):
runs = paragraph.runs
at = "".join(run.text for run in runs).find(old)
if at < 0:
return
end = at + len(old)
position = 0
for run in runs:
start, stop = position, position + len(run.text)
position = stop
if stop <= at or start >= end:
continue
kept_before = run.text[: max(at - start, 0)]
kept_after = run.text[end - start :] if stop > end else ""
run.text = kept_before + (new if start <= at else "") + kept_after
doc = Document("Reports/Q3 report.docx")
for paragraph in doc.paragraphs:
replace(paragraph, "third quarter", "third consecutive quarter")
summary = next(p for p in doc.paragraphs if p.text.startswith("Revenue grew"))
summary.insert_paragraph_before("Prepared for the board.")
doc.save("Reports/Q3 report.docx")
Word keeps tracked changes (w:ins, w:del) and comment anchors inside paragraphs, and python-docx doesn’t see them: rewriting such a paragraph loses a change or leaves a comment pointing nowhere. Before editing, look for them. Leave those paragraphs alone, or ask the person to accept or reject the changes in Word first. New comments are safe to add.
from docx import Document
doc = Document("Reports/Q3 report.docx")
body = doc.element.body
print("tracked changes:", len(body.xpath(".//w:ins | .//w:del")))
print("comments:", len(body.xpath(".//w:commentRangeStart")))
target = next(p for p in doc.paragraphs if p.text.startswith("Revenue grew"))
doc.add_comment(target.runs, text="Figures from the finance export.", author="Ivy", initials="IV")
doc.save("Reports/Q3 report.docx")
PowerPoint decks
Add slides from the template’s layouts, by name, and fill their predefined text boxes, so each slide follows the slide master. Don’t change the slide size or the master of a deck that has one. List the layouts with [layout.name for layout in prs.slide_layouts] and a layout’s boxes with [(p.placeholder_format.idx, p.name) for p in layout.placeholders].
from pptx import Presentation
from pptx.chart.data import CategoryChartData
from pptx.enum.chart import XL_CHART_TYPE, XL_LEGEND_POSITION
from pptx.util import Cm, Pt
prs = Presentation("templates/deck.pptx")
layouts = prs.slide_layouts
title = prs.slides.add_slide(layouts.get_by_name("Title Slide"))
title.shapes.title.text = "Q3 board update"
title.placeholders[1].text = "Finance, October"
points = prs.slides.add_slide(layouts.get_by_name("Title and Content"))
points.shapes.title.text = "Highlights"
body = points.placeholders[1].text_frame
body.text = "Revenue up 11%"
detail = body.add_paragraph()
detail.text = "Two new regions"
detail.level = 1
points.notes_slide.notes_text_frame.text = "Mention the hiring plan."
numbers = prs.slides.add_slide(layouts.get_by_name("Title Only"))
numbers.shapes.title.text = "Revenue by quarter"
data = CategoryChartData()
data.categories = ["Q1", "Q2", "Q3"]
data.add_series("Revenue", (120, 135, 150))
margin = Cm(1)
half = (prs.slide_width - 3 * margin) // 2
chart = numbers.shapes.add_chart(
XL_CHART_TYPE.COLUMN_CLUSTERED, margin, Cm(4), half, Cm(9), data
).chart
chart.has_legend = True
chart.legend.position = XL_LEGEND_POSITION.BOTTOM
chart.legend.include_in_layout = False
table = numbers.shapes.add_table(4, 2, 2 * margin + half, Cm(4), half, Cm(6)).table
for r, (quarter, revenue) in enumerate([("Quarter", "Revenue"), ("Q1", "120"), ("Q2", "135"), ("Q3", "150")]):
table.cell(r, 0).text, table.cell(r, 1).text = quarter, revenue
table.cell(0, 0).text_frame.paragraphs[0].runs[0].font.size = Pt(14)
picture = prs.slides.add_slide(layouts.get_by_name("Title Only"))
picture.shapes.title.text = "Trend"
picture.shapes.add_picture("/tmp/revenue.png", margin, Cm(4), width=prs.slide_width - 2 * margin)
prs.save("Reports/Q3 board update.pptx")
A chart made with add_chart is a native PowerPoint chart: people can edit its data in PowerPoint. A picture of a chart can’t be edited; use one only for what PowerPoint can’t draw.
To edit a deck, change the text of its runs as for Word, and save it to the same path. python-pptx has no call to delete or reorder slides; both work on the slide list:
from pptx import Presentation
prs = Presentation("Reports/Q3 board update.pptx")
for slide in prs.slides:
for shape in slide.shapes:
if shape.has_text_frame:
for paragraph in shape.text_frame.paragraphs:
for run in paragraph.runs:
run.text = run.text.replace("October", "November")
slide_ids = prs.slides._sldIdLst
trend = list(slide_ids)[3]
prs.part.drop_rel(trend.rId)
slide_ids.remove(trend)
highlights = list(slide_ids)[1]
slide_ids.remove(highlights)
slide_ids.append(highlights)
prs.save("Reports/Q3 board update.pptx")
A predefined box left empty shows its prompt text (“Click to add text”) in PowerPoint’s editor: fill it or remove it with placeholder._element.getparent().remove(placeholder._element).
Excel workbooks
Make a new workbook with XlsxWriter, and edit an existing one with openpyxl. XlsxWriter can’t open a file; openpyxl keeps an existing workbook’s styles, formulas, tables, charts and images, but drops shapes, text boxes, slicers and macros (.xlsm): say so before editing a workbook that has them.
Formulas or values. Write a formula where the person will change inputs and expect totals to follow (budgets, models); write the value where the sheet is a report of fixed numbers. Neither library calculates formulas. Ivy’s viewer, previews and the assistant’s reading show a formula’s saved result, and a formula saved without one shows as =SUM(…) until the file is opened and saved in Excel. So, in XlsxWriter, pass the result you computed in Python as the formula’s value. Write formulas in English with commas (=SUM(B2:B4)), as Excel stores them whatever its language.
import xlsxwriter
rows = [("Rent", 1200), ("Software", 340), ("Travel", 410)]
workbook = xlsxwriter.Workbook("Reports/Q3 budget.xlsx")
sheet = workbook.add_worksheet("Budget")
money = workbook.add_format({"num_format": "#,##0"})
bold_money = workbook.add_format({"num_format": "#,##0", "bold": True})
sheet.add_table(0, 0, len(rows), 1, {
"name": "Costs",
"columns": [{"header": "Item"}, {"header": "Cost", "format": money}],
"data": [list(r) for r in rows],
})
total_row = len(rows) + 1
sheet.write(total_row, 0, "Total")
sheet.write_formula(total_row, 1, f"=SUM(B2:B{total_row})", bold_money, sum(c for _, c in rows))
sheet.set_column("A:A", 18)
sheet.set_column("B:B", 12)
sheet.freeze_panes(1, 0)
chart = workbook.add_chart({"type": "column"})
chart.add_series({
"name": "Cost",
"categories": ["Budget", 1, 0, len(rows), 0],
"values": ["Budget", 1, 1, len(rows), 1],
})
chart.set_legend({"none": True})
sheet.insert_chart("D2", chart)
workbook.close()
To edit, open the workbook with its formulas (the default) and save it to the same path. Never save a workbook opened with data_only=True: that reads the saved results, and saving writes them over the formulas. openpyxl saves every formula without its result, so after an edit, say that totals show as formulas in Ivy until the file is next saved in Excel.
from openpyxl import load_workbook
from openpyxl.chart import BarChart, Reference
workbook = load_workbook("Reports/Q3 budget.xlsx")
sheet = workbook["Budget"]
total_row = sheet.max_row
sheet.insert_rows(total_row)
sheet.cell(total_row, 1, "Training")
sheet.cell(total_row, 2, 250).number_format = "#,##0"
sheet.cell(total_row + 1, 2, f"=SUM(B2:B{total_row})")
costs = sheet.tables["Costs"]
costs.ref = costs.autoFilter.ref = f"A1:B{total_row}"
for existing in sheet._charts:
for series in existing.series:
series.cat.strRef.f = f"Budget!$A$2:$A${total_row}"
series.val.numRef.f = f"Budget!$B$2:$B${total_row}"
chart = BarChart()
chart.title = "Costs"
chart.add_data(Reference(sheet, min_col=2, min_row=1, max_row=total_row), titles_from_data=True)
chart.set_categories(Reference(sheet, min_col=1, min_row=2, max_row=total_row))
sheet.add_chart(chart, "D20")
workbook.save("Reports/Q3 budget.xlsx")
Dates are datetime values with a number_format such as "yyyy-mm-dd"; percentages are fractions with "0%". Inserting rows with openpyxl doesn’t move the formulas, merged cells, charts or table ranges that refer to them: update each, as the example does for the total, the table and the chart.
Check the result
Before saying a file is ready, open it again with its library and look at what it holds: the headings, the slide titles and notes, the sheets and a few cells. A file that doesn’t open, or that holds less than expected, is fixed before it’s reported. Where soffice (LibreOffice or Collabora’s office core) is installed, in an environment of your organisation’s, convert a copy to PDF in /tmp as well: that catches files Office would have to repair.
import glob
import shutil
import subprocess
import tempfile
from docx import Document
from openpyxl import load_workbook
from pptx import Presentation
for path in sorted(glob.glob("Reports/*")):
if path.endswith(".docx"):
doc = Document(path)
print(path, [p.text for p in doc.paragraphs if p.style.name.startswith(("Heading", "Title"))])
elif path.endswith(".pptx"):
prs = Presentation(path)
for number, slide in enumerate(prs.slides, start=1):
notes = slide.notes_slide.notes_text_frame.text if slide.has_notes_slide else ""
print(path, number, slide.shapes.title.text if slide.shapes.title else "", notes)
elif path.endswith(".xlsx"):
workbook = load_workbook(path)
print(path, {s.title: s.dimensions for s in workbook.worksheets})
if shutil.which("soffice"):
out = tempfile.mkdtemp()
subprocess.run(
["soffice", "--headless", "--convert-to", "pdf", "--outdir", out, path],
check=True, timeout=120,
)
Then link each file in the reply with its ivy-file: link, which the step’s result lists under <saved_files>.