我似乎找不到在 xlwt.Workbook() 中返回工作表中列数的值的方法。这个想法是在一个目录中获取一堆 .xls 文件并将它们组合成一个。我遇到的一个问题是在编写下一个文件时更改列位置。这就是我目前正在使用的:
import xlwt, xlrd, os
def cbc(rd_sheet, wt_sheet, rlo=0, rhi=None,
rshift=0, clo=0, chi=None, cshift = 0):
if rhi is None: rhi = rd_sheet.nrows
if chi is None: chi = 2#only first two cols needed
for row_index in xrange(rlo, rhi):
for col_index in xrange(clo, chi):
cell = rd_sheet.cell(row_index, col_index)
wt_sheet.write(row_index + rshift, col_index + cshift, cell.value)
Dir = '/home/gerg/Desktop/ex_files'
ext = '.xls'
list_xls = [file for file in os.listdir(Dir) if file.endswith(ext)]
files = [Dir + '/%s' % n for n in list_xls]
output = '/home/gerg/Desktop/ex_files/copy_test.xls'
wbook = xlwt.Workbook()
wsheet = wbook.add_sheet('Summary', cell_overwrite_ok=True)#overwrite just for the repeated testing
for XLS in files:
rbook = xlrd.open_workbook(XLS)
rsheet = rbook.sheet_by_index(0)
cbc(rsheet, wsheet, cshift = 0)
wbook.save(output)
list_xls 返回:
['file2.xls', 'file3.xls', 'file1.xls', 'copy_test.xls']
文件返回:
['/home/gerg/Desktop/ex_files/file2.xls', '/home/gerg/Desktop/ex_files/file3.xls', '/home/gerg/Desktop/ex_files/file1.xls', '/home/gerg/Desktop/ex_files/copy_test.xls']
我的问题是如何每次将写入 xlwt.workbook 的每个文件都搜索 2 倍。这段代码给了我第一个保存到.../copy_test.xls
. 文件列表也有问题吗?我有一种感觉,可能有。这是 Python2.6,我在 windows 和 linux 之间跳来跳去。
谢谢你的帮助,GM