Skip to content
Advertisement

add specific rows and column into another excel file using openpyxl in python

I’m trying to merge multiple file into one excel file using openpyxl in python

I know there is a way using panda, but my files have a problem there have been always 2 empty rows in the beginning of the excel file

So to avoid that I’m using openpyxl with the old way Just open all files and copy the specific rows and columns to a new one

The first step I find out how to do it by just copy the specific row’s and column of the new xlsx file

but I didn’t find a way to add the next file (only the value not the header) under the first one

this my code

So far it just copy the first file (the header and the value) But I didn’t find out how to add the next file (only the value) under the first one

JavaScript

Advertisement

Answer

What you are doing is creating a list of the excel files in the default directory then just opening the first file ‘[0]’ in the list with the line;

JavaScript

This will never attempt to access any other excel file in the list.
Having the list generation in the load book command isn’t good, you don’t want to be generating the list of available excel files each time you process a file. Calling of the function find_xlsx_files() should be done once.
The easiest fix to your code is to get your list of excel files and then iterate that list for processing.

JavaScript

Also it should not be necessary to save the book until you have finished writing all data.
The function can be simplified using glob instead if you prefer.

JavaScript

This is also assuming there is only one sheet in each excel file you want to process since you’re only opening the first sheet.

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement