Skip to content

Instantly share code, notes, and snippets.

@antoinebou12
Last active August 15, 2019 00:49
Show Gist options
  • Save antoinebou12/2a4383faf6eabb3a085d893cb64e900f to your computer and use it in GitHub Desktop.
Save antoinebou12/2a4383faf6eabb3a085d893cb64e900f to your computer and use it in GitHub Desktop.
Django xlsxWriter view and Jquery download xlsx client side
def export_xlsx(request):
response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
response['Content-Disposition'] = 'attachment; filename="{}"'.format(self._fname)
# Excel configuration
# TODO add more formatting
workbook = xlsxwriter.Workbook(response, {'in_memory': True})
worksheet = workbook.add_worksheet(self._sheet_name)
bold = workbook.add_format({'bold': True})
row = 1
col = 0
# Header
xlsx_columns = set([1,2,3,4])
# Header Write
for i, label in enumerate(list(xlsx_columns)):
worksheet.write(0, i, label, bold)
workbook.close()
return response
function downloadFile(filename, text, format) {
// Simple Download Function
// https://ourcodeworld.com/articles/read/189/how-to-create-a-file-and-generate-a-download-with-javascript-in-the-browser-without-a-server
// TODO Make a better download function
'use strict';
var element = document.createElement('a'),
ext = format || '';
if (ext === 'json') {
element.setAttribute('href', 'data:application/json;charset=utf-8,' + encodeURIComponent(JSON.stringify(text)));
} else {
// ext === 'csv' || ext === 'xlsx'
element.setAttribute('href', URL.createObjectURL(text));
}
element.setAttribute('download', filename);
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
}
$(function () {
//ajax to export_xlsx in python django view
$.ajax({
type: 'POST',
url: 'export_xlsx',
xhrFields: {responseType: 'blob'},
data: {input: 1},
success: function (response) {
if (response.status === 'failed') {
//error
} else if (response) {
downloadFile(fileName, response, format);
}
},
error: function (response) {
//error
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment