使用xlsxwriter将CSV转换为excel并将其保存到django Model

时间:2017-01-31 16:37:08

标签: python django excel csv xlsxwriter

现在我对转换此csv或下载它没有任何问题我在将文件保存到文件字段的django模型时遇到问题 最小化的示例代码:

def download_convert_reports_s3_temp():
    def get_report_url():
        bucket_name = 'temp_bucket'
        conn = boto.connect_s3(AWS_ACCESS_KEY_ID,
                               AWS_SECRET_ACCESS_KEY)
        bucket = conn.get_bucket(bucket_name)
        key = bucket.get_key('TEMP_2017-01-10.csv')
        return key.generate_url(expires_in=600)

    def get_doc():
        return Doc.objects.get(owner=User.objects.first())

    def get_file(file):
        file_temp = NamedTemporaryFile(delete=True)
        file_temp.write(file.content)
        file_temp.flush()
        return File(file_temp)

    def convert_csv_to_xlsx():
        request = requests.get(get_report_url())
        csvfile = get_file(request)

        from django.conf import settings
        excelFile = xlsxwriter.Workbook('report.xlsx', {
                                            'strings_to_numbers': True,
                                            'default_date_format': 'yy/mm/dd',
                                            'tmpdir': settings.MEDIA_ROOT +
                                                      '/documents/%s'.format(file.name.rsplit('.')[0] + '.xlsx')
                                        }

        excelFile = get_doc().file
        worksheet = excelFile.add_worksheet()
        worksheet.write('A1', 'data')
        worksheet.write('B1', 'data')
        worksheet.write('C1', 'data')
        worksheet.write('D1', 'data')
        worksheet.write('E1', 'data')
        # Start from the first cell. Rows and columns are zero indexed.
        row = 1
        col = 0
        with open(csvfile, 'rb') as f:
            content = csv.reader(f)
            # Iterate over the data and write it out row by row.
            for row_data in content:
                for data in row_data:
                    worksheet.write(row, col, data)
                    col += 1
                row += 1
                col = 0

        f.close()
        excelFile.close()

    return convert_csv_to_xlsx()

现在我真的不知道将这个excel文件保存到doc.file的问题, 我试过django fieldfile save

---> 19 read = property(lambda self: self.file. AttributeError: 'Workbook' object has no attribute 'read' 任何建议谢谢

1 个答案:

答案 0 :(得分:1)

    def convert_csv_to_xlsx():
    csvfile = get_file()
    from django.conf import settings
    excelFile = xlsxwriter.Workbook(filename=settings.MEDIA_ROOT + '/documents%s' % (
        csvfile.name.rsplit('.')[0] + '.xlsx'))
    bold = excelFile.add_format({'bold': 1, 'align': 'left', 'bg_color': 'red', 'color': 'white'})
    worksheet = excelFile.add_worksheet()
    worksheet.set_column(0, 4, width=15)
    worksheet.write('A1', 'Sender MSISDN', bold)
    worksheet.write('B1', 'Reciever MSISDN', bold)
    worksheet.write('C1', 'Amount', bold)
    worksheet.write('D1', 'Transaction ID', bold)
    worksheet.write('E1', 'Datetime', bold)
    # Start from the first cell. Rows and columns are zero indexed.
    row = 1
    col = 0

    # Iterate over the data and write it out row by row.


    for row_data in csv.reader(csvfile):
        for idx, data in enumerate(row_data):
            if idx == 0:
                worksheet.write(row, col, data)
            elif idx == 1:
                worksheet.write(row, col, data)
            elif idx == 2:
                worksheet.write(row, col, data)
            elif idx == 3:
                worksheet.write(row, col, data)
            elif idx == 4:
                worksheet.write(row, col, data)
            col += 1
        row += 1
        col = 0
    csvfile.close()
    doc = get_doc()
    now = datetime.now()

    excelFile.close()
    doc.file.save(
        name='RECHARGE_%d-%s-%s.xlsx' % (now.year,
                                         validate_date(now.month),
                                         validate_date(now.day)
                                         ),
        content=File(open(settings.MEDIA_ROOT + '/documents%s' % (
            csvfile.name.rsplit('.')[0] + '.xlsx',)))
    )
    os.remove(settings.MEDIA_ROOT + '/documents%s' % (
        csvfile.name.rsplit('.')[0] + '.xlsx'), )