To Create a Excel file using python , the xlsxwriter module found pretty cool
pip install xlsxwriter
after installing it , lets write a code to create a file.
Create a file and associate it with worksheet
workbook = xlsxwriter.Workbook('person.xlsx')
worksheet = workbook.add_worksheet()
In a worksheet, column and row in a worksheet are referenced by their index number, which starts with 0.
Set a width of all columns :
worksheet.set_column(0, index_last_column, number)
above line can also be used to set width of particular column.
Creating a headers in bold :
bold = workbook.add_format({'bold': 1})
worksheet.write('A', 'Title', bold)
worksheet.write('B', 'Name', bold)
worksheet.write('C', 'Age', bold)
first row whose index is 0 is filled with above headers.
Filling Records
person_data = list(Person.objects.all())
let say we have a list of Person objects in person_data
row =1 // its not 0, since first row is a header
col =0
for person in person_data:
worksheet.write_string(row, col, person.title)
worksheet.write_string(row, col+1, person.first_name)
worksheet.write_string(row, col+2, person.last_name)
r = r+1
Close the file object :
workbook.close()
checkout docs for more fun.
pip install xlsxwriter
after installing it , lets write a code to create a file.
Create a file and associate it with worksheet
workbook = xlsxwriter.Workbook('person.xlsx')
worksheet = workbook.add_worksheet()
In a worksheet, column and row in a worksheet are referenced by their index number, which starts with 0.
Set a width of all columns :
worksheet.set_column(0, index_last_column, number)
above line can also be used to set width of particular column.
Creating a headers in bold :
bold = workbook.add_format({'bold': 1})
worksheet.write('A', 'Title', bold)
worksheet.write('B', 'Name', bold)
worksheet.write('C', 'Age', bold)
first row whose index is 0 is filled with above headers.
Filling Records
person_data = list(Person.objects.all())
let say we have a list of Person objects in person_data
row =1 // its not 0, since first row is a header
col =0
for person in person_data:
worksheet.write_string(row, col, person.title)
worksheet.write_string(row, col+1, person.first_name)
worksheet.write_string(row, col+2, person.last_name)
r = r+1
Close the file object :
workbook.close()
checkout docs for more fun.
No comments:
Post a Comment