在python中将txt文件转换为xls并添加新列

时间:2016-07-21 21:46:26

标签: python excel text xls

我有一个像这样内容的文本文件:

class Example(QtGui.QWidget):
    keyPressed = QtCore.pyqtSignal(QtCore.QEvent)
    def __init__(self):
        super(Example, self).__init__()
        self.setGeometry(300, 300, 250, 150)
        self.show()
        self.keyPressed.connect(self.on_key)

    def keyPressEvent(self, event):
        super(Example, self).keyPressEvent(event)
        self.keyPressed.emit(event) 

    def on_key(self, event):
        if event.key() == QtCore.Qt.Key_Enter and self.ui.continueButton.isEnabled():
            self.proceed()  # this is called whenever the continue button is pressed
        elif event.key() == QtCore.Qt.Key_Q:
            print "Killing"
            self.deleteLater()  # a test I implemented to see if pressing 'Q' would close the window

    def proceed(self):
        print "Call Enter Key"

def main():
    app = QtGui.QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

我想将文本文件转换为excel输出“。xls” 有两列,如下所示:

28179
49172
40180
36228
29337

我如何使用python执行此操作?

谢谢!

2 个答案:

答案 0 :(得分:0)

首先导入xlwt library并读取文件并将其保存在数组中:

import xlwt

data = []
with open("data.txt") as f:
    for line in f:
        data.append(line)

然后复制该数组并将新列写入Excel电子表格:

wb = xlwt.Workbook()
sheet = wb.add_sheet("New Sheet")
for row_index in range(len(data)):
    for col_index in range(2)):
        if col_index == 1:
            sheet.write(row_index, col_index, row_index)
        if col_index == 2:
            sheet.write(row_index, col_index, data[row_index])

 wb.save("newSheet.xls")

这是this question

中提供的代码的修改版本

答案 1 :(得分:0)

假设您已将数据保存在“ data.txt ”中,并且可以安装,

pip install pyexcel-io
pip install pyexcel-xls

您可以使用以下代码:

from pyexcel_io import save_data

SYMBOL = '----'

def data_gen(text_file):
    yield ['ID', SYMBOL, 'Code'] # first row
    with open(text_file, "r") as input_file:
        for row_index, element in enumerate(input_file, 1):
            yield row_index, SYMBOL, element.strip() # the rest

save_data("output.xls", {'data': data_gen("data.txt")})

如果您的数据文件超过65,536行,则需要安装

pip install pyexcel-xlsx

并将最后一行代码更新为:

...
save_data("output.xlsx", {'data': data_gen("data.txt")})