Python Forum

Full Version: openpyxl - How can I copy some row from an excel file and paste them in another one?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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
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"]