Split CSV file using Python shows not all data in Excel
<p>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 users can export a spreadsheet of all records in the database from Django admin. Right now when I export the file, I get this (only one random value out of many and not formatted correctly):</p>

<p><a href="http://i.stack.imgur.com/yGdrK.png" rel="nofollow"><img src="http://i.stack.imgur.com/yGdrK.png" alt="enter image description here"></a></p>

<p>What am I doing wrong? Not sure if I am using list comprehensions wrong, reading the file incorrectly, or if there is something wrong with my <code>for</code> loop. Please help! </p>

<pre><code>def dump_table_to_csv(db_table, io):
    with connection.cursor() as cursor:
        cursor.execute("SELECT * FROM %s" % db_table, [])
        row = cursor.fetchall()
        writer = csv.writer(io)
        writer.writerow([i[0] for i in cursor.description])
        writer.writerow(row)

    with open('/Users/nicoletorek/emarshal/myfile.csv', 'w') as f:
        dump_table_to_csv(Attorney._meta.db_table, f)

with open('/Users/nicoletorek/emarshal/myfile.csv', 'r') as f:
    db_list = f.read()
    split_db_list = db_list.split(',')

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

    header = workbook.add_format({
        'bg_color': '#F7F7F7',
        'color': 'black',
        'align': 'center',
        'valign': 'top',
        'border': 1
    })

    row = 0
    col = 0

    for x in split_db_list:
        worksheet_s.write(row + 1, col + 1, x, header)
</code></pre>

<p>Your CSV file could be read in and written as follows:</p>

<pre><code>import csv

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

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

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

workbook.close()
</code></pre>

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

python django csv split list-comprehension