1

My problem:

I'm programming in Python with pandas and openpyxl, what i am trying to do is make a console/ terminal app that looks up values the user types in, and then searches the excel file called db.xlsx If it has a match i would like to write that to a different excel file called output.xlsx

Whenever i do that it keeps deleting old data and puts in the new values, it doesnt matter if it overwrites as long as all the data gets written to output.xlsx, but i cant find a good answer on how to do this.

My code:

import pandas as pd
from openpyxl import Workbook, load_workbook

user_input = str
user_input = input('Type the name: ')

db_sheet = pd.read_excel('db.xlsx', sheet_name='db')
df = pd.DataFrame(db_sheet)

wb = load_workbook('output.xlsx')

for index, row in df.iterrows():
    if row['name'] == user_input:
        rows = row

the_data = {
    'name': [rows['name']],
    'gender': [rows['gender']],
    'age': [rows['age']],
}

df2 = pd.DataFrame(the_data, columns=['name', 'gender', 'age'])

df2.update(df2)
df2.to_excel('output.xlsx',index=False)

I tryed both pandas and openpyxl, what would be the best way to do this in?

Thanks in advance!

GIP
  • 21
  • 6
  • Possible duplicate of [append dataframe to excel with pandas](https://stackoverflow.com/questions/47737220/append-dataframe-to-excel-with-pandas) – AnsFourtyTwo Sep 28 '19 at 12:19
  • It helps if you post some sample data. Also, in``` for index, row in df.iterrows(): if row['name'] == user_input: rows = row ```, there could be multiple rows with matching names. In your case, you overwrite `rows` in every loop, so that only the last matching row is stored in `rows`. – Julia K Sep 28 '19 at 12:32

0 Answers0