循环遍历excel文件,查找某些单元格值并写入文本文件

时间:2017-03-30 08:20:49

标签: python xlrd

我正在使用现有excel文件中的信息制作文本文件。并非excel文件中的所有信息都应该写在文本文件中,但我希望我的代码循环遍历文件并根据某些单元格值从行中选择信息。

到目前为止,这是我的代码,但是,当我运行代码时没有任何反应,并且不会生成文本文件。我也没有收到错误消息。有谁知道我错过了什么?

import xlrd
xlsfilename = 'Myexcelfile.xls'
book = xlrd.open_workbook(xlsfilename)
book.sheet_by_index(0)
number_rows = 275
number_lines = 1

for row in range(number_rows):
    for col in 1, :     #Column where the cell value decides wether or not information in the row should be added to the text file.
        value = book.sheets()[0].cell(row, col).value
        if value == 19:   #Rows where 19 is the cell value in column 1 is to be focused on.
            txtfilename = 'Mytextfile' + str(row) + '.txt'
            with open(txtfilename, "w") as f:
                d={} #Creating a dictionary to for Subject number (see later in the code)
                for line in range(number_line):
                    f.write("Subject number{1}") #The subject number should change for each row containing 19 is added to the text file.
                    f.write('Text\n')
                    f.write('Newtext'.ljust(1))
                    for col in 3,:
                        val = book.sheets()[0].cell(row, col).value
                        s1 = str(val).ljust(1)
                        f.write(s1)
                    f.write('Moretext'.ljust(1))
                    for col 9, 10:
                        val = book.sheets()[0].cell(row, col).value
                        s2 = str(val).ljust(1)
                        f.write(s2)
        else:
            pass

非常感谢任何帮助! 我正在使用Python3.4.1

1 个答案:

答案 0 :(得分:2)

要将第1列中包含字符串“19”的所有行写入同一文本文件,您可以执行以下操作:

import xlrd
xlsfilename = 'Myexcelfile.xls'
book = xlrd.open_workbook(xlsfilename)
book.sheet_by_index(0)
number_rows = book.sheets()[0].nrows
number_lines = 1
column_target = 1
txtfilename = 'Mytextfile.txt'

with open(txtfilename, "w") as f:
    for row in range(number_rows):
        value = book.sheets()[0].cell(row, column_target).value
        if value == "19":   #Rows where 19 is the cell value in column 1 is to be focused on.
                d={} #Creating a dictionary to for Subject number (see later in the code)
                for line in range(number_line):
                    f.write("Subject number{1}") #The subject number should change for each row containing 19 is added to the text file.
                    f.write('Text\n')
                    f.write('Newtext'.ljust(1))
                    for col in 3,:
                        val = book.sheets()[0].cell(row, col).value
                        s1 = str(val).ljust(1)
                        f.write(s1)
                    f.write('Moretext'.ljust(1))
                    for col 9, 10:
                        val = book.sheets()[0].cell(row, col).value
                        s2 = str(val).ljust(1)
                        f.write(s2)
        else:
            pass

基本上,只需将文件范围移到循环外部,以便可以为多行重用相同的文件。