Package: xml2xlsx
Creatingxlsxfiles fromxmltemplate usingopenpyxl.TargetThis project is intended to createxlsxfiles fromxmlapi toopenpyxl, supposedly generated by other tamplate engines (i.e. django,
jinja).This is a merely an xml parser translating mostly linearly to worksheet, rows
and finally cells of the Excel workbook.ExampleAn xml file like this one<workbook><worksheettitle="test"><row><cell>This</cell><cell>is</cell><cell>aTEST</cell></row><row><cell>Nice,isn'tit?</cell></row></worksheet></workbook>can be parsed to create a neat Excel workbook with two rows of data in one
worksheet. Parsing can be done using command line (provided that you have your
system paths set correctly:xml2xlsx<input.xml>output.xmlor as a library callfromxml2xlsximportxml2xlsxtemplate='<sheet title="test"></sheet>'f=open('test.xlsx','wb')f.write(xml2xlsx(template))f.close()This is mainly intended (and was developed for this purpose) to parse files
generated by other templating engines, like django template system. One can
generate an excel workbook from template like this:{%foreinlist%}<row><cell>{{e.name}}</cell></row>{%endfor%}FeaturesBasic features of the library include creating multiple, named sheets within one
workbook and creating rows of cells in these sheets. However, there are more
possibiliteis to create complex excel based reports.Cell typeEach cell can be specified to use one of the types:string (default)numberdateType is defined intypecell attribute. The cell value is converted
appropriately to the type specified. If you insert a number in the cell value
and do not specifytype="number"attribute, you will find Excel complaining
about storing nubers as text.Since there are more date formats than countries, you have to be aware of
current locale. The simplest way to be i18n compatible is to specify date format
indate-fmtattribute and pass compatible (possibily non localized) date
in the cell value, as in the following example...<row><celltype="date"date-fmt="%Y-%m-%d">2016-10-01</cell></row><row><celltype="date"date-fmt="%d.%m.%Y">01.10.2016</cell></row>...Generated excel file will have two rows with the same date (1st of October 2016)
with date formatted according to Excel defaults (and current locale).WarningExcel tries to be very smart and converts date-like text to date format.
Please usetype="date"anddate-fmtattribute always if you pass
dates to cells.ColumnsColumns can be tackled only in a limited way, i.e. only column widths can be
changed. Column properties are defined incolumnstag as one or more child
of thesheettag. It is possible to specify a range of columns usingstartandendatrributes. For example:...<sheettitle="test"><columnsstart="A"end="D"width="123"/><row><cell>Test</cell></row></sheet>...Formulasxml2xlscan effectively create cells with formulas in them. The only
limitation (as withopenpyxl) is using English names of the functions.For example:...<row><cell>=SUM(A1:A5)</cell></row>...Cell referencingThe parser can store positions of the cell in a dictionary-like structure. It
then can be referenced to create complex formulas. Each value of the cell is
preprocessed using string format with stored values. This means that these
values can be referenced using{and}brackets.Current row and columnThere are two basic values that can always be used, i.e.rowandcolwhich return current row number and column name.<workbook><sheet><row><cell>{col}{row}</cell></row></sheet></workbook>...would create a workbook with a text “A1” included in theA1cell of the
worksheet. Using template languages, you can create more complicated
constructs, like (using django template system):...{%foreinlist%}<row><celltype="date"date-fmt="%Y-%m-%d">{{e|date:"Y-m-d"}}</cell><cell>=TEXT(A{row},"ddd")</cell></row>{%endfor%}...would create a list of rows with a date in the first column and weekday names
for these dates in the second column (providedlistcontext variable
contains a list of dates).Specified cellIt is also possible to store cell possible to store names of specified cells in
a pseudo-variable (as in a dictionary). One has to useref-idattribute of
thecelltag and then reuse the value of this attribute in the remainder of
the xml input. This is very useful in formulas. A simple example would be
referencing another cell in a formula like this:...<row><cellref-id="mycell">Thisisjustatest</cell></row>...<row><cell>={mycell}</cell></row>...which would create an excel formula referencing a cell with “this is just a
test” text, whatever this cell address was.WarningUsing the same identifier inref-idattribute for two different cellsoverwritesthe cell reference, i.e. the last cell in the xml template
would be referenced.A more complex example using django template engine to create summaries can
look like this:...{%foreinlist%}<row><cellref-id="{% if forloop.first %}start{% elsif forloop.last %}end{% endif %}">{{e}}</cell></row>{%endfor%}<row><cell>Summary</cell><cell>=SUM({start}:{end})</cell></row>...List of cellsReferencing a single cell can be harsh when dealing with complex reports.
Especially when creating summaries of irregularly sheet-distributed data.xml2xlsxcan append a cell to a variable-like list, as inref-idattribute, to reuse it as a comma concatenated value. Instead ofref-id, one
has to useref-appendattribute.This is a simple example to demonstrate the feature:...
<sheet>
    <row>
        <cell ref-append="mylist">1</cell>
        <cell ref-append="mylist">2</cell>
    </row>
    <row><cell ref-append="mylist">3</cell></row>
    <row><cell>=SUM({mylist})</cell></row>
</sheet>This will generate an Excel sheet withA3cell containing formula to sumA1,B1andA2cells (=SUM(A1, B1, A2)).Referencing limitationsIt is perfectly possible to reference a cell in another sheet with bothref-idandref-append. However, there is a limitation to that. Sincexml2xslxis a linear parser, you are only allowed to reference already
parsed elements. This means, you have to create sheets in a proper order (sheets
referencing other sheets must be createdafterreferenced cells are parsed).The following examplewill not work:...<sheettitle="one"><row><cell>{mycell}</cell></row></sheet><sheettitle="two"><row><cellref-id="mycell">XYZ</cell></row></sheet>...However, it is possible to make this exmaple workandretain the same
worksheet ordering usingindexattribute:...<sheettitle="two"><row><cellref-id="mycell">XYZ</cell></row></sheet><sheettitle="one"index="0"><row><cell>{mycell}</cell></row></sheet>...Cell formattingThe cell format can be specified using various attributes of the cell tag. Only
font formatting can be specifed for now.Font formatA font format is specified in infontattribute. It is a semicolon separated
dict like list of font formats as specified infontclass ofopenpyxllibrary.An example to create a cell with bold 10px font:...
<cell font="bold: True; size: 10px;">Cell formatted</cell>
...Planned featuresHere is the (probably incomplete) wishlist for the projectGlobal font and cell stylesRow widths and column heightsHorizontal and vertical cell mergingXML validation with XSD to quickly raise an error if parsing wrong xmlXML Schema ReferenceParsed xml should be enclosed in aworkbooktag. Eachworkbooktag can
have multiplesheet. The hierarchy continues torowandcelltags.Here is a complete list of available attributes of these tags.workbookNo attributes for now.sheetAttribute:titleUsage:Specifies the worksheet titleAttribute:indexUsage:Specifies the worksheet index. This is relative to already created indexes.
An index of 0 creates sheet at the beginning of the sheets collection.rowNo attributes for nowcolumnsAttribute:startUsage:Specifies the starting column for the column range (in a letter format).Attribute:endUsage:Specifies the ending column for the column range (in a letter format).Default:Same asstartattributeAttribute:widthUsage:Specifies the width for all columns in the range. It is in px format.cellAttribute:typeUsage:Specifies the resulting type of the excel cell.Type:One ofunicode,date,numberDefault:unicodeAttribute:date-fmtUsage:Specifies the format of the date parsed as instrftime and strptimefunctions ofdatetimestandard python library.Remarks:Parsed only iftype="date".Attribute:fontUsage:Sepcifies font formatting for a single cell.Type:List of semicolon separated dict-like values in form ofkey: value; key: value;Remarks:Key and values are arguments ofFontclas inopenpyxl.Release History0.2Added documentationAdded cell referencing with inter-sheet possibilityChangedsheettitle attribute fromnametotitleAdded possibility to set index for a sheet