Python, search excel sheet for specific strings in

2019-02-19 10:01发布

Here's the code I've frankensteined together from other posts,

import xlrd
import os.path
wb = xlrd.open_workbook(os.path.join('D:\Data','SPS1 demo data.xlsx'))
wb.sheet_names()
sh = #?
Strings=#variables
i = 1
file = open("Output.txt", "w")
while sh.cell(i,3).value = (Strings):
   file.write(#row)
   i = i + 1
file.close

It's not complete, but what I'm trying to accomplish is a search in column 3(or entire sheet, doesn't matter) for 5 specific strings and output those rows line by line to a text file, if possible csv formatted i.e. commas between each value.

How can I set a variable to 5 possible strings? Would this need to be an array?
I think the way that I have it written here will overwrite the text file each time rather than append it, is that correct? And if so what's the correct function, "file.append(#stuff)"?

1条回答
乱世女痞
2楼-- · 2019-02-19 10:15

This should work. You can't assign 5 strings to a single variable, without using a list or some other data type. You can however check to see if the third cell's value (i[2] - here) is equal to any of the strings you're looking for ("string1" - "string5" - here).

import xlrd
sheet_data = []   
wb = xlrd.open_workbook(Path_to_xlsx)
p = wb.sheet_names()
for y in p:
   sh = wb.sheet_by_name(y)
   for rownum in xrange(sh.nrows):
      sheet_data.append((sh.row_values(rownum)))

found_list = []
rows_to_be_saved = []
for i in sheet_data:
  if i[2] == "string1" or i[2] == "string2" or i[2] == "string3" or i[2] == "string4" or i[2] == "string5":
    found_list.append(i)
  else:
      rows_to_be_saved.append(i)

text_file = open("Output.txt", "w")
text_file.write(found_list)
text_file.close()

Your output written to the text file "Output.txt" will be comma separated as the rows in your excel are read into python as tuples in a list.

查看更多
登录 后发表回答