├── .editorconfig ├── .flake8 ├── .gitignore ├── .isort.cfg ├── .travis.yml ├── CHANGELOG ├── LICENSE ├── MANIFEST.in ├── README.rst ├── VERSION ├── excel_response ├── __init__.py ├── response.py └── views.py ├── runtests.py ├── setup.py ├── testapp ├── __init__.py ├── apps.py ├── migrations │ ├── 0001_initial.py │ └── __init__.py ├── models.py ├── settings.py ├── tests.py ├── urls.py └── views.py └── tox.ini /.editorconfig: -------------------------------------------------------------------------------- 1 | # http://editorconfig.org 2 | 3 | root = true 4 | 5 | [*] 6 | indent_style = space 7 | indent_size = 4 8 | insert_final_newline = true 9 | trim_trailing_whitespace = true 10 | end_of_line = lf 11 | charset = utf-8 12 | tab_width = 4 13 | # Width of Github's online editor/diff display 14 | max_line_length = 119 15 | 16 | # Use 2 spaces for the HTML files 17 | [*.html] 18 | indent_size = 2 19 | 20 | # The JSON files contain newlines inconsistently 21 | [*.json] 22 | indent_size = 2 23 | insert_final_newline = ignore 24 | 25 | # Minified JavaScript files shouldn't be changed 26 | [**.min.js] 27 | indent_style = ignore 28 | insert_final_newline = ignore 29 | 30 | # Makefiles always use tabs for indentation 31 | [Makefile] 32 | indent_style = tab 33 | 34 | # Batch files use tabs for indentation 35 | [*.bat] 36 | indent_style = tab 37 | 38 | [*.md] 39 | trim_trailing_whitespace = false 40 | -------------------------------------------------------------------------------- /.flake8: -------------------------------------------------------------------------------- 1 | [flake8] 2 | max-line-length=119 3 | exclude=.eggs,.tox,migrations 4 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | env/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | 28 | # PyInstaller 29 | # Usually these files are written by a python script from a template 30 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 31 | *.manifest 32 | *.spec 33 | 34 | # Installer logs 35 | pip-log.txt 36 | pip-delete-this-directory.txt 37 | 38 | # Unit test / coverage reports 39 | htmlcov/ 40 | .tox/ 41 | .coverage 42 | .coverage.* 43 | .cache 44 | nosetests.xml 45 | coverage.xml 46 | *,cover 47 | .hypothesis/ 48 | 49 | # Translations 50 | *.mo 51 | *.pot 52 | 53 | # Django stuff: 54 | *.log 55 | local_settings.py 56 | 57 | # Flask stuff: 58 | instance/ 59 | .webassets-cache 60 | 61 | # Scrapy stuff: 62 | .scrapy 63 | 64 | # Sphinx documentation 65 | docs/_build/ 66 | 67 | # PyBuilder 68 | target/ 69 | 70 | # Jupyter Notebook 71 | .ipynb_checkpoints 72 | 73 | # pyenv 74 | .python-version 75 | 76 | # celery beat schedule file 77 | celerybeat-schedule 78 | 79 | # SageMath parsed files 80 | *.sage.py 81 | 82 | # dotenv 83 | .env 84 | 85 | # virtualenv 86 | .venv 87 | venv/ 88 | ENV/ 89 | 90 | # Spyder project settings 91 | .spyderproject 92 | .spyproject 93 | 94 | # Rope project settings 95 | .ropeproject 96 | 97 | # mkdocs documentation 98 | /site 99 | 100 | # PyCharm/IntelliJ 101 | .idea/ 102 | -------------------------------------------------------------------------------- /.isort.cfg: -------------------------------------------------------------------------------- 1 | [settings] 2 | skip=.tox,migrations,docs 3 | atomic=true 4 | multi_line_output=5 5 | known_standard_library= 6 | known_third_party=django,openpyxl,six 7 | known_first_party=excel_response 8 | line_length=119 9 | not_skip=__init__.py 10 | lines_after_imports=2 11 | default_section=THIRDPARTY 12 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | sudo: false 2 | language: python 3 | cache: pip 4 | python: 5 | - 2.7 6 | - 3.4 7 | - 3.5 8 | - 3.6 9 | env: 10 | - DJANGO=1.8 11 | - DJANGO=1.9 12 | - DJANGO=1.10 13 | - DJANGO=1.11 14 | - DJANGO=2.0 15 | matrix: 16 | exclude: 17 | - python: 2.7 18 | env: DJANGO=2.0 19 | - python: 3.6 20 | env: DJANGO=1.8 21 | - python: 3.6 22 | env: DJANGO=1.9 23 | - python: 3.6 24 | env: DJANGO=1.10 25 | fast_finish: true 26 | include: 27 | - python: 3.6 28 | env: TOXENV=flake8 29 | install: pip install tox-travis codecov 30 | script: tox 31 | after_success: coverage combine && codecov 32 | branches: 33 | only: 34 | - master 35 | - "/^v?\\d+\\.\\d+(\\.\\d+)?(-\\S*)?$/" 36 | deploy: 37 | provider: pypi 38 | user: jwilhelm 39 | password: 40 | secure: bd/EAzypVoySzjSdaXjIiF95LXOVM2mKn7F42K2WKCxFOpgVXPTmAErE2LigHzWxebfuX6+TZvw3ETp/6H5WiVmUBh1en0+osYvTvFPXZ7e1uLreNf9rKhxpUNHXrHgc9b8OB0vqEPNYt5QNuHGb2qItvzkGlemodwIejx1J5J+WHItBeKec1PEvGaYLWbQkiT64tNNv9t0fjro4T681WxPGb9wHhN5tTqPP/zWfY+CHF3YvVP0LAwGsooNed/tqD22if+/M9n9oy6zGlxXhVo+ehEPkAP7ZirY3eGHJ8d9vZU3X2C6OV9Yo6m+rm8xPhfb8qhTKEv+6ua8di9wN4lLAIRfoXuLa89fva0LTCT0w8LdDMVS2bUvlinCnPTfCkrnJQoIicYAlOHnA+TLsBZsxdGSS2H/2iH+RXOVej5gEO3Uu+7L16EhPIlM7GcZAWLfl+NwSs7lAx07Tl0hQtl4bQuOGGGKQSYZEfAOEjbEOdR77IDV3PS/wB54Ms4EK7Km9jTXx7IUkOsLoCIVnd6GH66lxSwg2cjXc9oXyZeFY7Z/e3c1L2BFq3hZ+Zb2G+LOdSxxlmSBZLGt6hwItRDmiJzmD39IB4YfIO1tCvzEV85FVC4eECXQyWhOObDN3UpE8p+i6oU9HqshpiBGEu3+QRrwGUNRKCnwOUuCVe/Y= 41 | on: 42 | tags: true 43 | python: 3.6 44 | condition: "$TOXENV = flake8" 45 | distributions: sdist bdist_wheel 46 | repo: tarkatronic/django-excel-response 47 | -------------------------------------------------------------------------------- /CHANGELOG: -------------------------------------------------------------------------------- 1 | Version 2.0.5 - Mon 27, 2020 2 | - #29 - Fix file extension. Append file extension to the filename (@rakeshmohan46) 3 | 4 | Version 2.0.4 - Fri Feb 07, 2020 5 | - #25 - Fix Chrome multiple-headers bug for filenames containing commas (@broxeph) 6 | 7 | Version 2.0.3 - Fri Jan 26, 2017 8 | - Bugfix for #18 - OpenPyXL breaking change (Thanks to @ojhilt and @bertramr) 9 | 10 | Version 2.0.2 - Sat Dec 09, 2017 11 | - Bugfix for #14 - IndexError on empty queryset or list 12 | 13 | Version 2.0.1 - Sun May 14, 2017 14 | - Bugfix for streaming content 15 | - Bugfix for .values() queries with Django >= 1.9 16 | 17 | Version 2.0.0 - Mon May 01, 2017 18 | - Full rewrite from the ground up using openpyxl 19 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include *.txt 2 | include *.rst 3 | include CHANGELOG 4 | include LICENSE 5 | include VERSION 6 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | .. image:: http://unmaintained.tech/badge.svg 2 | :target: http://unmaintained.tech 3 | :alt: No Maintenance Intended 4 | 5 | ===================== 6 | django-excel-response 7 | ===================== 8 | .. image:: https://img.shields.io/pypi/v/django-excel-response.svg 9 | :target: https://pypi.python.org/pypi/django-excel-response 10 | :alt: Latest Version 11 | 12 | .. image:: https://travis-ci.org/tarkatronic/django-excel-response.svg?branch=master 13 | :target: https://travis-ci.org/tarkatronic/django-excel-response 14 | :alt: Test/build status 15 | 16 | .. image:: https://codecov.io/gh/tarkatronic/django-excel-response/branch/master/graph/badge.svg 17 | :target: https://codecov.io/gh/tarkatronic/django-excel-response 18 | :alt: Code coverage 19 | 20 | 21 | A subclass of HttpResponse which will transform a QuerySet, 22 | or sequence of sequences, into either an Excel spreadsheet or 23 | CSV file formatted for Excel, depending on the amount of data. 24 | 25 | Installation 26 | ============ 27 | 28 | :: 29 | 30 | pip install django-excel-response 31 | 32 | Provided Classes 33 | ================ 34 | 35 | * ``excel_response.response.ExcelResponse`` 36 | 37 | Accepted arguments: 38 | 39 | * ``data`` - A queryset or list of lists from which to construct the output 40 | * ``output_filename`` - The filename which should be suggested in the http response, 41 | minus the file extension (**default: excel_data**) 42 | * ``worksheet_name`` - The name of the worksheet inside the spreadsheet into which 43 | the data will be inserted (**default: None**) 44 | * ``force_csv`` - A boolean stating whether to force CSV output (**default: False**) 45 | * ``header_font`` - The font to be applied to the header row of the spreadsheet; 46 | must be an instance of ``openpyxl.styles.Font`` (**default: None**) 47 | * ``data_font`` - The font to be applied to all data cells in the spreadsheet; 48 | must be an instance of ``openpyxl.styles.Font`` (**default: None**) 49 | 50 | * ``excel_response.views.ExcelMixin`` 51 | * ``excel_response.views.ExcelView`` 52 | 53 | Examples 54 | ======== 55 | 56 | Function-based views 57 | -------------------- 58 | 59 | You can construct your data from a queryset. 60 | 61 | .. code-block:: python 62 | 63 | from excel_response import ExcelResponse 64 | 65 | 66 | def excelview(request): 67 | objs = SomeModel.objects.all() 68 | return ExcelResponse(objs) 69 | 70 | 71 | Or you can construct your data manually. 72 | 73 | .. code-block:: python 74 | 75 | from excel_response import ExcelResponse 76 | 77 | 78 | def excelview(request): 79 | data = [ 80 | ['Column 1', 'Column 2'], 81 | [1,2] 82 | [23,67] 83 | ] 84 | return ExcelResponse(data, 'my_data') 85 | 86 | Class-based views 87 | ----------------- 88 | 89 | These are as simple as import and go! 90 | 91 | .. code-block:: python 92 | 93 | from excel_response import ExcelView 94 | 95 | 96 | class ModelExportView(ExcelView): 97 | model = SomeModel 98 | -------------------------------------------------------------------------------- /VERSION: -------------------------------------------------------------------------------- 1 | 2.0.5 2 | -------------------------------------------------------------------------------- /excel_response/__init__.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import 2 | 3 | from .response import ExcelResponse 4 | from .views import ExcelMixin, ExcelView 5 | 6 | 7 | __all__ = ['ExcelMixin', 'ExcelResponse', 'ExcelView'] 8 | -------------------------------------------------------------------------------- /excel_response/response.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import, unicode_literals 2 | 3 | import csv 4 | 5 | import django 6 | import six 7 | from django.http.response import HttpResponse 8 | from openpyxl import Workbook 9 | from openpyxl.writer.excel import save_virtual_workbook 10 | from openpyxl.writer.write_only import WriteOnlyCell 11 | 12 | 13 | if django.VERSION >= (1, 9): 14 | from django.db.models.query import QuerySet 15 | else: 16 | from django.db.models.query import QuerySet, ValuesQuerySet 17 | 18 | 19 | ROW_LIMIT = 1048576 20 | COL_LIMIT = 16384 21 | 22 | 23 | class ExcelResponse(HttpResponse): 24 | """ 25 | This class provides an HTTP Response in the form of an Excel spreadsheet, or CSV file. 26 | """ 27 | 28 | def __init__(self, data, output_filename='excel_data', worksheet_name=None, force_csv=False, header_font=None, 29 | data_font=None, guess_types=True, *args, **kwargs): 30 | # We do not initialize this with streaming_content, as that gets generated when needed 31 | self.output_filename = output_filename 32 | self.worksheet_name = worksheet_name or 'Sheet 1' 33 | self.header_font = header_font 34 | self.data_font = data_font 35 | self.force_csv = force_csv 36 | self.guess_types = guess_types 37 | super(ExcelResponse, self).__init__(data, *args, **kwargs) 38 | 39 | @property 40 | def content(self): 41 | return b''.join(self._container) 42 | 43 | @content.setter 44 | def content(self, value): 45 | workbook = None 46 | if not bool(value) or not len(value): # Short-circuit to protect against empty querysets/empty lists/None, etc 47 | self._container = [] 48 | return 49 | elif isinstance(value, list): 50 | workbook = self._serialize_list(value) 51 | elif isinstance(value, QuerySet): 52 | workbook = self._serialize_queryset(value) 53 | if django.VERSION < (1, 9): 54 | if isinstance(value, ValuesQuerySet): 55 | workbook = self._serialize_values_queryset(value) 56 | if workbook is None: 57 | raise ValueError('ExcelResponse accepts the following data types: list, dict, QuerySet, ValuesQuerySet') 58 | 59 | if self.force_csv: 60 | self['Content-Type'] = 'text/csv; charset=utf8' 61 | self['Content-Disposition'] = 'attachment;filename="{}.csv"'.format(self.output_filename) 62 | workbook.seek(0) 63 | workbook = self.make_bytes(workbook.getvalue()) 64 | else: 65 | self['Content-Type'] = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 66 | self['Content-Disposition'] = 'attachment; filename="{}.xlsx"'.format(self.output_filename) 67 | workbook = save_virtual_workbook(workbook) 68 | self._container = [self.make_bytes(workbook)] 69 | 70 | def _serialize_list(self, data): 71 | if isinstance(data[0], dict): # If we're dealing with a list of dictionaries, generate the headers 72 | headers = [key for key in data[0]] 73 | else: 74 | headers = data[0] 75 | if len(data) > ROW_LIMIT or len(headers) > COL_LIMIT or self.force_csv: 76 | self.force_csv = True 77 | workbook = six.StringIO() 78 | csvwriter = csv.writer(workbook, dialect='excel') 79 | append = getattr(csvwriter, 'writerow') 80 | write_header = append 81 | else: 82 | workbook = Workbook(write_only=True) 83 | workbook.guess_types = self.guess_types 84 | worksheet = workbook.create_sheet(title=self.worksheet_name) 85 | 86 | # Define custom functions for appending so that we can handle any formatting 87 | def append(data): 88 | return self._append_excel_row(worksheet, data, header=False) 89 | 90 | def write_header(data): 91 | return self._append_excel_row(worksheet, data, header=True) 92 | 93 | if isinstance(data[0], dict): 94 | append(headers) 95 | for index, row in enumerate(data): 96 | if isinstance(row, dict): 97 | write_header([row.get(col, None) for col in headers]) 98 | else: 99 | if index > 0: 100 | append(row) 101 | else: 102 | write_header(row) 103 | return workbook 104 | 105 | def _serialize_queryset(self, data): 106 | if isinstance(data[0], dict): # .values() returns a list of dicts 107 | return self._serialize_list(list(data)) 108 | else: 109 | return self._serialize_list(list(data.values())) 110 | 111 | def _serialize_values_queryset(self, data): 112 | return self._serialize_list(list(data)) 113 | 114 | def _append_excel_row(self, worksheet, data, header=False): 115 | if header: 116 | font = self.header_font 117 | else: 118 | font = self.data_font 119 | 120 | if not font: 121 | row = data 122 | else: 123 | row = [] 124 | for cell in data: 125 | cell = WriteOnlyCell(worksheet, cell) 126 | cell.font = font 127 | row.append(cell) 128 | 129 | worksheet.append(row) 130 | -------------------------------------------------------------------------------- /excel_response/views.py: -------------------------------------------------------------------------------- 1 | from django.views.generic.base import View 2 | from django.views.generic.list import MultipleObjectMixin 3 | 4 | from .response import ExcelResponse 5 | 6 | 7 | class ExcelMixin(MultipleObjectMixin): 8 | response_class = ExcelResponse 9 | header_font = None 10 | data_font = None 11 | output_filename = None 12 | worksheet_name = None 13 | force_csv = False 14 | 15 | def get_header_font(self): 16 | """ 17 | Return the font to be applied to the header row of the spreadsheet. 18 | """ 19 | return self.header_font 20 | 21 | def get_data_font(self): 22 | """ 23 | Return the font to be applied to all data cells in the spreadsheet. 24 | """ 25 | return self.data_font 26 | 27 | def get_output_filename(self): 28 | """ 29 | Return the name of the file to be generated, minus the file extension. 30 | 31 | For instance, an output filename of `'excel_data'` would return either 32 | `'excel_data.xlsx'` or `'excel_data.csv'` 33 | """ 34 | return self.output_filename or 'excel_data' 35 | 36 | def get_worksheet_name(self): 37 | """ 38 | Return the name of the worksheet into which the data will be inserted. 39 | """ 40 | return self.worksheet_name 41 | 42 | def get_force_csv(self): 43 | """ 44 | Return a boolean for whether or not to force CSV output. 45 | """ 46 | return self.force_csv 47 | 48 | def get_context_data(self, **kwargs): 49 | """ 50 | Provide an empty stub since these responses take no context. 51 | """ 52 | return {} 53 | 54 | def render_to_response(self, context, *args, **kwargs): 55 | return self.response_class( 56 | self.get_queryset(), 57 | output_filename=self.get_output_filename(), 58 | worksheet_name=self.get_worksheet_name(), 59 | force_csv=self.get_force_csv(), 60 | header_font=self.get_header_font(), 61 | data_font=self.get_data_font() 62 | ) 63 | 64 | 65 | class ExcelView(ExcelMixin, View): 66 | """ 67 | Return the results of a queryset as an Excel spreadsheet. 68 | """ 69 | def get(self, request, *args, **kwargs): 70 | return self.render_to_response({}) 71 | -------------------------------------------------------------------------------- /runtests.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import os 3 | import sys 4 | 5 | import django 6 | from django.conf import settings 7 | from django.test.utils import get_runner 8 | 9 | 10 | def runtests(): 11 | os.environ['DJANGO_SETTINGS_MODULE'] = 'testapp.settings' 12 | django.setup() 13 | TestRunner = get_runner(settings) # NOQA: N806 14 | test_runner = TestRunner() 15 | failures = test_runner.run_tests(["testapp"]) 16 | sys.exit(bool(failures)) 17 | 18 | 19 | if __name__ == "__main__": 20 | runtests() 21 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | from setuptools import setup 4 | 5 | 6 | # allow setup.py to be run from any path 7 | os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir))) 8 | 9 | with open('README.rst', 'r') as f: 10 | README = f.read() 11 | 12 | with open('VERSION', 'r') as vfile: 13 | VERSION = vfile.read().strip() 14 | 15 | setup( 16 | name='django-excel-response', 17 | version=VERSION, 18 | author='Joey Wilhelm', 19 | author_email='tarkatronic@gmail.com', 20 | license='Apache', 21 | description='Django package to easily render Excel spreadsheets', 22 | long_description=README, 23 | packages=['excel_response'], 24 | include_package_data=True, 25 | url='https://github.com/tarkatronic/django-excel-response', 26 | download_url='https://github.com/tarkatronic/django-excel-response/archive/master.tar.gz', 27 | install_requires=[ 28 | 'Django>=1.8', 29 | 'openpyxl<2.5' 30 | ], 31 | 32 | classifiers=[ 33 | 'Development Status :: 5 - Production/Stable', 34 | 'Environment :: Web Environment', 35 | 'Intended Audience :: Developers', 36 | 'License :: OSI Approved :: Apache Software License', 37 | 'Natural Language :: English', 38 | 'Operating System :: OS Independent', 39 | 'Programming Language :: Python', 40 | 'Programming Language :: Python :: 2.7', 41 | 'Programming Language :: Python :: 3', 42 | 'Programming Language :: Python :: 3.3', 43 | 'Programming Language :: Python :: 3.4', 44 | 'Programming Language :: Python :: 3.5', 45 | 'Programming Language :: Python :: 3.6', 46 | 'Framework :: Django', 47 | 'Framework :: Django :: 1.8', 48 | 'Framework :: Django :: 1.9', 49 | 'Framework :: Django :: 1.10', 50 | 'Framework :: Django :: 1.11', 51 | 'Topic :: Software Development :: Libraries :: Python Modules', 52 | 'Topic :: Office/Business :: Financial :: Spreadsheet', 53 | ], 54 | zip_safe=False, 55 | test_suite='runtests.runtests' 56 | ) 57 | -------------------------------------------------------------------------------- /testapp/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tarkatronic/django-excel-response/aef8072b3a6d0611b3b8fa46026e5152a23ed19f/testapp/__init__.py -------------------------------------------------------------------------------- /testapp/apps.py: -------------------------------------------------------------------------------- 1 | from django.apps import AppConfig 2 | 3 | 4 | class TestappConfig(AppConfig): 5 | name = 'testapp' 6 | -------------------------------------------------------------------------------- /testapp/migrations/0001_initial.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Generated by Django 1.11 on 2017-04-27 13:09 3 | from __future__ import unicode_literals 4 | 5 | from django.db import migrations, models 6 | 7 | 8 | class Migration(migrations.Migration): 9 | 10 | initial = True 11 | 12 | dependencies = [ 13 | ] 14 | 15 | operations = [ 16 | migrations.CreateModel( 17 | name='TestModel', 18 | fields=[ 19 | ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 20 | ('text', models.CharField(max_length=255)), 21 | ('number', models.IntegerField()), 22 | ('timestamp', models.DateTimeField(auto_now_add=True)), 23 | ], 24 | ), 25 | ] 26 | -------------------------------------------------------------------------------- /testapp/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tarkatronic/django-excel-response/aef8072b3a6d0611b3b8fa46026e5152a23ed19f/testapp/migrations/__init__.py -------------------------------------------------------------------------------- /testapp/models.py: -------------------------------------------------------------------------------- 1 | from django.db import models 2 | 3 | 4 | # Create your models here. 5 | class TestModel(models.Model): 6 | text = models.CharField(max_length=255) 7 | number = models.IntegerField() 8 | timestamp = models.DateTimeField(auto_now_add=True) 9 | -------------------------------------------------------------------------------- /testapp/settings.py: -------------------------------------------------------------------------------- 1 | SECRET_KEY = 'Pangalactic Gargleblaster' 2 | DATABASES = { 3 | 'default': { 4 | 'ENGINE': 'django.db.backends.sqlite3', 5 | 'NAME': ':memory:' 6 | } 7 | } 8 | 9 | INSTALLED_APPS = ['testapp'] 10 | 11 | ROOT_URLCONF = 'testapp.urls' 12 | -------------------------------------------------------------------------------- /testapp/tests.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import, unicode_literals 2 | 3 | from collections import OrderedDict 4 | 5 | import openpyxl 6 | import six 7 | from django.test import TestCase 8 | from openpyxl.styles import Font 9 | 10 | from excel_response import response 11 | 12 | from .models import TestModel 13 | 14 | 15 | class ExcelResponseCSVTest(TestCase): 16 | 17 | def test_force_csv(self): 18 | r = response.ExcelResponse([['a']], force_csv=True) 19 | # Call this so that all of the data gets resolved 20 | r.content 21 | self.assertEqual(r['content-type'], 'text/csv; charset=utf8') 22 | 23 | def test_exceeding_row_limit_with_list_creates_csv(self): 24 | old_limit = response.ROW_LIMIT 25 | response.ROW_LIMIT = 2 26 | r = response.ExcelResponse( 27 | [['a'], ['b'], ['c']] 28 | ) 29 | # Call this so that all of the data gets resolved 30 | r.content 31 | self.assertEqual(r['content-type'], 'text/csv; charset=utf8') 32 | response.ROW_LIMIT = old_limit 33 | 34 | def test_exceeding_column_limit_with_list_creates_csv(self): 35 | old_limit = response.COL_LIMIT 36 | response.COL_LIMIT = 2 37 | r = response.ExcelResponse( 38 | [['a', 'b', 'c']] 39 | ) 40 | # Call this so that all of the data gets resolved 41 | r.content 42 | self.assertEqual(r['content-type'], 'text/csv; charset=utf8') 43 | response.COL_LIMIT = old_limit 44 | 45 | def test_exceeding_row_limit_with_model_creates_csv(self): 46 | old_limit = response.ROW_LIMIT 47 | response.ROW_LIMIT = 2 48 | TestModel.objects.create(text='a', number='1') 49 | TestModel.objects.create(text='b', number='2') 50 | TestModel.objects.create(text='c', number='3') 51 | r = response.ExcelResponse( 52 | TestModel.objects.all() 53 | ) 54 | # Call this so that all of the data gets resolved 55 | r.content 56 | self.assertEqual(r['content-type'], 'text/csv; charset=utf8') 57 | response.ROW_LIMIT = old_limit 58 | 59 | def test_exceeding_column_limit_with_model_creates_csv(self): 60 | old_limit = response.COL_LIMIT 61 | response.COL_LIMIT = 2 62 | TestModel.objects.create(text='a', number='1') 63 | r = response.ExcelResponse( 64 | TestModel.objects.all() 65 | ) 66 | # Call this so that all of the data gets resolved 67 | r.content 68 | self.assertEqual(r['content-type'], 'text/csv; charset=utf8') 69 | response.COL_LIMIT = old_limit 70 | 71 | def test_csv_from_list(self): 72 | r = response.ExcelResponse( 73 | [['a', 'b', 'c'], [1, 2, 3], [4, 5, 6]], 74 | force_csv=True 75 | ) 76 | output = r.getvalue() 77 | self.assertEqual( 78 | output, 79 | b'a,b,c\r\n1,2,3\r\n4,5,6\r\n' 80 | ) 81 | 82 | def test_csv_from_list_of_dicts(self): 83 | r = response.ExcelResponse( 84 | [ 85 | OrderedDict([('a', 1), ('b', 2), ('c', 3)]), # OrderedDict ensures the order of our headers & output 86 | {'a': 4, 'b': 5, 'c': 6} 87 | ], 88 | force_csv=True 89 | ) 90 | output = r.getvalue() 91 | self.assertEqual( 92 | output, 93 | b'a,b,c\r\n1,2,3\r\n4,5,6\r\n' 94 | ) 95 | 96 | def test_queryset_values_limits_output_columns(self): 97 | TestModel.objects.create(text='a', number='1') 98 | TestModel.objects.create(text='b', number='2') 99 | TestModel.objects.create(text='c', number='3') 100 | r = response.ExcelResponse( 101 | TestModel.objects.all().values('text'), 102 | force_csv=True 103 | ) 104 | output = r.getvalue() 105 | self.assertEqual( 106 | output, 107 | b'text\r\na\r\nb\r\nc\r\n' 108 | ) 109 | 110 | def test_csv_output_with_empty_list(self): 111 | r = response.ExcelResponse([], force_csv=True) 112 | output = r.getvalue() 113 | self.assertEqual(output, b'') 114 | 115 | def test_csv_output_with_empty_queryset(self): 116 | r = response.ExcelResponse(TestModel.objects.none(), force_csv=True) 117 | output = r.getvalue() 118 | self.assertEqual(output, b'') 119 | 120 | 121 | class ExcelResponseExcelTest(TestCase): 122 | 123 | def test_create_excel_from_list(self): 124 | r = response.ExcelResponse( 125 | [['a', 'b', 'c'], [1, 2, 3], [4, 5, 6]] 126 | ) 127 | output = six.BytesIO(r.getvalue()) 128 | # This should theoretically raise errors if it's not a valid spreadsheet 129 | wb = openpyxl.load_workbook(output, read_only=True) 130 | ws = wb.active 131 | self.assertEqual((ws['A1'].value, ws['B1'].value, ws['C1'].value), ('a', 'b', 'c')) 132 | self.assertEqual((ws['A2'].value, ws['B2'].value, ws['C2'].value), (1, 2, 3)) 133 | 134 | def test_create_excel_from_list_of_dicts(self): 135 | r = response.ExcelResponse( 136 | [ 137 | OrderedDict([('a', 1), ('b', 2), ('c', 3)]), # OrderedDict ensures the order of our headers & output 138 | {'a': 4, 'b': 5, 'c': 6} 139 | ] 140 | ) 141 | output = six.BytesIO(r.getvalue()) 142 | openpyxl.load_workbook(output, read_only=True) 143 | 144 | def test_create_excel_from_queryset(self): 145 | TestModel.objects.create(text='a', number='1') 146 | TestModel.objects.create(text='b', number='2') 147 | TestModel.objects.create(text='c', number='3') 148 | r = response.ExcelResponse( 149 | TestModel.objects.all() 150 | ) 151 | output = six.BytesIO(r.getvalue()) 152 | openpyxl.load_workbook(output, read_only=True) 153 | 154 | def test_header_font_is_applied(self): 155 | f = Font(name='Windings') 156 | r = response.ExcelResponse( 157 | [['a', 'b', 'c'], [1, 2, 3], [4, 5, 6]], 158 | header_font=f 159 | ) 160 | output = six.BytesIO(r.getvalue()) 161 | book = openpyxl.load_workbook(output, read_only=True) 162 | sheet = book.active 163 | cell = sheet['A1'] 164 | self.assertEqual(cell.font.name, 'Windings') 165 | 166 | def test_data_font_is_applied(self): 167 | f = Font(name='Windings') 168 | r = response.ExcelResponse( 169 | [['a', 'b', 'c'], [1, 2, 3], [4, 5, 6]], 170 | data_font=f 171 | ) 172 | output = six.BytesIO(r.getvalue()) 173 | book = openpyxl.load_workbook(output, read_only=True) 174 | sheet = book.active 175 | cell = sheet['A2'] 176 | self.assertEqual(cell.font.name, 'Windings') 177 | 178 | def test_create_excel_with_guess_types_on(self): 179 | r = response.ExcelResponse( 180 | [['a', 'b', 'c'], ['2018032710050111540290000000000720000000023', 2, 3], [4, 5, 6]] 181 | ) 182 | output = six.BytesIO(r.getvalue()) 183 | # This should theoretically raise errors if it's not a valid spreadsheet 184 | wb = openpyxl.load_workbook(output, read_only=True) 185 | ws = wb.active 186 | self.assertEqual((ws['A1'].value, ws['B1'].value, ws['C1'].value), ('a', 'b', 'c')) 187 | self.assertEqual((ws['A2'].value, ws['B2'].value, ws['C2'].value), (2.018032710050112e+42, 2, 3)) 188 | 189 | def test_create_excel_with_guess_types_off(self): 190 | r = response.ExcelResponse( 191 | [['a', 'b', 'c'], ['2018032710050111540290000000000720000000023', 2, 3], [4, 5, 6]], guess_types=False 192 | ) 193 | output = six.BytesIO(r.getvalue()) 194 | # This should theoretically raise errors if it's not a valid spreadsheet 195 | wb = openpyxl.load_workbook(output, read_only=True) 196 | ws = wb.active 197 | self.assertEqual((ws['A1'].value, ws['B1'].value, ws['C1'].value), ('a', 'b', 'c')) 198 | self.assertEqual((ws['A2'].value, ws['B2'].value, ws['C2'].value), 199 | ('2018032710050111540290000000000720000000023', 2, 3)) 200 | 201 | 202 | class CBVTest(TestCase): 203 | 204 | def test_excel_view(self): 205 | TestModel.objects.create(text='a', number='1') 206 | TestModel.objects.create(text='b', number='2') 207 | TestModel.objects.create(text='c', number='3') 208 | response = self.client.get('/test/') 209 | output = six.BytesIO(response.content) 210 | openpyxl.load_workbook(output, read_only=True) 211 | -------------------------------------------------------------------------------- /testapp/urls.py: -------------------------------------------------------------------------------- 1 | from django.conf.urls import url 2 | 3 | from .views import TestView 4 | 5 | 6 | urlpatterns = [ 7 | url(r'^test/$', TestView.as_view()) 8 | ] 9 | -------------------------------------------------------------------------------- /testapp/views.py: -------------------------------------------------------------------------------- 1 | from excel_response import ExcelView 2 | 3 | from .models import TestModel 4 | 5 | 6 | class TestView(ExcelView): 7 | model = TestModel 8 | -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | [tox] 2 | envlist = 3 | py{27,33,34,35}-django18 4 | py{27,34,35}-django{19,110} 5 | py{27,34,35,36}-django111 6 | py{34,35,36}-django20 7 | py{35,36}-djangomaster, 8 | flake8 9 | skip_missing_interpreters = true 10 | 11 | [testenv] 12 | setenv = 13 | PYTHONDONTWRITEBYTECODE=1 14 | PYTHONWARNINGS=once 15 | COVERAGE_PROCESS_START=.coveragerc 16 | basepython = 17 | py27: python2.7 18 | py33: python3.3 19 | py34: python3.4 20 | py35: python3.5 21 | py36: python3.6 22 | deps = 23 | coverage_pth 24 | et-xmlfile 25 | jdcal 26 | openpyxl<2.5 27 | six 28 | django18: Django>=1.8,<1.9 29 | django19: Django>=1.9,<1.110 30 | django110: Django>=1.10,<1.11 31 | django111: Django>=1.11,<2.0 32 | django20: Django>=2.0,<2.1 33 | djangomaster: https://github.com/django/django/archive/master.tar.gz 34 | commands = python setup.py test 35 | 36 | [testenv:flake8] 37 | deps = 38 | flake8 39 | flake8-isort 40 | flake8-polyfill 41 | isort 42 | mccabe 43 | pep8 44 | pep8-naming 45 | pycodestyle 46 | pyflakes 47 | testfixtures 48 | basepython = python3.6 49 | commands = flake8 50 | 51 | [travis] 52 | python = 53 | 2.7: py27 54 | 3.3: py33 55 | 3.4: py34 56 | 3.5: py35 57 | 3.6: py36, flake8 58 | 59 | [travis:env] 60 | DJANGO = 61 | 1.8: django18 62 | 1.9: django19 63 | 1.10: django110 64 | 1.11: django111 65 | 2.0: django20 66 | master: djangomaster 67 | 68 | [coverage:run] 69 | branch = True 70 | source = excel_response 71 | parallel = True 72 | 73 | [coverage:paths] 74 | source = 75 | excel_response 76 | */site-packages 77 | --------------------------------------------------------------------------------