J
J
Jay Marlow2016-09-22 23:30:18
Python
Jay Marlow, 2016-09-22 23:30:18

How to search and copy data in Excel using Python?

Good day.
I write in desperation.
For several days I have been trying to learn at least something (openpyxl, xlsxwriter, xlrd-xlwt ...) that will help me execute the following seemingly simple algorithm:

  1. Open Excel file.
  2. Find a cell in a certain column that matches a predetermined word (in Russian).
  3. Copy the entire row along with this cell and all the data in this row (row).
  4. Create a new Excel file and write it all there (all the rows in which that predetermined word was found).

Tried exactly each of the modules. Some have terrible troubles with getting data from a string, others do not accept the Russian language in cells, others refuse to work at all ...
Let's say the last failed example using win32com:
import win32com.client
Excel = win32com.client.Dispatch("Excel.Application")

text = 'Блендер'
counter = 2

def write(val, pos):
    wb = Excel.Workbooks.Add()
    ws = wb.ActiveSheet
    i = 1
    for rec in val:
        ws.Cells(pos,i).value = rec
        i = i + 1
    wb.SaveAs('test.xlsx')
    wb.Close()
    Excel.Quit()


def search():
    wb = Excel.Workbooks.Open(u'C:/Users/User/Desktop/excel.xlsx')
    sheet = wb.ActiveSheet
    srch = [r[0].value for r in sheet.Range("B2:B13")]
    for items in srch:
        if text in items:
            global counter
            print ('Found')
            found = sheet.Range("A%s:D%s" % (counter,counter)).Value
            print (found)
            write(found,counter)
        counter += 1
    
search()

Surely this code is as imperfect as it can be.
But let there be at least over999 crutches, if only it worked, but he doesn’t even work with this - when he sees a Russian-language text, he gets hysterical and shouts 'OLE error NONE NONE'. And even without Russian characters, one fig records only the first cell.
I will be eternally glad for any help.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Saboteur, 2016-09-23
@kolumbou

openpyxl seems to be nowhere easier. Here is a simple version on the knee.
To copy the entire row, just read the doc, or loop through all the cells in the row.

from openpyxl import Workbook,load_workbook

wbSearch = Workbook()
wbSearch = load_workbook("search.xlsx")
wsSearch = wbSearch.active

wbResult = Workbook()
wsResult = wbResult.active
resultRow = 1

lookFor = 'Блендер'

for i in range(1,21):
   value=wsSearch.cell(row=i, column=1).value
   if value == lookFor:
       wsResult.cell(row=resultRow, column=1).value=value

wbResult.save("result.xlsx")

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question