문서 작업

26871 단어
문서 작업
# -*- 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)

좋은 웹페이지 즐겨찾기