python 生成csv文件
import csv
with open("a.csv","w",newline="") as csvfile:
writer = csv.writer(csvfile)
writer.writerow(["a","b","c"])
Django 生成csv文件
def test_csv_view(request):
from bookstore.models import Book
response = HttpResponse(content_type="test/csv")
response['Content-Disposition'] = 'attachment;filename="test_csv.csv"'
all_book = Book.objects.all()
writer = csv.writer(response)
writer.writerow(["id","title"])
for i in all_book:
writer.writerow([i.id,i.title])
return response
上传文件
前端
- 上传请求: post
- form表单: 添加enctype=“multipart/form-data”
- 表单上传文件标签:
<input type="file" name="xxxx" >
后端
视图
视图函数,用request.FILES 取文件框内容
file = request.FILES[“xxx”]
说明
- FilES的key对应页面中file框的name值
- file 绑定文件流对象
- file.name文件名
- file.file文件字节流数据
路由
setting.py
添加
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR,"media")
urls.py
添加
from django.conf import settings
from django.conf.urls.static import static
urlpatterns +=static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
文件写入方案
传统open方法(需要考虑文件重名)
@csrf.csrf_exempt
def test_upload1(request):
if request.method == "GET":
return render(request,"test_upload.html")
if request.method == "POST":
a_file = request.FILES["myfile"]
print("上传文件",a_file.name)
filename = os.path.join(settings.MEDIA_ROOT,a_file.name)
with open(filename,"wb") as f:
data = a_file.file.read()
f.write(data)
return HttpResponse("接受文件成功")
借助ORM(推荐使用)
字段: FileField(upload=“子目录名”)
#存储路径
@csrf.csrf_exempt
def test_upload2(request):
if request.method == "GET":
return render(request,"test_upload.html")
if request.method == "POST":
title = request.POST.get("title")
a_file = request.FILES["myfile"]
content.object.create(desc=title,myfile=a_file)
return HttpResponse("接受文件成功")
#content→模型类
查看上传文件
http://127.0.0.1:8000/media/类字段名/图片名
.xls上传下载文件示例:
有模板
import xlrd
from xlutils.copy import copy
import xlwt
import os
import datetime
from django.http import FileResponse
def get_file_path(file_type):
# 开发环境下保存在smartwork同级文件下
app_file_save_path = r'D:\Desktop\pythonProject1\test1'
path = os.path.join(app_file_save_path, file_type)
# 如果目录不存在,自动建立目录
if not os.path.exists(path):
os.makedirs(path)
return path
def excel(request):
template = xlrd.open_workbook('D:\Desktop\pythonProject1\emplate.xls', formatting_info=True)
export_file = copy(template)
sheet = export_file.get_sheet(0)
# 设置样式
style = xlwt.XFStyle() # Create Style
borders = xlwt.Borders() # Create Borders
font = xlwt.Font() # 为样式创建字体
# 设置字体
# font.name = 'Times New Roman'
# font.name = u'宋体'
font.height = 220
# 设置单元格下框线样式
borders.left = 1
borders.right = 1
borders.top = 1
borders.bottom = 1
borders.bottom_colour = 0x3A
style.font = font # 设定样式
style.borders = borders # 将赋值好的模式参数导入Style
# 添加数据
# row = 6
for row, num in enumerate(range(3)):
# 编号
sheet.write(row + 6, 0,
f'{num}', style)
# row += 1
export_path = get_file_path('ceshi')
export_file_name = "feedback_export" + f"{datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S')}.xls"
export_file_path = os.path.join(export_path, export_file_name)
export_file.save(export_file_path)
f = open(export_file_path, 'rb')
response = FileResponse(f)
response['Content-Type'] = 'application/octet-stream'
export_file_name = os.path.basename(export_file_path)
response['Content-Disposition'] = 'attachment;filename=%s' % export_file_name
return response
无模板
def excel(request):
export_path = get_file_path("临时文件保存位置")
# 创建excel文件
workbook = xlwt.Workbook()
# 添加一个表
worksheet = workbook.add_sheet('sheet1')
export_file_name = "文件名.xls"'))
export_file_path = os.path.join(export_path, export_file_name)
# 设置导出表头样式
head_style = xlwt.XFStyle() # Create Style
head_borders = xlwt.Borders() # Create Borders
head_font = xlwt.Font() # 为样式创建字体
# 设置字体
# head_font.name = 'Times New Roman'
# head_font.name = u'宋体'
head_font.height = 240
head_font.bold = True
# 设置单元格下框线样式
head_borders.left = 1
head_borders.right = 1
head_borders.top = 1
head_borders.bottom = 1
head_borders.bottom_colour = 0x3A
head_style.font = head_font # 设定样式
head_style.borders = head_borders # 将赋值好的模式参数导入Style
# 设置数据内容样式
data_style = xlwt.XFStyle() # Create Style
data_borders = xlwt.Borders() # Create Borders
data_font = xlwt.Font() # 为样式创建字体
# 设置字体
# data_font.name = 'Times New Roman'
# data_font.name = u'宋体'
data_font.height = 220
# 设置单元格下框线样式
data_borders.left = 1
data_borders.right = 1
data_borders.top = 1
data_borders.bottom = 1
data_borders.bottom_colour = 0x3A
data_style.font = data_font # 设定样式
data_style.borders = data_borders # 将赋值好的模式参数导入Style
# 合并第一行得到提示信息
# worksheet.write_merge(0, 0, 0, 9, '备注:\n\r 1.仅供反馈管理模块的数据导出使用 ', data_style)
# 加入空行
# for i in range(1, 5):
# for n in range(0, 10):
# worksheet.write(i, n, "", data_style)
# 加入表头
head_list = list("表头名的列表")
head_col = 0
for a_head in head_list:
worksheet.write(0, head_col, a_head, head_style)
head_col += 1
# 添加数据
data_row = 1
for trouble in troubles:
# 反馈编号
worksheet.write("行号", "列号", f'数据', data_style)
# 保存
workbook.save(export_file_path)
return export_file_path