Pandas to excel bold text

Thanks to @NoobVB I was pointed in the right direction: write_rich_string. Found this great article describing it as a cookbook and turned it into a working solution:

import pandas as pd
from pandas.io.excel._xlsxwriter import XlsxWriter


class RichExcelWriter[XlsxWriter]:
    def __init__[self, *args, **kwargs]:
        super[RichExcelWriter, self].__init__[*args, **kwargs]

    def _value_with_fmt[self, val]:
        if type[val] == list:
            return val, None
        return super[RichExcelWriter, self]._value_with_fmt[val]

    def write_cells[self, cells, sheet_name=None, startrow=0, startcol=0, freeze_panes=None]:
        sheet_name = self._get_sheet_name[sheet_name]
        if sheet_name in self.sheets:
            wks = self.sheets[sheet_name]
        else:
            wks = self.book.add_worksheet[sheet_name]
            #add handler to the worksheet when it's created
            wks.add_write_handler[list, lambda worksheet, row, col, list, style: worksheet._write_rich_string[row, col, *list]]
            self.sheets[sheet_name] = wks
        super[RichExcelWriter, self].write_cells[cells, sheet_name, startrow, startcol, freeze_panes]

writer = RichExcelWriter['sample.xlsx']
workbook = writer.book
bold = workbook.add_format[{'bold': True}]

df = pd.DataFrame[[["Hello world."], [["Hello", bold, "bold", "world."]], columns = ["example"]]

df.to_excel[writer, sheet_name='Sample', index=False]
writer.save[]

This is the easiest way I figured out so far.

An example of converting a Pandas dataframe to an Excel file with a user defined header format using Pandas and XlsxWriter.

##############################################################################
#
# An example of converting a Pandas dataframe to an xlsx file
# with a user defined header format.
#
# SPDX-License-Identifier: BSD-2-Clause
# Copyright 2013-2022, John McNamara, 
#

import pandas as pd

# Create a Pandas dataframe from some data.
data = [10, 20, 30, 40, 50, 60]
df = pd.DataFrame[{'Heading': data,
                   'Longer heading that should be wrapped' : data}]

# Create a Pandas Excel writer using XlsxWriter as the engine.
writer = pd.ExcelWriter["pandas_header_format.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.
df.to_excel[writer, sheet_name='Sheet1', startrow=1, header=False]

# Get the xlsxwriter workbook and worksheet objects.
workbook  = writer.book
worksheet = writer.sheets['Sheet1']

# Add a header format.
header_format = workbook.add_format[{
    'bold': True,
    'text_wrap': True,
    'valign': 'top',
    'fg_color': '#D7E4BC',
    'border': 1}]

# Write the column headers with the defined format.
for col_num, value in enumerate[df.columns.values]:
    worksheet.write[0, col_num + 1, value, header_format]

# Close the Pandas Excel writer and output the Excel file.
writer.save[]

How do I bold text in Excel using Python?

How to set font bold for the Excel cells.
from openpyxl import Workbook from openpyxl.styles import Font..
wb = Workbook[].
ws = wb. active..
ws['A1'] = 'Tori Code' ws['A2'] = 'Tori Code'.
font = Font[bold=True].
ws['A1']. font = font..
wb. ... .
from openpyxl import Workbook from openpyxl.styles import Font wb = Workbook[] ws = wb..

How do I convert a panda to Excel?

Use pandas to_excel[] function to write a DataFrame to an excel sheet with extension . xlsx. By default it writes a single DataFrame to an excel file, you can also write multiple sheets by using an ExcelWriter object with a target file name, and sheet name to write to.

Can I format Excel with Python?

xlwings is an open-source Python library which allows easy manipulation and automation of Excel using Python code. xlwings is able to leverage Python's scientific packages [NumPy, Pandas, SciPy, scikit-learn ,etc.], write tools with Python instead of VBA, and create User Defined Functions in Python to use in Excel.

Why is Panda preferred over Excel?

Speed - Pandas is much faster than Excel, which is especially noticeable when working with larger quantities of data. Automation - A lot of the tasks that can be achieved with Pandas are extremely easy to automate, reducing the amount of tedious and repetitive tasks that need to be performed daily.

Chủ Đề