简体   繁体   中英

Exporting to xlsx using Python and XlsxWriter

I´m using XlsxWriter (version 1.0.2) for creating an Excel file, but when I exporting and opening it, an error is showed: “We found a problem with some content in filename.xlsx. Do you want us to try to recover as much as we can? If you trust the source of this workbook, click Yes.” When I click “Yes” button and after: “Close”, the Excel is opening and all is fine, so I can´t understand why this error is showed. I´m using Python 3.6.4, Django 2.0.1, Microsoft Office 2016, Windows 10 and module IO´s Python. I would like to know how to fix that problem.

Added code after comments:

def testError(request):
    data = [["Goal 1", 0, 0], ["1", "Activity 1", "Alex, Peter"], ["1.1", "Activity 1.1", "Matthew"], ["1.1.1", "Activity 1.1.1", "Jhon"]]
    output = io.BytesIO()
    workbook = xlsxwriter.Workbook(output, {'in_memory': True})
    worksheet = workbook.add_worksheet("Sheet1")
    bold = workbook.add_format({'bold': True})
    title = 'Example'
    merge_format = workbook.add_format({
        'bold': 1,
        'align': 'left',
        'valign': 'vcenter'})
    worksheet.merge_range('A1:C1', title, merge_format)
    a = 'B3:D'
    a += str(len(data)+4)
    worksheet.add_table(a, {'columns': [{'header': 'No'}, {'header': 'ACTIVITY'}, {'header': 'PARTAKERS'}], 'banded_rows': False, 'banded_columns': False, 'autofilter': 0})
    border_format = workbook.add_format({
        'border': 1,
        'align': 'left',
        'font_size': 10
    })
    merge_format = workbook.add_format({
        'bold': 1,
        'border': 1,
        'align': 'left',
        'valign': 'vcenter',
    })
    header_format = workbook.add_format({
        'bold': 1,
        'align': 'center',
        'valign': 'vcenter',
    })
    tab = 'B3:D'
    tab += str(len(data)+3)
    worksheet.autofilter(tab)
    it = 0
    countElem = (len(data))
    max_width_number = 0
    max_width_name = 0
    max_width_partaker = 0
    for ite in range(3, countElem+3):
        cel = 'B'
        cel += str(ite+1)
        if (data[it][0] != 0 and data[it][1] == 0 and data[it][2] == 0):
            worksheet.write_row(cel, data[it])
            iniCel = cel
            finCel = 'D'
            finCel += str(ite+1)
            mergecel = iniCel+':'+finCel
            worksheet.merge_range(mergecel, data[it][0], merge_format)
        else:
            i = 1
            for d in data[it]:
                worksheet.write_rich_string((str('B'+str(ite+1))), str(data[it][0]))
                if len(str(data[it][0])) > max_width_number:
                    max_width_number = len(str(data[it][0]))
                worksheet.write_rich_string((str('C'+str(ite+1))), str(data[it][1]))
                if len(data[it][1]) > max_width_name:
                    max_width_name = len(data[it][1])
                worksheet.write((str('D'+str(ite+1))), data[it][2])
                if len(data[it][2]) > max_width_partaker:
                    max_width_partaker = len(data[it][2])
        it = it+1
    worksheet.conditional_format(a, {'type': 'no_blanks', 'format': border_format})
    worksheet.conditional_format('B3:D3', {'type': 'no_blanks', 'format': header_format})
    worksheet.set_column(1, 1, max(5, max_width_number))
    worksheet.set_column(2, 2, max(20.57, max_width_name))
    worksheet.set_column(3, 3, max(8.29, max_width_partaker))
    workbook.close()
    output.seek(0)
    response = HttpResponse(output.read(), content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
    response['Content-Disposition'] = str("attachment; filename= workbook_example.xlsx")
    return response

There are two issues in your code.

The first is that you cannot merge cells in a table. Excel doesn't allow it. So remove this line:

worksheet.merge_range(mergecel, data[it][0], merge_format)

Also, you shouldn't add an autofilter to the table like this:

worksheet.autofilter(tab)

Instead use the autofilter property of add_table() :

worksheet.add_table(a, {..., 'autofilter': True})

After that the workbook will open without a warning and display like this:

在此处输入图片说明

You probably need to adjust the table range as well. Note, you don't need to create a range for the table like this:

tab = 'B3:D'
tab += str(len(data)+3)

The add_table() method, and almost all other methods in XlsxWriter, take (row, col) notation, see the docs .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM