You can create a bar chart in Excel using Python by generating data with pandas and plotting it with matplotlib or openpyxl, then saving the result as an .xlsx file that includes an embedded chart. This approach automates report generation and is ideal for recurring data visualization tasks.

What You'll Need

  • Python 3.6 or later installed
  • pandas library (for data handling)
  • matplotlib or openpyxl with XlsxWriter engine (for chart creation)
  • A code editor or IDE (such as VS Code, PyCharm, or Jupyter Notebook)
  • Basic understanding of Python syntax and data frames

Step-by-Step

  1. Install required libraries using pip: run pip install pandas matplotlib openpyxl in your terminal or command prompt. If you prefer using XlsxWriter for more chart control, install it with pip install XlsxWriter instead of or alongside openpyxl.
  2. Prepare your data in a Python script. For example, create a dictionary with categories and values, then convert it to a pandas DataFrame:
    import pandas as pd
     data = {
         'Product': ['A', 'B', 'C', 'D'],
         'Sales': [230, 450, 150, 320]
     }
     df = pd.DataFrame(data)
    This creates a simple dataset for a vertical bar chart.
  3. Choose your plotting method. For direct Excel integration with formatting control, use pandas with XlsxWriter:
    import pandas as pd
     writer = pd.ExcelWriter('sales_chart.xlsx', engine='xlsxwriter')
     df.to_excel(writer, sheet_name='Sheet1', index=False)
     workbook = writer.book
     worksheet = writer.sheets['Sheet1']
     chart = workbook.add_chart({'type': 'column'})
     chart.add_series({
         'name': 'Sales',
         'categories': ['Sheet1', 1, 0, 4, 0],
         'values': ['Sheet1', 1, 1, 4, 1]
     })
     chart.set_title({'name': 'Product Sales'})
     chart.set_x_axis({'name': 'Product'})
     chart.set_y_axis({'name': 'Sales (Units)'})
     worksheet.insert_chart('D2', chart)
     writer.close()
    
    This writes the data to Excel and embeds a column (bar) chart starting at cell D2.
  4. Alternatively, use matplotlib to generate a chart and save it as an image, then insert it into Excel using openpyxl:
    import matplotlib.pyplot as plt
    from openpyxl import Workbook
    from openpyxl.drawing.image import Image
    
    plt.figure(figsize=(8, 5))
    plt.bar(df['Product'], df['Sales'], color='skyblue')
    plt.title('Product Sales')
    plt.xlabel('Product')
    plt.ylabel('Sales (Units)')
    plt.tight_layout()
    plt.savefig('bar_chart.png', dpi=150)
    plt.close()
    
    wb = Workbook()
    ws = wb.active
    for r in dataframe_to_rows(df, index=False, header=True):
        ws.append(r)
    img = Image('bar_chart.png')
    ws.add_image(img, 'D2')
    wb.save('sales_chart_openpyxl.xlsx')
    
    This method gives you full styling control via matplotlib before embedding.
  5. Open the generated .xlsx file in Microsoft Excel or LibreOffice Calc to verify the chart appears correctly. Check that axes are labeled, the title is visible, and data points match your source values.
  6. To update the chart with new data, simply re-run the script. The Excel file will be overwritten with updated values and a refreshed chart.

Common Mistakes

  • Forgetting to close the Excel writer with writer.close() or using a with statement, which can result in a corrupted or empty file.
  • Using incorrect cell ranges when defining chart series in XlsxWriter — ensure row and column indices are zero-based and correctly offset for header rows.
  • Neglecting to set index=False when exporting a DataFrame, which writes an extra unnamed column and shifts data alignment.
  • Using matplotlib’s plt.show() in a script intended to run headlessly (e.g., on a server), which can cause the script to hang waiting for user input.
  • Assuming the chart will update automatically if the source data changes — Excel does not link to the Python script; you must re-run and regenerate the file.

Tips

  • Use with pd.ExcelWriter(...) as writer: context manager to ensure proper file handling and automatic closing.
  • For horizontal bar charts, change the chart type to 'bar' in XlsxWriter instead of 'column'.
  • Apply consistent styling by defining colors, fonts, and borders in the chart properties to match corporate templates.
  • When generating multiple charts, create separate worksheets or position them with vertical spacing (e.g., 'D2', 'D20', 'D40') to avoid overlap.
  • Add data labels to the chart for better readability: in XlsxWriter, use .
  • If working in Jupyter Notebook, remember to call plt.close() after saving figures to prevent memory buildup during loops.

Troubleshooting

If the Excel file opens but the chart is missing:

  • Confirm the chart was actually added by checking for any errors during script execution — silent failures often occur if XlsxWriter isn’t installed.
  • Verify the worksheet name used in add_chart matches the sheet where data was written.
  • Ensure the image file path is correct when using openpyxl — a missing PNG will result in no image being inserted.
  • Check that the chart object wasn’t created but never inserted via insert_chart.

If the file fails to open or shows as corrupted:

  • Make sure you’re not writing to a file that’s currently open in Excel — close it first to avoid locking issues.
  • Try saving to a different directory or filename to rule out permission problems.
  • Use a try/except block to catch and print exceptions during file writing for easier debugging.

If the chart appears but labels or values are wrong:

  • Double-check that your DataFrame indices align with the expected rows — remember that to_excel starts writing data at row 0 unless offset.
  • Confirm that the series categories and values ranges in XlsxWriter correctly reference the data columns and rows.
  • Print your DataFrame before exporting to verify its contents and structure.

Frequently Asked Questions

Can I update an existing Excel file’s chart without rewriting the whole sheet?

Not directly with pandas or openpyxl — these libraries rewrite the entire file. For partial updates, consider using win32com on Windows to automate Excel, but this requires Excel to be installed and is platform-specific.

Is it possible to create stacked bar charts?

Yes. In XlsxWriter, set {'type': 'column', 'subtype': 'stacked'} or 'percent_stacked'. In matplotlib, use plt.bar(bottom=previous_values) to stack series manually.

Do I need Microsoft Excel installed to run this code?

No. The Python libraries generate the .xlsx file independently. Excel is only needed to view or edit the output, not to create it.

How do I add a chart title and axis labels?

In XlsxWriter, use chart.set_title(), chart.set_x_axis(), and chart.set_y_axis() with a 'name' field. In matplotlib, use plt.title(), plt.xlabel(), and plt.ylabel() before saving.

Can this work in a web server or automated report system?

Yes. As long as the server has Python and the required libraries, you can generate Excel files on demand and serve them as downloads or store them for later use.

What if I want to add multiple charts to one sheet?

Create multiple chart objects and insert them at different cell positions (e.g., 'D2', 'D18', 'D34') using worksheet.insert_chart() each time. Ensure sufficient vertical spacing to prevent overlap.