How it works...

If you take a look at the product administration list page in the browser, you will see a new action called Export XLSX, along with the default Delete selected Products action, as shown in the following screenshot:

To create the spreadsheet export response, we use the openpyxl Python module to create an OpenOffice XML file compatible with Excel and other spreadsheet software.

First, a workbook is created, and the active worksheet is selected, for which we set the title to Products. Because there are common styles that we will want to use throughout the worksheet, these are set up as named styles, so that they can be applied by name to each cell, as appropriate. For the id and price headers, the base Headline 1 style is copied, aligned right, and stored under a new name, Number Headline 1. These styles, the column headings, and the column widths are stored as Config objects, and a column_config dictionary maps column letter keys to the objects. This is then iterated over, to set up the headers and column widths.

The value given for the column width can be an integer or decimal, and it indicates the quantity of the widest number in the normal style's font that should fit on a single line, adjusted to account for the spacing and gridlines of each cell.

We use the append() method of the sheet to add the content for each of the selected products in  QuerySet, ordered by ID, including the URL of the first photo for the product, when photos are available. The product data is then individually styled by iterating over each of the cells in the just-added row, once again referring to  column_config to apply styles consistently.

By default, admin actions do something with  QuerySet, and redirect the administrator back to the change list page. However, for more complex actions like these, HttpResponse can be returned. The export_xlsx() function saves a virtual copy of the workbook to HttpResponse, with the content type and character set appropriate to the Office Open XML (OOXML) spreadsheet. Using the Content-Disposition header, we set the response to be downloadable as products.xlsx. The resulting sheet can be opened in Excel, and will look similar to the following:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.134.118.95