2

首先也是最重要的:感谢您提前提供的任何帮助。我是一个编程新手,我的代码将反映这一点。我将尝试描述我正在尝试做的事情,并显示代码。再次感谢您的时间和解释。

目标:我想让 python 打开一个现有的 excel 文件(output.xls),并在该文档的下一个可用行中输入一个值(在本例中为“测试文本”)。我尝试使用“while”循环和“if”语句来完成这项工作。尽管两者都没有返回错误,但它们都未能正确地将输出移过第二行。这就是我所拥有的。

from xlrd import open_workbook
from xlutils.copy import copy
import xlwt

wb = open_workbook('output.xls',formatting_info=True)
sheet = wb.sheet_by_name("sheet 1")

#This is the simple test text here.
a = 'just a test'

rb = copy(wb)
ws = rb.get_sheet(0)

row = 0
cell = sheet.cell(row,4)

我在下面要说的是-WHILE-单元格不是空白的(类型 6),然后在行中添加一个并重复。IE:继续前进,直到您在第四列中找到一个空白行。

while cell.ctype != 6:
    row = row + 1

ws.write(row,4,a)

在这里,我希望确认结果。

print cell.ctype
rb.save('output.xls')

无论如何,当我运行代码时,它似乎并没有超过第一行。就好像代码说,“太好了,第一个单元格不是类型六”,但并没有超过那个。尽管在网上搜索了数小时,但我似乎无法找到原因。

非常感谢任何帮助/指导。

- - 编辑 - -

这是我收到的建议回复的错误。错误是相同的。

Traceback (most recent call last):
  File "C:\Users\Administrator\Desktop\Folder", line 19, in <module>
    cell = sheet.cell(row,4)
  File "C:\Python27\lib\site-packages\xlrd\sheet.py", line 395, in cell
    xfx = self.cell_xf_index(rowx, colx)
  File "C:\Python27\lib\site-packages\xlrd\sheet.py", line 421, in cell_xf_index
    xfx = self._cell_xf_indexes[rowx][colx]
IndexError: list index out of range
4

2 回答 2

2

你永远不会移动到下一个单元格。仅更改变量row不会影响cell. 试试这个代码:

cell = sheet.cell(row,4)
while cell.ctype != 6:
    row = row + 1
    if row >= sheet.nrows:
        break
    cell = sheet.cell(row,4)   # <-- actually move the "pointer" in the excel sheet
于 2014-01-09T09:42:56.530 回答
1

您推进行索引 - 但您没有读取新单元格,因此您的单元格保持不变,然后您进入无限循环

while cell.ctype != 6:
    row = row + 1
    cell = sheet.cell(row,4)

应该管用

编辑:

您的行数已经用完了 - 很容易修复

try:
    while cell.ctype != 6:
        row = row + 1
        cell = sheet.cell(row,4)
except IndexError:
    <do something>

就个人而言,我感觉你跑得太快了——你试图在没有学习基础知识的情况下变得太深

于 2014-01-09T09:42:47.390 回答