The .NET version of this page lists the C# classes of a business layer: a DataLayer class that builds customer, order and product objects, reads them from a database, a DataSet, XML and JSON files, and a CommonUtilities class that resolves template and report paths and applies the licence. In Python, the business layer is the set of data files the examples read, and a few lines that load each of them. This page describes those files, as they are in the sample set, and how a page loads each one.
The data is that of Harbor Lane Provisions, the specialty-food wholesaler of the business case.
Common Utilities
Template and Report Locations
The examples need no path helpers. Each example runs in a folder that holds only its input files, reads them by their bare file names ("customers.json", "shop-customer-orders.docx") and writes its report next to them ("shop-customer-orders-report.docx"). The tabs beside each example link the files it reads.
Applying Product License
The examples do not set a licence themselves. Set the GROUPDOCS_LIC_PATH environment variable to the path or URL of your licence file, and GroupDocs.Assembly for Python via .NET applies it at the first call into the engine. To apply a licence in code instead, call License().set_license(...) with a path or an open file before the first report:
Where the .NET examples build Customer, Order, Product and Service objects, the Python examples pass dicts and lists. A dict’s keys are the member names the template reads, so <<[c.CustomerName]>> and <<[o.Product.ProductName]>> read a dict exactly as they read a C# object. Python’s types decide what the template sees: a str is a string, an int a 64-bit integer, a float a double, a datetime a date-time value. JSON has no date type, so a page whose template reads a date turns the date strings into datetime objects while loading the file, with an object_hook.
Getting Customers’ Details
customers.json holds the four customers of the shop, each with its orders:
str in the file ("2015-01-14T00:00:00"), datetime once loaded
2015-01-14
Order[].Barcode
str
HLP-10001
Order[].Services
list of dicts with a ServiceName (str)
Next-day delivery
Quayside Bistro, Lantern Street Café, Saltmarsh Deli and Pier Nine Kitchen placed ten orders between them, all dated 2015. A page whose template reads the dates loads the file as follows; the other pages call json.load(f) alone.
importjsonfromdatetimeimportdatetimefromgroupdocs.assemblyimportDataSourceInfo,DocumentAssemblerdefparse_dates(item):# JSON has no dates: turn the order dates into datetime objects for the templateforkeyin("OrderDate","ShippingDate"):ifkeyinitem:item[key]=datetime.strptime(item[key],"%Y-%m-%dT%H:%M:%S")returnitemwithopen("customers.json",encoding="utf-8")asf:customers=json.load(f,object_hook=parse_dates)assembler=DocumentAssembler()assembler.assemble_document("shop-customer-orders.docx","shop-customer-orders-report.docx",DataSourceInfo(customers,"customers"))
orders.json holds the same ten orders as one flat list, where the .NET GetOrdersData method walks the customers’ orders. Each order carries the members above and a Customer dict (the customer’s members without its orders), so a template can read <<[o.Customer.CustomerName]>> or group the orders with GroupBy(o => o.Customer): two orders of one customer hold equal customer dicts, and the engine compares them by value.
importjsonfromdatetimeimportdatetimefromgroupdocs.assemblyimportDataSourceInfo,DocumentAssemblerdefparse_dates(item):# JSON has no dates: turn the order dates into datetime objects for the templateforkeyin("OrderDate","ShippingDate"):ifkeyinitem:item[key]=datetime.strptime(item[key],"%Y-%m-%dT%H:%M:%S")returnitemwithopen("orders.json",encoding="utf-8")asf:orders=json.load(f,object_hook=parse_dates)assembler=DocumentAssembler()assembler.assemble_document("shop-order-list.docx","shop-order-list-report.docx",DataSourceInfo(orders,"orders"))
products.json is the list of the ten products the orders name, each with ProductName, UnitInStock, Discount and ProductPrice. It holds no dates, so json.load is all it takes.
customer.json is one customer, Quayside Bistro, with its three orders: the first item of customers.json, where the .NET GetCustomerData method takes the first customer of the list. The pages pass it under the name customer.
The .NET examples read the same customers, orders and products from an SQL Server database through LINQ to SQL entities. In Python, read the rows with your database driver and turn each row into a dict: the column names become the members the template reads. The following example loads the products into an in-memory SQLite database and reads them back with sqlite3, whose sqlite3.Row objects convert to dicts. See Generate Document from Database for more.
importjsonimportsqlite3fromgroupdocs.assemblyimportDataSourceInfo,DocumentAssembler# A database with the products, as a shop would keep themconnection=sqlite3.connect(":memory:")connection.execute("CREATE TABLE Products (ProductName TEXT, UnitInStock INTEGER, Discount INTEGER, ProductPrice TEXT)")withopen("products.json",encoding="utf-8")asf:forpinjson.load(f):connection.execute("INSERT INTO Products VALUES (?, ?, ?, ?)",(p["ProductName"],p["UnitInStock"],p["Discount"],p["ProductPrice"]))# Each row becomes a dict whose keys are the column namesconnection.row_factory=sqlite3.Rowproducts=[dict(row)forrowinconnection.execute("SELECT * FROM Products ORDER BY ProductName")]connection.close()assembler=DocumentAssembler()assembler.assemble_document("shop-product-list.docx","shop-product-list-from-database.docx",DataSourceInfo(products,"products"))
ADO.NET DataSet, DataTable and DataRow objects have no Python form. Related tables are nested dicts and lists in Python, as in customers.json, or a DocumentTableSet when the tables come from a document (see Use Tables of Documents as Data Sources below).
XML and JSON Data Sources
managers.json and managers.xml hold the same data: Harbor Lane’s three account managers, Mei Tanaka, Daniel Reyes and Sofia Marino, each with a Name and the supply contracts they signed, each Contract with a Client (its Name) and a Price. Nine contracts in all, worth 430000.
Five files hold the account managers’ figures as tables of Word, PowerPoint and Excel documents. A page loads one table as a DocumentTable, or all the tables of a document as a DocumentTableSet.
File
What it holds
contracts.xlsx
One worksheet, Contracts: Client, Manager and Price of the nine contracts.
managers.docx
Two tables: an unused one, then the top 5 managers with their total contract price (Manager, Total Contract Price).
managers.pptx
The same two tables on one slide.
related-tables.xlsx
Three worksheets linked by ID: MANAGER (ID, NAME), CLIENT (ID, NAME) and CONTRACT (ID, CLIENT_ID, MANAGER_ID, PRICE).
multiple-tables.docx
Three tables: Planet/Number, the staff (First Name, Last Name) and Harbor Lane’s suppliers (Name, Address).
Use Spreadsheets as Data Sources
The first worksheet of contracts.xlsx, with column names from its first row. A space in a column name becomes an underscore, and a column whose cells all hold numbers is a float column.
fromgroupdocs.assembly.dataimportDocumentTable,DocumentTableOptionsoptions=DocumentTableOptions()options.first_row_contains_column_names=True# Use data of the first worksheettable=DocumentTable("contracts.xlsx",0,options)# Check column count, names, and typesprint("Columns:",table.columns.count)forcolumnintable.columns:print(column.name,column.type.__name__)
The following sample file is used in this example: contracts.xlsx
Use Tables of Word Processing Documents as Data Sources
The second table of managers.docx, with its first row read as data and only the first four rows loaded. The columns then take default names.
fromgroupdocs.assembly.dataimportDocumentTable,DocumentTableOptions# Do not extract column names from the first row, so that the first row is treated as a data row.# Limit the largest row index, so that only the first four data rows are loaded.options=DocumentTableOptions()options.max_row_index=3# Use data of the second table in the documenttable=DocumentTable("managers.docx",1,options)# Default column names are used, because the names are not extracted from the first rowprint("Columns:",table.columns.count)print([column.nameforcolumnintable.columns])
The following sample file is used in this example: managers.docx
Use Tables of Presentation Documents as Data Sources
The same for the table on the slide of managers.pptx:
fromgroupdocs.assembly.dataimportDocumentTable,DocumentTableOptions# Do not extract column names from the first row, so that the first row is treated as a data row.# Limit the largest row index, so that only the first four data rows are loaded.options=DocumentTableOptions()options.max_row_index=3# Use data of the second table in the presentationtable=DocumentTable("managers.pptx",1,options)# Default column names are used, because the names are not extracted from the first rowprint("Columns:",table.columns.count)print([column.nameforcolumnintable.columns])
The following sample file is used in this example: managers.pptx
A DocumentTableSet loads every table of a document at once. A handler sets the load options of each table, and relations link the tables of related-tables.xlsx by their ID columns, so a template can walk from a manager to its contracts and from a contract to its client.
fromgroupdocs.assembly.dataimportDocumentTableOptions,DocumentTableSetdefload_table(args):# The first row of every worksheet holds its column namesoptions=DocumentTableOptions()options.first_row_contains_column_names=Trueargs.options=optionstables=DocumentTableSet("related-tables.xlsx",load_table)tables.relations.add(tables.tables["CLIENT"].columns["ID"],tables.tables["CONTRACT"].columns["CLIENT_ID"])tables.relations.add(tables.tables["MANAGER"].columns["ID"],tables.tables["CONTRACT"].columns["MANAGER_ID"])fortableintables.tables:print(table.name,[column.nameforcolumnintable.columns])
The tables of a Word document have no names of their own, so a DocumentTableSet names them Table1, Table2 and so on:
fromgroupdocs.assembly.dataimportDocumentTableOptions,DocumentTableSetdefload_table(args):# The first row of every table holds its column namesoptions=DocumentTableOptions()options.first_row_contains_column_names=Trueargs.options=optionstables=DocumentTableSet("multiple-tables.docx",load_table)fortableintables.tables:print(table.name,[column.nameforcolumnintable.columns])
Each customer’s Photo names a picture of the sample set: quayside-bistro.png, lantern-street-cafe.png, saltmarsh-deli.png and pier-nine-kitchen.png, 240 by 240 pixels. An image tag such as <<image [Photo]>> loads the file by that name from the folder the example runs in, so the image pages list the pictures among their input files. logo.png is the Harbor Lane Provisions logo.
The .NET Classes
The complete DataLayer and CommonUtilities classes of the .NET examples have no Python counterpart: every page loads its data with the few lines shown above. The DynamicEntity class, which serves data lazily through indexers, is discussed in Working with Lazy And Recursive Access of Data.
Was this page helpful?
Any additional feedback you'd like to share with us?
Please tell us how we can improve this page.
Thank you for your feedback!
We value your opinion. Your feedback will help us improve our documentation.
Ask AI
Ask anything about this page — the answer is based on its content.
Searching the docs and writing an answer…
Something went wrong while getting an answer. Please try again in a moment.