// 엑셀 다운로드
$('#id').unbind("click").bind('click', function(){
...
...
..
.
const data = {
// Put your data
}
location.href = LOCAL_URL + "/excel?data=" + JSON.stringify(data);
});
def MyExcelView(request):
if request.method == "GET":
#html = request.GET.get('html', None)
#type = request.GET.get("type", None)
data = request.GET.get("data", None)
data = eval(data)
...
...
..
.
qs = "SELECT ......"
res = None
try:
cursor = connection.cursor()
cursor.execute(qs)
data = cursor.fetchall()
logger.debug(data)
data_json = []
for item in data:
data_id = item[0]
qs = "SELECT......."
try:
cursor = connection.cursor()
cursor.execute(qs)
post_image = cursor.fetchone()
data_json.append({
"item": item,
"image": post_image,
"type": type,
})
except Exception as e:
logger.debug(e)
# 여기가 중요
res = export_excel(request, data_json)
connection.commit()
connection.close()
if res is None:
res = redirect("/home")
except Exception as e:
logger.debug(e)
return res
import datetime, os, xlsxwriter, json
from io import BytesIO
from django.http import FileResponse, HttpResponse
from string import ascii_uppercase
import pandas as pd
from pathlib import Path
from django.conf import settings
import urllib
def export_excel(request, data):
if data:
output = BytesIO()
workbook = xlsxwriter.Workbook(output, {'in_memory': True})
bold = workbook.add_format({'bold': True})
worksheet = workbook.add_worksheet("test")
LOCAL = "http://127.0.0.1:8000"
SERVER = "..."
merge_format = workbook.add_format({
'bold': 1,
'align': 'center',
'valign': 'vcenter',
})
column_format = workbook.add_format({
'bold': 1,
'border': 1,
'fg_color': 'gray',
'align': 'center',
'valign': 'vcenter',
})
gallery = []
row = 0
col = 0
for item in data:
type = item["type"]
col = 0
row = 0
items = item["item"]
columns = [.......]
worksheet.set_column('A:G', 30)
worksheet.set_row(0, 30)
for y in range(len(users)):
worksheet.write(row, col, columns[y], column_format)
col += 1
for item in data:
each_item = item["item"]
row += 1
worksheet.set_row(row, 20)
for elm in range(len(each_item)):
idx = each_item[elm]
worksheet.write(row, elm, idx, merge_format)
workbook.close()
output.seek(0)
response = HttpResponse(output.read(), content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
response['Content-Disposition'] = "attachment; filename=%s.xlsx" %"test"
return response
참고 사이트
http://my-django-python.blogspot.com/2015/05/how-to-create-excel-file-with-images.html?m=1