Match the length of the column and aswell the height of each cell for a certian column

48 Views Asked by At

I have a problem. I have a dataframe with the column Summary. This contains a String something like:

example_string = """
Hello, I am a long text
With different
new lines
And with a loooooooooooooooooong text.
"""

What I want

enter image description here

Instead of

enter image description here

So I want that the length of the column is matched to length of the and for every cell it should get the 'perfect' height. How can I do this ?

     col_i_width = (df['Summary'].astype(str).apply(len).max() + 2) * 1.1
        worksheet.set_column(8, 8, col_i_width)

        for row_num, value in enumerate(df['Summary']):
            lines = str(value).split('\n')
            max_line_length = max(map(len, lines))
            if max_line_length > 0:
                for line_num, line in enumerate(lines):
                    worksheet.set_row(row_num + 1 + line_num, len(line) * 1.0)  # Adjust the factor for your preferred height.

Example

import pandas as pd
from datetime import datetime

excel_file = 'your_filename.xlsx'  # Set the desired filename

# Create a DataFrame (replace this with your own data source)
data = {'ColumnA': [1, 2, 3], 'ColumnB': [4, 5, 6], 'ColumnC': [7, 8, 9], 'ColumnI': ['Hello', 'I am a', 'somewhat', """
Hello, I am a long text
With different
new lines
And with a loooooooooooooooooong text.
"""]}
df = pd.DataFrame(data)

with pd.ExcelWriter(excel_file, engine='xlsxwriter') as writer:
    # Current date
    current_date = datetime.now()

    # Date formatting
    formatted_date = current_date.strftime("%b. %d")

    df.to_excel(writer, sheet_name=formatted_date, index=False)

    # Access the XlsxWriter workbook and worksheet objects
    workbook = writer.book
    worksheet = writer.sheets[formatted_date]

    # Automatically adjust column width for all columns
    for i, column in enumerate(df.columns):
        column_len = max(df[column].astype(str).str.len().max(), len(column))
        col_width = (column_len + 2) * 1.1  # Adjust the factor for your preferred width
        worksheet.set_column(i, i, col_width)

     col_i_width = (df['Summary'].astype(str).apply(len).max() + 2) * 1.1
        worksheet.set_column(8, 8, col_i_width)

        for row_num, value in enumerate(df['Summary']):
            lines = str(value).split('\n')
            max_line_length = max(map(len, lines))
            if max_line_length > 0:
                for line_num, line in enumerate(lines):
                    worksheet.set_row(row_num + 1 + line_num, len(line) * 1.0)  # Adjust the factor for your preferred height.
0

There are 0 best solutions below