Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

export excel with python using xlwt and adjusting width [duplicate]

Tags:

python

excel

xlwt

i have exported my list using xlwt :

response = HttpResponse(mimetype="application/ms-excel")
response['Content-Disposition'] = 'attachment; filename=Countries.xls'

wb = xlwt.Workbook()
ws1 = wb.add_sheet('Countries')

ws1.write(0, 0, 'Country Name')
ws1.write(0, 1, 'Country ID') 
countries = Country.objects.all()
index = 1
for country in countries:
   ws1.write(index, 0, country.country_name)    
   ws1.write(index, 1, country.country_id)
   index +=1

It generate an Excel file with list of countries but the problem is the columns of the sheet are not adjusted to data generated. is there any solution to adjust those columns ?

like image 464
Drwhite Avatar asked May 14 '13 13:05

Drwhite


People also ask

How do I automatically adjust column width in excel using Python?

The easiest way to auto-size the width and height of a column is to call the Worksheet class' autoFitColumn method. The autoFitColumn method takes the column index (of the column about to be resized) as a parameter. Copy def autofit_column(self): \# Instantiating a Workbook object by excel file path workbook = self.

What is XLWT module in Python?

This is a library for developers to use to generate spreadsheet files compatible with Microsoft Excel versions 95 to 2003. The package itself is pure Python with no dependencies on modules or packages outside the standard Python distribution.


1 Answers

There's no built-in way to adjust column width to the data inside using xlwt.

The question was already asked here, so I'll just refer you:

  • Python xlwt - accessing existing cell content, auto-adjust column width
  • Python XLWT adjusting column widths
  • John Machin's answers on the topic
    • Zoom in xlwt + auto-adjusting width for columns
    • Autofit column formatting

Basically, you should just keep track of the maximum data length in each column and adjust the column width manually based on the font size and style.

Hope that helps.

like image 193
alecxe Avatar answered Nov 14 '22 23:11

alecxe