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

使用xlwt向Excel写入数据时遭遇单元格覆盖错误求助

Fixing Your Excel-Python Export Errors

Hey there! Let's break down what's going wrong with your code and fix it step by step.

What's Causing the Issues?

1. Cell Overwrite Error (Exception: attempt to overwrite cell)

Looking at your code, the first for loop writes to the same row (row 1) every time because you never increment the m variable inside it. That means you're overwriting cell (1,0) 8 times in a row. The confusing mention of row 9 comes from your unnecessary second for loop, which increments m to 9 but doesn't serve any purpose—let's focus on fixing the core issue first.

2. Abnormal print(x) Output

You added x = x+1 inside the first loop, but for x in range(1,9) already automatically increments x each iteration. This double-increment makes x jump from 1→2, 2→3, etc., so your print output ends up being 2,3,4,5,6,7,8,9 instead of the expected 1-8.

Fixed Code

Let's rewrite your code to fix both problems. We'll remove redundant lines, increment rows correctly, and get rid of the useless second loop:

import xlwt

book = xlwt.Workbook(encoding="utf-8")
sheet1 = book.add_sheet("sheet 1")
sheet1.write(0, 0, "Display")

# Use enumerate to track row number starting from 1
for row_num, x in enumerate(range(1, 9), start=1):
    sheet1.write(row_num, 0, x)
    print(x)  # Now outputs 1,2,3,4,5,6,7,8 as expected

book.save("trial.xls")

Alternative (Using Your Original Variable Names)

If you prefer sticking with m instead of enumerate, here's another working version:

import xlwt

book = xlwt.Workbook(encoding="utf-8")
sheet1 = book.add_sheet("sheet 1")
sheet1.write(0, 0, "Display")

m = 1  # Start writing from row 1 (header is row 0)
for x in range(1, 9):
    sheet1.write(m, 0, x)
    print(x)
    m += 1  # Move to the next row after writing

book.save("trial.xls")

Key Fixes Explained

  • Removed x = x+1: The for loop handles incrementing x automatically—manual increments break the loop's natural flow.
  • Added m += 1 (or used enumerate): This ensures each value of x gets written to a new row, eliminating cell overwrites.
  • Deleted the second for loop: It was only incrementing m unnecessarily and didn't contribute to writing data.

Now when you run this code, it will write numbers 1-8 to rows 1-8 in column 0, print the correct values, and save your Excel file without errors.

内容的提问来源于stack exchange,提问作者Ravi Mevada

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:59:57