Python ajax上传文件 合并文件完整版
view:
from django.http import HttpResponse, JsonResponse
import pandas as pd
import chardet
import copy
import time
import random
import os
def concatexcel(request):
# 获取前段formdata传来的列表
fs = request.FILES.getlist('excel_files')
# 需要跳过的行
skip_rows = request.POST.get('skip_rows')
length = len(fs)
new_list = []
for i in range(length):
# 获取文件格式
file_name_temp, file_type = os.path.splitext(str(fs[i]))
if file_type == '.csv':
# 无密码csv格式转换
data = normal_csv(fs[i], skip_rows)
# 将数据加到列表
new_list.append(data)
if file_type == '.xls':
data = read_excel(fs[i], skip_rows)
new_list.append(data)
if file_type == '.xlsx':
data = read_excel(fs[i], skip_rows)
new_list.append(data)
# 合并表
try:
df = pd.concat(new_list)
except Exception as e:
return JsonResponse({"status": "400", "msg": str(e)})
# 文件名字
t = time.time()
file_name = int(round(t * 1000))
file_name = str(file_name) + str(random.randint(100, 999)) + '.xls'
# 文件路径全名
all_name = 'static/concatfile/' + file_name
# 写入到一个新excel表中
df.to_excel(all_name, index=False)
return JsonResponse({"status": "200", 'file_name': file_name})
# 无密码csv转换
def normal_csv(file, skip_rows):
# 深拷贝数据 防止f.read()和pd.read_csv干扰
f = copy.deepcopy(file)
# 获取编码格式
content = f.read()
encode = chardet.detect(content)['encoding']
f.close()
# 读取数据
try:
data = pd.read_csv(file, encoding=encode, skiprows=skip_rows)
except Exception as e:
return JsonResponse({"status": "400", "msg": str(e)})
return data
def read_excel(file, skip_rows):
# 读取数据
try:
data = pd.read_excel(file, skiprows=int(skip_rows))
except Exception as e:
return JsonResponse({"status": "400", "msg": str(e)})
return data
# 下载文件
def file_down(request):
file_name = request.GET.get('file_name')
# 读取文件
file = open('static/concatfile/' + file_name, 'rb')
# 下载文件
response = HttpResponse(file)
response['Content-Type'] = 'application/octet-stream'
response['Content-Disposition'] = 'attachment;filename=' + file_name
file.close()
return response
html:
document.getElementById('upload').onclick = function () {
var file = document.getElementById('excelFile');
//清空值
//file.outerHTML = file.outerHTML;
file.click();
}
//监听输入框变化
$('#excelFile').change(() => {
//如果为空 停止操作
if ($('#excelFile')[0].files.length == 0) {
return
}
//已选择文件
$('.download').val("合并并下载")
$('.upload').val("已选择" + $('#excelFile')[0].files.length + '个文件')
//设置可以选择下载
$('.download').removeAttr("disabled");
})
//点击下载
$('.download').click(() => {
var skip_rows = $('.deleteRowCountInput').val();
skip_rows == "" ? skip_rows=0 : skip_rows;
var ajaxurl = 'http://127.0.0.1:8000/concatexcel'
var formdata = new FormData();
file = $('#upload')[0].files;
for (var i = 0; i < $('#excelFile')[0].files.length; i++) {
file = $('#excelFile')[0].files[i];
formdata.append('excel_files', file)
formdata.append('skip_rows', skip_rows)
}
$.ajax({
type: 'post',
url: ajaxurl,
dataType: 'json',
data: formdata,
processData: false,
contentType: false
})
.done(function (e) {
if(e.status == '200'){
var file_name = e.file_name
//下载文件
location.href = "http://127.0.0.1:8000/file_down?file_name="+file_name;
} else{
console.log(e);
}
})
})