Copying a row from a range of Excel files to another

Sayth Renshaw flebber.crue at gmail.com
Wed Jun 26 20:45:12 EDT 2019


 Cecil Westerhof  wrote:
> I was asked to copy a certain line from about 300 Excel lines to a new
> Excel file. That is not something I would like to do by hand and I
> immediately thought: that should be possible with Python.
> 
> And it is. I was surprised how fast I could write that with openpyxl.
> My first try was not very neat, but a proof of concept. Then by
> looking better at the possibilities I could get much cleaner code. But
> I am still not completely happy. At the moment I have the following
> code:
>     wb_out = Workbook()
>     for filepath in filepathArr:
>         current_row = []
>         wb_in       = load_workbook(filepath)
>         for cell in wb_in.active[src_row]:
>             current_row.append(cell.value)
>         wb_out.active.append(current_row)
>         wb_in.close()
>     wb_out.save(report_start + datetime.now().strftime('%Y-%m-%d') + report_end)
>     wb_out.close()
> 
> I could not find a way to copy a row from one workbook to another.
> That is why I put the row in current_row and do an append. Am I
> overlooking something, or is that really the way to do this?
> 
> 
> 
> -- 
> Cecil Westerhof

Pandas may work out better.

import pandas as pd

df = pd.read_excel('spreadsheet')
# find the row by filtering with regex
df2 = df.'column'.str.contains('criteria as regex')
df2.pd.save_excel('output.xlsx')

Cheers

Sayth



More information about the Python-list mailing list