使用xlwt向Excel写入数据时遭遇单元格覆盖错误求助
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: Theforloop handles incrementingxautomatically—manual increments break the loop's natural flow. - Added
m += 1(or usedenumerate): This ensures each value ofxgets written to a new row, eliminating cell overwrites. - Deleted the second
forloop: It was only incrementingmunnecessarily 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

