Skip to content Skip to sidebar Skip to footer

Split Csv File Using Python Shows Not All Data In Excel

I am trying to dump the values in my Django database to a csv, then write the contents of the csv to an Excel spreadsheet which looks like a table (one value per cell), so that my

Solution 1:

The immediate problem with your sample code, as Jean-Francois points out, is that you aren't incrementing your counters in the loop. Also you may also find it more readable to use xlsxwriter.write_row() instead of xlsxwriter.write(). At the moment a secondary complication is you aren't preserving row information when you read in your data from the CSV.

If your data looks like this:

row_data = [[r1c1, r1c2], [r2c1, r2c2], ... ]

You can then use:

forindex, row in enumerate(row_data):
    worksheet_s.write_row(index, 0, row)

That said, I assume you are interested in the .xlsx because you want control over formatting. If the goal is to just to generate the .xlsx and there is no need for the intermediate .csv, why not just create the .xlsx file directly? This can be accomplished nicely in a view:

import io
from django.http import HttpResponse

defdump_attorneys_to_xlsx(request):

    output = io.BytesIO()
    workbook = xlsxwriter.Workbook(output, {'in_memory': True})
    worksheet = workbook.add_worksheet('Summary')

    attorneys = Attorney.objects.all().values()

    # Write header
    worksheet.write_row(0, 0, attorneys[0].keys())

    # Write datafor row_index, row_dict inenumerate(attorneys, start=1):
        worksheet.write_row(row_index, 0, row_dict.values())
    workbook.close()

    output.seek(0)

    response = HttpResponse(output.read(), content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
    response['Content-Disposition'] = 'attachment; filename=summary.xlsx'return response

Solution 2:

Your CSV file could be read in and written as follows:

import csv

workbook = xlsxwriter.Workbook('output.xlsx')
worksheet_s = workbook.add_worksheet("Summary")

withopen(r'\Users\nicoletorek\emarshal\myfile.csv', 'rb') as f_input:
    csv_input = csv.reader(f_input)

    for row_index, row_data inenumerate(csv_input):
        worksheet_s.write_row(row_index, 0, row_data)

workbook.close()

This uses the csv library to ensure the rows are correctly read in, and the write_row function to allow the whole row to be written using a single call. The enumerate() function is used to provide a running row_index value.

Post a Comment for "Split Csv File Using Python Shows Not All Data In Excel"