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:

We use the openpyxl Python module to create an OpenOffice XML file that's 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. 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.

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 for 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, 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 so that it can be downloaded as a products.xlsx file. The resulting sheet can be opened in Open Office 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.22.100.180