Python - 复制Excel信息

时间:2016-06-23 21:14:17

标签: excel python-2.7

如何从excel文档第3页的第1和第2列复制信息。

我使用xlwt和xlrd作为库来读取和写入excel文档

这是我的代码:

import xlwt
import xlrd

workbook = xlrd.open_workbook('input.xls')
sheet = workbook.sheet_by_index(2)

data = [sheet.cell_value(row, 0) for row in range(sheet.nrows)]

data = [sheet.cell_value(row, 1) for row in range(sheet.nrows)]

workbook = xlwt.Workbook()
sheet = workbook.add_sheet('test')

for index, value in enumerate(data):
    sheet.write(0, index, value)

workbook.save('Commands')

1 个答案:

答案 0 :(得分:1)

你正在覆盖data。而是做:

import xlwt
import xlrd

workbook = xlrd.open_workbook('input.xlsx')
sheet = workbook.sheet_by_index(2)

data = []
data.append([sheet.cell_value(row, 0) for row in range(sheet.nrows)])
data.append([sheet.cell_value(row, 1) for row in range(sheet.nrows)])

workbook = xlwt.Workbook()
sheet = workbook.add_sheet('test')

for colidx, col in enumerate(data):
    for rowidx, row in enumerate(col):
        sheet.write(rowidx, colidx, row)

workbook.save('Commands.xls')

编辑:要写入txt文件使用:

with open('output.txt','wb') as fou:
    writer = csv.writer(fou)
    for row in data:
        writer.writerow(row)