Python在多个Excel中搜索对应的数据并粘贴到新的Excel工作表中

时间:2018-08-20 21:27:55

标签: python excel pandas openpyxl

我的文件夹中有一些excel文件,每个文件中已经有一个工作表称为“服务”

Notes_111.xlsx
Notes_222.xlsx
Notes_888.xlsx

工作流程:我想打开每个.xlsx文件,例如Notes_111.xlsx,然后添加一个新工作表,名称为“ code_city”,然后基于文件名 111 < / strong>,仅从主数据框中提取 code = 111 数据并粘贴到新工作表中。然后保存。

在另一个Excel文件中采样主数据框

    code           city
0    111            NY
1    111            CA
2    222            NJ
3    888            WE
4    888            TL

我不知道如何在循环中编写逻辑来搜索对应的数据

import pandas as pd
import numpy as np
import glob
from openpyxl import load_workbook

for f in glob.glob(path + "Notes_*.xlsx"):
   wb = load_workbook(f)
   ws = wb.create_sheet('code_city')
   ws['A1'] = 'how to search corresponding data and paste here???'
   wb.save(f)

请帮助。

2 个答案:

答案 0 :(得分:1)

使用pandas更加容易操作,我相信它仍然会在幕后使用openpyxl。

import glob
import pandas as pd
import os


for f in glob.glob('Notes_*.xlsx'):
    dda = re.findall('\d+', f) #matches digits in the filename

    df_each = pd.read_excel(f) # have to save the data first, coz ExcelWriter will clear up and create a new excel, so, you paste the saved data back to new sheet
    df_1_dda = df_master[df_master['code'] == int(dda[0])] #select only those records with code in the filename

    writer = pd.ExcelWriter(f)
    df_each.to_excel(writer, 'service', index = False) #  paste the saved data back to new sheet
    df_1_dda.to_excel(writer, 'code_city', index = False)
    writer.close()

希望有帮助!

使用python 3.6.4 Anaconda-32位

答案 1 :(得分:0)

from openpyxl import load_workbook

for f in glob.glob("Notes_*.xlsx"):
    code = re.findall('\d+', f) #matches digits in the filename
    df_1_dda = df_master[df_master['code'] == int(code[0])] #select only those records with code from the master dataframe

    #create new worksheet using openpyxl
    wb = load_workbook(f)
    ws = wb.create_sheet('code_city')
    wb.save(f)

    # reload the file and paste data I need
    writer = pd.ExcelWriter(f)
    df_1_dda.to_excel(writer, 'code_city')
    writer.save()