Saturday 13 September 2014

How to Export Your Data as CSV, Excell (XLS), or XLSX in python with django

Standard

today i will tell you how you will export data from database

suppose you are export a data format that only you can read or your programmer can read so it's not a good programming , a good programmer design a user interface where a baby can handle.

so give a data format where user can understand what is it and also he/she can download , that's why i choose EXCELL format and for program CSV format.

in python with django it's so simple and easy just follow bellow example



Comma-Separated Values Format(CSV)

CSV is the most common import and export format for spreadsheets and databases. It's a textual format which one could easily create or parse himself, but there is also a python built-in library csv for handy data manipulation.

here todo_obj is data source

def export_csv(request):
    import csv
    from django.utils.encoding import smart_str
   
    todo_obj=Todo.objects.filter(user_id=request.session['user_id'])
    response = HttpResponse(mimetype='text/csv')
    response['Content-Disposition'] = 'attachment; filename=todo.csv'
    writer = csv.writer(response, csv.excel)
    response.write(u'\ufeff'.encode('utf8')) # BOM (optional...Excel needs it to open UTF-8 file properly)
    writer.writerow([
        smart_str(u"sl"),
        smart_str(u"job"),
        smart_str(u"date"),
    ])
    row_num = 0
    for obj in todo_obj:
        row_num += 1
        writer.writerow([
            smart_str(row_num),
            smart_str(obj.todo_job),
            smart_str(obj.created_date.strftime("%A %d. %B %Y")),
        ])
    return response


Excel Binary File Format

XLS is the main spreadsheet format which holds data in worksheets, charts, and macros. We are going to use xlwt library to create a spreadsheet. There is analogous library xlrd to read XLS files. Note, that this format allows to have only 256 columns.

here todo_obj is data source

def export_excell(request):
    import xlwt
    import datetime
   
    todo_obj=Todo.objects.filter(user_id=request.session['user_id'])
    response = HttpResponse(mimetype='application/ms-excel')
    response['Content-Disposition'] = 'attachment; filename=todo.xls'
    wb = xlwt.Workbook(encoding='utf-8')
    ws = wb.add_sheet("Todo")
   
    row_num = 0
   
    columns = [
        (u"sl", 2000),
        (u"job", 8000),
        (u"date", 6000),
    ]

    font_style = xlwt.XFStyle()
    font_style.font.bold = True

    for col_num in xrange(len(columns)):
        ws.write(row_num, col_num, columns[col_num][0], font_style)
        # set column width
        ws.col(col_num).width = columns[col_num][1]

    font_style = xlwt.XFStyle()
    font_style.alignment.wrap = 1
   
    for obj in todo_obj:
        row_num += 1
        row = [
            row_num,
            obj.todo_job,
            obj.created_date.strftime("%A %d. %B %Y"),
        ]
        for col_num in xrange(len(row)):
            ws.write(row_num, col_num, row[col_num], font_style)
           
    wb.save(response)
    return response


Here we created one worksheet, filled it with data, marked the first row in bold, and made the lines in the other cells wrapped. Also we set the width for each column. We'll do the same in the next format too.

Office Open XML Format

XLSX (a.k.a. OOXML or OpenXML) is a zipped, XML-based file format developed by Microsoft. It is fully supported by Microsoft Office 2007 and newer versions. OpenOffice 4.0, for example, can only read it. There is a python library openpyxl for reading and writing those files. This format is great when you need more than 256 columns and text formatting options.

here todo_obj is data source

def export_xlsx(request):
    import openpyxl
    from openpyxl.cell import get_column_letter
    todo_obj=Todo.objects.filter(user_id=request.session['user_id'])
    response = HttpResponse(mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
    response['Content-Disposition'] = 'attachment; filename=todo.xlsx'
    wb = openpyxl.Workbook()
    ws = wb.get_active_sheet()
    ws.title = "Todo"

    row_num = 0

    columns = [
        (u"sl", 15),
        (u"job", 100),
        (u"Date", 70),
    ]

    for col_num in xrange(len(columns)):
        c = ws.cell(row=row_num + 1, column=col_num + 1)
        c.value = columns[col_num][0]
        # set column width
        ws.column_dimensions[get_column_letter(col_num+1)].width = columns[col_num][1]

    for obj in todo_obj:
        row_num += 1
        row = [
            row_num,
            obj.todo_job,
            obj.created_date.strftime("%A %d. %B %Y"),
        ]
        for col_num in xrange(len(row)):
            c = ws.cell(row=row_num + 1, column=col_num + 1)
            c.value = row[col_num]

    wb.save(response)
    return response



so now you can export any format as ur user requirement

enjoy