Python xls:仅将非隐藏行复制到新工作簿并保存

Python xls: Copying only non-hidden rows to new Workbook and save

我正在编写一个脚本,仅将非隐藏行从一个文件复制到一个新工作簿。现在我有这个:

 import xlrd
 import xlwt
 from xlrd import open_workbook

 wb = open_workbook('input.xls', formatting_info=True)

 wb_sheet = wb.sheet_by_index(0)

 newBook = xlwt.Workbook()
 newSheet = newBook.add_sheet("no_hidden")

 idx = 0
 for row_idx in range(1, wb_sheet.nrows):
     hidden = wb_sheet.rowinfo_map[row_idx].hidden
     if(hidden is not True):
        for col_index, cell_value in enumerate(wb_sheet.row[row_idx]):
            newSheet.write(idx, col_index, cell_value)
            idx = idx+1
 newBook.save("test.xls")

但是,我收到一条错误消息:

Traceback (most recent call last):
  File "delete.py", line 16, in <module>
    for col_index, cell_value in enumerate(wb_sheet.row[row_idx]):
TypeError: 'method' object is not subscriptable

我想我处理 wb_sheet.row[]-对象的方式有误,但此时我不知道如何实现我想要的。任何帮助都会很棒。

谢谢!

来自文档行的是方法

row(rowx)

Returns a sequence of the Cell objects in the given row.

只需更改这部分代码:

  for col_index, cell_value in enumerate(wb_sheet.row(row_idx)):

同样的错误:

 def a():pass
 a[1]  # TypeError: 'function' object is not subscriptable

请按以下方式修改您的代码,希望这对您有所帮助。

import xlrd
import xlwt
from xlrd import open_workbook

wb = open_workbook('input.xls', formatting_info=True)

wb_sheet = wb.sheet_by_index(0)

newBook = xlwt.Workbook()
newSheet = newBook.add_sheet("no_hidden")

idx = 0
for row_idx in range(0, wb_sheet.nrows):
    hidden = wb_sheet.rowinfo_map[row_idx].hidden
    if(hidden==0):
        for col_index, cell_obj in enumerate(wb_sheet.row(row_idx)):
            newSheet.write(idx, col_index, cell_obj.value)
        idx = idx+1
newBook.save("test1.xls")

而不是 wb_sheet.row[row_idx] 应该是 wb_sheet.row(row_idx) 并且 它 returns 单元格对象,在写入其他 excel 文件时 cell_obj.value应该写成

希望这可能有所帮助。