You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

使用Pandas与Openpyxl实现Python读取CSV并写入Excel的问题

Hey there! Let's work through this problem together—you're already off to a great start getting the CSV read into a DataFrame, so we just need to iron out the Excel append part with openpyxl.

First, let's make sure you have the right tools installed (if you don't already):

pip install pandas openpyxl

The main trick here is using pd.ExcelWriter in append mode, and handling both cases where your target Excel file already exists (with the worksheet you want) or needs to be created from scratch. Here's a complete, commented example that should solve your issue:

import pandas as pd
from openpyxl import load_workbook

# Step 1: Read your daily CSV (you already have this part down, adjust the path as needed)
daily_df = pd.read_csv("path/to/your/daily_report.csv")

# Step 2: Define your target Excel file and the specific worksheet to append to
target_excel = "your_master_spreadsheet.xlsx"
target_worksheet = "DailyData"  # Replace with your actual sheet name

try:
    # Case 1: Excel file already exists—load it and append to the worksheet
    workbook = load_workbook(target_excel)
    
    with pd.ExcelWriter(
        target_excel,
        engine="openpyxl",
        mode="a",  # "a" stands for append mode
        if_sheet_exists="overlay"  # Overlay means we add to the existing sheet instead of replacing it
    ) as writer:
        # Find the last row with data in the target worksheet so we don't overwrite existing content
        last_row = workbook[target_worksheet].max_row
        # Append the DataFrame—skip the header since it's already in the Excel file
        daily_df.to_excel(
            writer,
            sheet_name=target_worksheet,
            startrow=last_row,  # Start writing right after the last existing row
            header=False,
            index=False
        )
except FileNotFoundError:
    # Case 2: Excel file doesn't exist yet—create it and write the first batch (including headers)
    with pd.ExcelWriter(target_excel, engine="openpyxl") as writer:
        daily_df.to_excel(writer, sheet_name=target_worksheet, index=False)

Key Notes to Avoid Common Issues:

  • Don't have the Excel file open: If the file is open in Excel itself, openpyxl won't be able to write to it—make sure it's closed before running the script.
  • Match worksheet names exactly: Worksheet names are case-sensitive, so double-check that target_worksheet matches what's in your Excel file (e.g., "Sheet1" vs "sheet1" are different).
  • Upgrade your libraries: Old versions of pandas or openpyxl might have bugs with append mode. Run pip install --upgrade pandas openpyxl to make sure you're on the latest versions.

If you run into specific errors (like permission issues or sheet not found errors), feel free to share the error message and we can dig deeper!

内容的提问来源于stack exchange,提问作者Jil W

火山引擎 最新活动