
Index_length = max(df.index.map(_to_str).map(text_length).max(), text_length(df.index. If index: # If the index column is being exported # Compute column width of index column (if enabled) Here is the official documentation: Xlsxwriter worksheet.writeblank () method Another alternative is to merge a few blank columns ws.mergerange ('A1:D1', '') Otherwise you'll need to run a loop to write each blank cell Replace 1 for the row number you need for c in range (0,10): ws. lumn_dimensions.width = column_length * length_factor + margin # Set width of column to (column_length + margin) # Column index is +1 if we also export the index columnĬol_idx = df.columns.get_loc(column_name) # Convert the value of the columns to string and select theĬolumn_length = max(df.apply(_to_str).map(text_length).max(), text_length(column_name)) + 5

# Compute & set column width for each column With the help of this engine object, we can write the dataframe object to Excel worksheet. _to_str = functools.partial(_to_str_for_length, decimals=decimals) Then use XlsxWriter as the engine to create a Pandas Excel writer. xlsx', engine'xlsxwriter') workbook writer.book worksheet workbook.addworksheet ('new sheet') worksheet.

Return str(Decimal(v).quantize(Decimal('1.' + '0' * decimals)).normalize())ĭef auto_adjust_xlsx_column_width(df, writer, sheet_name, margin=3, length_factor=1.0, decimals=3, index=False): I don't see anything wrong with the way you are doing it but you could also use the XlsxWriter workbook object from the ExcelWriter as follows: writer pd.ExcelWriter ('test 2. Like str() but rounds decimals to predefined length

Get the effective text length in characters, taking into account newlines I may be a bit late to the party but this code works when using 'openpyxl' as your engine, sometimes pip install xlsxwriter wont solve the issue. It gets DataFrame and lets you to style it very easily.īy default the columns width is auto-adjusting.įor example: from StyleFrame import StyleFrameĭf = pd.DataFrame( is written as sheet')Ĭall example: writer = write_to_excel(writer, dataframe, "Statistical_Analysis") The object of this class is used as an argument to the DataFrame.to_excel() function to write DataFrame to excel sheet.Ĭlass pandas.There is a nice package that I started to use recently called StyleFrame. Technologies = ĭuration = Ĭolumns=ĭf = pd.DataFrame(list(zip(technologies,fee,duration,discount)), columns=columns)įollowing is the syntax of the ExcelWrite class.
