1

I was looking at the code related to xlsxwriter, when using Pandas' Dataframe.to_excel Command. I ended up adding some formatting to the files, but the columns dont see to work. Ideally i was hoping to dynamically set column widths to fit the content.

I saw there was a command called: set_column which i thought might do the trick. https://xlsxwriter.readthedocs.io/worksheet.html#set_column Showed me though that it needs to be a number.

that number to me, needs to be the largest string in that column (including the column name itself). While I can process that, I thought it a bit extreme to do. I figured there might be a wrap command i could use which auto formats or something.

Some Simple Code I was using:

import pandas as pd
from pandas import DataFrame
df = DataFrame({"aadsfasdfasdfasdfasdf":[1,2,3]})
writer = pd.ExcelWriter(filename, engine='xlsxwriter') 
_base_sheet = "Sheet1"
df.to_excel(writer, sheet_name=_base_sheet, header=HEADERS)
workbook = writer.book
worksheet = writer.sheets[_base_sheet]
...
# Here I would want do set all columns to have some sort of auto-width

Fallenreaper
  • 10,222
  • 12
  • 66
  • 129
  • If I understand correctly, then what you need is "auto fit". Possible related questions: [this](https://stackoverflow.com/questions/29463274/simulate-autofit-column-in-xslxwriter) and [this](https://stackoverflow.com/questions/33665865/adjust-cell-width-in-excel). – Qusai Alothman Jan 30 '21 at 05:23
  • @QusaiAlothman So the first one you linked is the one i found and I used that. The issue is though means that for every cell in a column i now need to computer character lengths and find the largest. I find that sounds to be computationally expensive. I was thinking there was just a dynamic thing such that when Excel opens and renders it would just have a format column width='fit' or something else as column metadata. – Fallenreaper Jan 31 '21 at 19:08
  • @Fallenreaper There isn't a simple instruction to get autofit since it is calculated by Excel at runtime and isn't part of the file format. See the XlsxWriter FAQ: https://xlsxwriter.readthedocs.io/faq.html – jmcnamara Feb 01 '21 at 09:15
  • Ah, ok. It is ok. Then i will have to do it this way. – Fallenreaper Feb 03 '21 at 16:27

0 Answers0