1锭部、最簡單的文件下載功能
def file_download(request):
with open('file_name.txt') as f:
c = f.read()
return HttpResponse(c)
2、更合理的文件下載功能
from django.http import StreamingHttpResponse
def big_file_download(request):
def file_iterator(file_name,chunk_size=512):
with open(file_name) as f:
while True:
c = f.read(chunk_size)
if c:
yield c
else:
break
the_file_name = "file_name.txt"
response = StreamingHttpResponse(file_iterator(the_file_name))
return response
3、文件下載功能再次優(yōu)化
from django.http import StreamingHttpResponse
def big_file_download(request):
# do something...
def file_iterator(file_name, chunk_size=512):
with open(file_name) as f:
while True:
c = f.read(chunk_size)
if c:
yield c
else:
break
the_file_name = "big_file.pdf"
response = StreamingHttpResponse(file_iterator(the_file_name))
response['Content-Type'] = 'application/octet-stream'
response['Content-Disposition'] = 'attachment;filename="{0}"'.format(the_file_name)
return response
4、直接導出Excel表格
import xlwt
import io
import json
from django.http import HttpResponse
def set_style(name, height, bold=False):
style = xlwt.XFStyle() # 初始化樣式
font = xlwt.Font() # 為樣式創(chuàng)建字體
font.name = name # 'Times New Roman'
font.bold = bold
font.color_index = 000
font.height = height
style.font = font
# 設置單元格邊框
# borders= xlwt.Borders()
# borders.left= 6
# borders.right= 6
# borders.top= 6
# borders.bottom= 6
# style.borders = borders
# 設置單元格背景顏色
# pattern = xlwt.Pattern()
# 設置其模式為實型
# pattern.pattern = pattern.SOLID_PATTERN
# 設置單元格背景顏色
# pattern.pattern_fore_colour = 0x00
# style.pattern = pattern
return style
def write_excel(data, name, header):
# 打開一個Excel工作簿
file = xlwt.Workbook()
# 新建一個sheet冠息,如果對一個單元格重復操作,會引發(fā)異常涩赢,所以加上參數(shù)cell_overwrite_ok=True
table = file.add_sheet(name, cell_overwrite_ok=True)
if data is None:
return file
# 寫標題欄
row0 = [u'業(yè)務', u'狀態(tài)', u'北京', u'上海', u'廣州', u'深圳', u'狀態(tài)小計']
for i in range(0, len(row0)):
table.write_merge(0, 0, i, i, row0[i], set_style('Times New Roman', 220, True))
table.write_merge(0, 2, 7, 9, "單元格合并", set_style('Times New Roman', 220, True))
"""
table.write_merge(x, x + m, y, w + n, string, sytle)
x表示行啸箫,y表示列,m表示跨行個數(shù)堂鲜,n表示跨列個數(shù)栈雳,string表示要寫入的單元格內(nèi)容,style表示單元格樣式缔莲。其中哥纫,x,y酌予,w磺箕,h,都是以0開始計算的抛虫。
"""
l = 0
n = len(header)
# 寫入數(shù)據(jù)
for line in data:
for i in range(n):
table.write(l, i, line[header[i]])
l += 1
# 直接保存文件
# file.save("D:/excel_name.xls")
# 寫入IO
res = get_excel_stream(file)
# 設置HttpResponse的類型
response = HttpResponse(content_type='application/vnd.ms-excel')
from urllib import parse
response['Content-Disposition'] = 'attachment;filename=' + parse.quote("excel_name") + '.xls'
# 將文件流寫入到response返回
response.write(res)
return response
def get_excel_stream(file):
# StringIO操作的只能是str松靡,如果要操作二進制數(shù)據(jù),就需要使用BytesIO建椰。
excel_stream = io.BytesIO()
# 這點很重要雕欺,傳給save函數(shù)的不是保存文件名,而是一個BytesIO流(在內(nèi)存中讀寫)
file.save(excel_stream)
# getvalue方法用于獲得寫入后的byte將結(jié)果返回給re
res = excel_stream.getvalue()
excel_stream.close()
return res
5棉姐、導出json格式
def write_json(data):
try:
json_stream = get_json_stream(data)
response = HttpResponse(content_type='application/json')
from urllib import parse
response['Content-Disposition'] = 'attachment;filename=' + parse.quote("test") + '.json'
response.write(json_stream)
return response
except Exception as e:
print(e)
def get_json_stream(data):
# 開始這里我用ByteIO流總是出錯屠列,但是后來參考廖雪峰網(wǎng)站用StringIO就沒問題
file = io.StringIO()
data = json.dumps(data)
file.write(data)
res = file.getvalue()
file.close()
return res
6、導出壓縮包
def write_zip(e_data, j_data, export_name):
try:
# 保存到本地文件
# 返回文件名伞矩,注意此時保存的方法和前面導出保存的json笛洛、excel文件區(qū)別
j_name = write_json(j_data, export_name[1])
e_name = write_excel(e_data, export_name[1])
# 本地文件寫入zip,重命名乃坤,然后刪除本地臨時文件
z_name='export.zip'
z_file = zipfile.ZipFile(z_name, 'w')
z_file.write(j_name)
z_file.write(e_name)
os.remove(j_name)
os.remove(e_name)
z_file.close()
# 再次讀取zip文件苛让,將文件流返回,但是此時打開方式要以二進制方式打開
z_file = open(z_name, 'rb')
data = z_file.read()
z_file.close()
os.remove(z_file.name)
response = HttpResponse(data, content_type='application/zip')
from urllib import parse
response['Content-Disposition'] = 'attachment;filename=' + parse.quote(z_name)
return response
except Exception as e:
logging.error(e)
print(e)
連接數(shù)據(jù)庫導出表格
import xlwt
import xlrd
import pymysql
conn = pymysql.connect(
host = '10.0.122.120',
port = 3306,
user = 'king',
passwd = 'QFedu123!'
)
cursor = conn.cursor()
cursor.execute("use dj21gp01")
cursor.execute("select * from server")
col = cursor.description
data = cursor.fetchall()
wb = xlwt.Workbook()
ws = wb.add_sheet("dj21gp01",cell_overwrite_ok=True)
for i in range(len(col)):
ws.write(0,i,col[i][0])
row = 1
for item in data:
for j in range(len(item)):
ws.write(row,j,item[j])
row += 1
wb.save("/root/桌面/server_info.xls")
cursor.close()