Python26 min read

Python Working with Excel

Automate Excel files using pandas and openpyxl: read sheets, write reports, format headers, and generate Excel outputs for business and data workflows.

David Miller
September 2, 2025
9.7k309

Excel automation is very common in real jobs:
- reporting
- finance sheets
- data cleaning
- exporting results for clients

        Python can:
        - read Excel
        - create Excel
        - format Excel (colors, bold headers)
        - write multiple sheets
        
        ## Install libraries
        
        ```bash
        pip install openpyxl pandas
        ```
        
        ## Pandas: read Excel (fastest for analysis)
        
        ```python
        import pandas as pd
        
        df = pd.read_excel("data.xlsx")
        print(df.head())
        
        df2 = pd.read_excel("data.xlsx", sheet_name="Sheet1")
        ```
        
        ## Pandas: write Excel
        
        ```python
        import pandas as pd
        
        df.to_excel("output.xlsx", index=False)
        
        with pd.ExcelWriter("output.xlsx") as writer:
            df.to_excel(writer, sheet_name="Users", index=False)
            df.to_excel(writer, sheet_name="Backup", index=False)
        ```
        
        ## openpyxl: read cells (more control)
        
        ```python
        from openpyxl import load_workbook
        
        wb = load_workbook("data.xlsx")
        sheet = wb["Sheet1"]
        
        for row in sheet.iter_rows(min_row=2, values_only=True):
            print(row)
        ```
        
        ## openpyxl: write + format (best for styling)
        
        ```python
        from openpyxl import Workbook
        from openpyxl.styles import Font, PatternFill
        
        wb = Workbook()
        sheet = wb.active
        
        sheet.append(["Name", "Age", "City"])
        sheet.append(["Tom", 25, "Austin"])
        sheet.append(["Sarah", 28, "Miami"])
        
        header_font = Font(bold=True, color="FFFFFF")
        header_fill = PatternFill(start_color="0070C0", fill_type="solid")
        
        for cell in sheet[1]:
            cell.font = header_font
            cell.fill = header_fill
        
        wb.save("formatted.xlsx")
        ```
        
        ## Graph: choose pandas vs openpyxl
        
        ```mermaid
        flowchart TD
          A[Excel Task] --> B{Goal?}
          B -->|Analysis + filtering| C[Pandas]
          B -->|Formatting + styling| D[openpyxl]
          B -->|Both| E[Use pandas then style with openpyxl]
        ```
        
        ## Remember
        
        - pandas is best for data work
        - openpyxl is best for formatting
        - For professional reports, you often use both
        
#Python#Advanced#Excel