문서 작업
# -*- coding: utf-8 -*-
# @Time : 2019-06-15 16:40
# @Author : songmz
# @email : [email protected]
import datetime
import xlwt
import xlrd
import requests
import json
from common.log import logger
from django.http import JsonResponse, HttpResponse, FileResponse
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
def down_doc(request):
file_info = open('./home_application/utiles/docs/info.docx', 'rb')
response = FileResponse(file_info)
response['Content-Type'] = 'application/octet-stream'
response['Content-Disposition'] = 'attachment;filename="{0}"'.format(u' .docx')
return response
def down_excel(request):
file_info = open('./home_application/utiles/docs/name.xls', 'rb')
response = FileResponse(file_info)
response['Content-Type'] = 'application/octet-stream'
response['Content-Disposition'] = 'attachment;filename="{0}"'.format(u' .xls')
return response
def import_doc(request):
file = request.FILES.get("file")
with open("./home_application/utiles/docs/%s" % file.name, 'wb+') as f:
for line in file.chunks():
f.write(line)
def export_excel(request):
"""
excel
:param request:
#
class BizInfo(models.Model):
cw_biz_id = models.IntegerField(u' ID')
cw_biz_name = models.CharField(u' ', max_length=32)
is_delete = models.BooleanField(u' ', default=False)
updated_date = models.DateTimeField(u' ', auto_now=True, null=True, blank=True)
class Meta:
verbose_name = u" "
verbose_name_plural = u" "
:return:
"""
style_bold_red = xlwt.easyxf('font:color-index black,bold on')
header_style = style_bold_red #
wb = xlwt.Workbook() # book
ws = wb.add_sheet('sheet1') #
# .
ws.write(0, 0, u" id", header_style)
ws.write(0, 1, u" ID", header_style)
ws.write(0, 2, u" ", header_style)
ws.write(0, 3, u" ", header_style)
try:
#
gathers = BizInfo.objects.all()
j = 1
for gather in gathers:
value = []
#
value.append(gather.id)
value.append(gather.cw_biz_id)
value.append(gather.cw_biz_name)
value.append(gather.updated_date)
# sheet
log_info = wb.get_sheet(0)
for i in range(0, len(value)):
#
if isinstance(value[i], unicode):
v = value[i]
else:
v = str(value[i])
log_info.write(j, i, v)
j += 1
response = HttpResponse(content_type='application/vnd.ms-excel', charset='utf-8')
response['Content-Disposition'] = r'attachment; filename={filename}'.format(filename=u"name") \
+ '.xls'
wb.save(response)
return response
except Exception as e:
logger.exception(u" :{}".format(e))
result = {'result': False, "error": e, "message": u" "}
return JsonResponse(result)
def import_excelt(request):
"""
excel
:param
:return:
"""
if len(request.FILES) <= 0:
return JsonResponse({'result': False, 'message': u' '})
f = request.FILES.get("file")
try:
book = xlrd.open_workbook(filename=None, file_contents=f.read())
sheet = book.sheet_by_index(0)
except Exception as e:
logger.exception(e)
return JsonResponse({'result': False, 'message': u' '})
if sheet.ncols != 4:
return JsonResponse({'result': False, 'message': u' '})
headers = [u" id", u" ID", u" ", u' ']
#
headers_match = True
for i in range(0, 4):
if sheet.cell(0, i).value != headers[i]:
headers_match = False
break
if headers_match is False:
return JsonResponse({'result': 0, 'message': u' '})
error_data = []
for i in range(1, sheet.nrows):
#
error_info = {}
id = sheet.cell(i, 0).value # id
cw_biz_id = sheet.cell(i, 1).value # ID
cw_biz_name = sheet.cell(i, 2).value #
updated_date = sheet.cell(i, 3).value #
object_info = BizInfo.objects.filter(id=id)
if len(object_info) == 1:
object_info.update(cw_biz_id=cw_biz_id, cw_biz_name=cw_biz_name, updated_date=updated_date)
else:
error_info['info'] = u" {cw_biz_name} , ".format(cw_biz_name=cw_biz_name)
error_data.append(error_info)
if error_data:
result = {'result': False, "data": error_data, "message": u" "}
else:
result = {'result': False, "data": "", "message": u" "}
return JsonResponse(result)
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
다양한 언어의 JSONJSON은 Javascript 표기법을 사용하여 데이터 구조를 레이아웃하는 데이터 형식입니다. 그러나 Javascript가 코드에서 이러한 구조를 나타낼 수 있는 유일한 언어는 아닙니다. 저는 일반적으로 '객체'{}...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.