You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python读取Excel转CSV报错:期望可迭代对象而非整数

Fixing the "iterable expected, not int" Error When Converting Excel Sheets to CSV

Hey there! Let's break down why you're hitting that frustrating error and get your Excel-to-CSV conversion working smoothly.

What's Causing the Error?

That message pops up because the csv.writerow() method needs an iterable (like a list, tuple, or row object) with all the values for a single row. Instead, your code is passing a single integer somewhere—either in the rowData.append(stuff) step (where stuff is a single cell value instead of a full row's data) or directly to csvWriter.writerow(r) (where r is a row number instead of the row's content).

Corrected Code Example

Let's use openpyxl (the standard library for modern .xlsx files) to build a working solution. First, install it if you haven't:

pip install openpyxl

Here's code that handles all your requirements without errors:

import openpyxl
import csv

# 1. Open the Excel file
workbook = openpyxl.load_workbook("your_excel_file.xlsx")

# 2. Get all sheet names
sheet_names = workbook.sheetnames

# 3. Convert each sheet to a separate CSV
for sheet_name in sheet_names:
    sheet = workbook[sheet_name]
    # Create a CSV file named after the worksheet
    with open(f"{sheet_name}.csv", "w", newline="", encoding="utf-8") as csv_file:
        csv_writer = csv.writer(csv_file)
        # Iterate over every row (values_only=True returns cell values directly as a tuple)
        for row in sheet.iter_rows(values_only=True):
            csv_writer.writerow(row)

print("All sheets converted to CSV successfully!")

Why This Works

  • sheet.iter_rows(values_only=True) returns each row as a tuple of cell values—this is exactly the iterable writerow() expects, so no more int-related errors.
  • We loop through every sheet by name, create a matching CSV file, and write rows directly without manual list-building (the most common spot for mistakes here).

What Might Have Gone Wrong in Your Original Code

If you were manually constructing rows (e.g., looping cell by cell), you might have done something like this (which triggers the error):

# ❌ Wrong example that causes the error
for row_num in range(1, sheet.max_row + 1):
    # Accidentally appending a single cell value instead of building a full row
    stuff = sheet.cell(row=row_num, column=1).value
    rowData.append(stuff)
    csvWriter.writerow(rowData)  # Or even worse, passing row_num directly!

This passes a single integer (or a list of isolated values) to writerow(), which isn't what the method needs. Instead, you need to collect all cell values for a row first, then pass that full list/tuple to writerow().

内容的提问来源于stack exchange,提问作者Chicken Sandwich No Pickles

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:02:27