Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format Excel Column header for better visibility and Color

I have gone through many posts but did not found the exact way to do the below. Sorry for attaching screenshot(Just for better visibility) as well , I will write it also. Basically it looks like -

Name_of_the_Man Address_of_Man  City
Jordan           NC             LMN

Input csv looks like

Available csv

Output Needed Need this

I have this code with me that picks the csv and attach as sheet in excel.

writer = pd.ExcelWriter('final.xlsx'), engine='xlsxwriter')
for f in glob.glob(os.path.join(Path, "*.csv")):
         df = pd.read_csv(f)
         df.to_excel(writer, sheet_name=os.path.basename(f))
writer.save()

I want my csv file - having good space in between and color for the column header.I have went through this link Python - change header color of dataframe and save it to excel file but it's not serving the purpose - It is coloring the sheet itself apart from column.

Update: Got the answer below . Also wondering if that can be possible just a thought enter image description here

like image 718
RonyA Avatar asked Jun 03 '18 09:06

RonyA


People also ask

How do I format the column headings to emphasize in Excel?

To do this, you should select the cells you want to have wrapped text and then right-click. A menu will open and you should select Format Cells. In the Format Cells box, select the Alignment tab, check Wrap text, and then click OK. Your column headings text is now being displayed on multiple lines.

How do I change the color of a column header in Excel?

Click the Excel tab. Click Edit. Select the background color of the technical column name header row from the Excel Column Name Background list box. Select the color of the technical column name text from the Excel Column Name Foreground list box.

How do you format headers in Excel?

On the status bar, click the Page Layout View button. Select the header or footer text you want to change. On the Home tab in the Font group, set the formatting options that you want to apply to the header / footer. When you're done, click the Normal view button on the status bar.

How do I bold column headings in Excel?

In Excel, you can set data in a cell to be bold, italic, or underlined, to help bring attention to it. To change a cell's text format, on the Home tab Font section of the Ribbon, click the B icon for bold, I icon for italic, or U icon for underline.


1 Answers

You can use Pandas Excel output with user defined header format with solution for change width by content:

writer = pd.ExcelWriter("file.xlsx", engine='xlsxwriter')

# Convert the dataframe to an XlsxWriter Excel object. Note that we turn off
# the default header and skip one row to allow us to insert a user defined
# header. Also remove index values by index=False
df.to_excel(writer, sheet_name='Sheet1', startrow=1, header=False, index=False)

workbook  = writer.book
worksheet = writer.sheets['Sheet1']
# Add a header format.
header_format = workbook.add_format({
    'bold': True,
    'fg_color': '#ffcccc',
    'border': 1})
for col_num, value in enumerate(df.columns.values):
    worksheet.write(0, col_num, value, header_format)

    column_len = df[value].astype(str).str.len().max()
    # Setting the length if the column header is larger
    # than the max column value length
    column_len = max(column_len, len(value)) + 3
    print(column_len)
    # set the column length
    worksheet.set_column(col_num, col_num, column_len)

# Close the Pandas Excel writer and output the Excel file.
writer.save()

pic

Changed your solution:

writer = pd.ExcelWriter('final.xlsx'), engine='xlsxwriter')
for f in glob.glob(os.path.join(Path, "*.csv")):
         df = pd.read_csv(f)
         df.to_excel(writer, sheet_name=os.path.basename(f))

        workbook  = writer.book
        worksheet = writer.sheets[os.path.basename(f)]
        # Add a header format.
        header_format = workbook.add_format({
            'bold': True,
            'fg_color': '#ffcccc',
            'border': 1})
        for col_num, value in enumerate(df.columns.values):
            worksheet.write(0, col_num, value, header_format)
            column_len = df[value].astype(str).str.len().max()
            # Setting the length if the column header is larger
            # than the max column value length
            column_len = max(column_len, len(value)) + 3
            print(column_len)
            # set the column length
            worksheet.set_column(col_num, col_num, column_len)

writer.save()

EDIT:

writer = pd.ExcelWriter("file.xlsx", engine='xlsxwriter')

#skip 2 rows
df.to_excel(writer, sheet_name='Sheet1', startrow=2, header=False, index=False)

workbook  = writer.book
worksheet = writer.sheets['Sheet1']
# Add a header format.
header_format = workbook.add_format({
    'bold': True,
    'fg_color': '#ffcccc',
    'border': 1})

#create dictionary for map length of columns 
d = dict(zip(range(25), list(string.ascii_uppercase)))
#print (d)

max_len = d[len(df.columns) - 1]
print (max_len)
#C
#dynamically set merged columns in first row
worksheet.merge_range('A1:' + max_len + '1', 'This Sheet is for Personal Details')

for col_num, value in enumerate(df.columns.values):
    #write to second row
    worksheet.write(1, col_num, value, header_format)

    column_len = df[value].astype(str).str.len().max()
    column_len = max(column_len, len(value)) + 3
    worksheet.set_column(col_num, col_num, column_len)

# Close the Pandas Excel writer and output the Excel file.
writer.save()
like image 140
jezrael Avatar answered Nov 10 '22 05:11

jezrael