Python Forum
openpyxl - How can I copy some row from an excel file and paste them in another one? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: openpyxl - How can I copy some row from an excel file and paste them in another one? (/thread-27431.html)



openpyxl - How can I copy some row from an excel file and paste them in another one? - aquerci - Jun-06-2020

from a source excel file I have to copy the rows (with theirs formatting) where I find a specific string placed in a specific column. In few words I wanna implement a filter (see my attached screenshot to have an example).

now, I don't know so much about openpyxl, I chosed it because it seems quite popular. today I started to write a draft of the code, but now I don't know how to complete it. can you give me a hand please?
from io import BytesIO
import openpyxl

def FindColumnID(name, ws):
    header = ws[1]
    for cell in header:
        if cell.value == name:
            return header.index(name) + 1

def CreateDocument(database_path, text_path, column_name):
    text_file = open(text_path, "r")
    text = text_file.read()
    text_file.close()
    ls = text.split("\n")
    ls.insert(0, column_name)

    database_wb = openpyxl.load_workbook(database_path)
    database_ws = database_wb[database_wb.sheetnames[0]]

    column_id = FindColumnID(column_name, database_ws)

    output = BytesIO()    
    result_wb = openpyxl.Workbook(output)
    result_ws = slu_wb.active
    result_ws.title = "RESULT"

    for row in database_ws.rows:
        for element in ls:
            if database_ws.cell(row, column_id).value == element:
                #
                # copy the row with the formatting in result_wb  <---------- how can I do it?
                #
                #
                break



RE: openpyxl - How can I copy some row from an excel file and paste them in another one? - Knight18 - Jun-07-2020

Did some quick googling for you. According this openpyxl article, you can use the following code to retrieve values. There is also another way using the columns and rows, which is probably the better the idea. I advise you to read the article. It's a lot of information.

a = sheet["A1"]
b = sheet["D2"]
c = sheet["F7"]


RE: openpyxl - How can I copy some row from an excel file and paste them in another one? - buran - Jun-07-2020

look at this SO https://stackoverflow.com/q/23332259/4046632