Skip to content

Instantly share code, notes, and snippets.

@dafma
Created August 1, 2017 18:55
Show Gist options
  • Select an option

  • Save dafma/7bf991fba0a1c3d9d3b4d64f40570db7 to your computer and use it in GitHub Desktop.

Select an option

Save dafma/7bf991fba0a1c3d9d3b4d64f40570db7 to your computer and use it in GitHub Desktop.
Django export rar sql to excel install -- pip install xlwt
# install pip install xlwt
from django.shortcuts import render
from django.db import connection
# Create your views here.
import xlwt
from django.http import HttpResponse
from django.contrib.auth.models import User
## SQL TO EXPORT
#Select email, is_active from auth_user
def sqlView(request):
response = HttpResponse(content_type='application/ms-excel')
response['Content-Disposition'] = 'attachment; filename="users.xls"'
wb = xlwt.Workbook(encoding='utf-8')
ws = wb.add_sheet('Semanas')
# Sheet header, first row
row_num = 0
font_style = xlwt.XFStyle()
font_style.font.bold = True
columns = ['Email', 'is active', ]
for col_num in range(len(columns)):
ws.write(row_num, col_num, columns[col_num], font_style)
# Sheet body, remaining rows
font_style = xlwt.XFStyle()
sql = "Select email, is_active from auth_user"
cursor = connection.cursor()
cursor.execute(sql)
rows = cursor.fetchall()
for row in rows:
row_num += 1
for col_num in range(len(row)):
ws.write(row_num, col_num, row[col_num], font_style)
wb.save(response)
return response
def index(request):
return render(request, 'index.html')
def export_users_xls(request):
response = HttpResponse(content_type='application/ms-excel')
response['Content-Disposition'] = 'attachment; filename="users.xls"'
wb = xlwt.Workbook(encoding='utf-8')
ws = wb.add_sheet('Users')
# Sheet header, first row
row_num = 0
font_style = xlwt.XFStyle()
font_style.font.bold = True
columns = ['Username', 'First name', 'Last name', 'Email address', ]
for col_num in range(len(columns)):
ws.write(row_num, col_num, columns[col_num], font_style)
# Sheet body, remaining rows
font_style = xlwt.XFStyle()
rows = User.objects.all().values_list('username', 'first_name', 'last_name', 'email')
print(rows)
for row in rows:
row_num += 1
for col_num in range(len(row)):
ws.write(row_num, col_num, row[col_num], font_style)
wb.save(response)
return response
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<a href="{% url 'export_users_xls' %}">Export all users</a>
<a href="{% url 'sqlView' %}">Reads</a>
</body>
</html>
from django.conf.urls import url
from django.contrib import admin
from app import views
# sqlView
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^export/xls/$', views.export_users_xls, name='export_users_xls'),
url(r'^export/reads$', views.sqlView, name='sqlView'),
url(r'^$', views.index, name='index')
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment