问题
I need some help with python. Basically I have 2 files(for this example will be file1 and file2). File1 have several sheets inside, file2 is just one sheet. So after some work in file2 now i have the DataFrame that i need. And I need to paste this DataFrame in one specific sheet in file1.
File1
A B C D E F G
<data> <data> <data> <data> <formula> <formula> <formula>
<data> <data> <data> <data> <formula> <formula> <formula>
<data> <data> <data> <data> <formula> <formula> <formula>
<data> <data> <data> <data> <formula> <formula> <formula>
<data> <data> <data> <data> <formula> <formula> <formula>
<data> <data> <data> <data> <formula> <formula> <formula>
File2
A B C D
<Newdata> <Newdata> <Newdata> <Newdata>
<Newdata> <Newdata> <Newdata> <Newdata>
<Newdata> <Newdata> <Newdata> <Newdata>
<Newdata> <Newdata> <Newdata> <Newdata>
<Newdata> <Newdata> <Newdata> <Newdata>
<Newdata> <Newdata> <Newdata> <Newdata>
So now i need to update the file one with the new Data.
File1
A B C D E F G
<Newdata> <Newdata> <Newdata> <Newdata> <formula> <formula> <formula>
<Newdata> <Newdata> <Newdata> <Newdata> <formula> <formula> <formula>
<Newdata> <Newdata> <Newdata> <Newdata> <formula> <formula> <formula>
<Newdata> <Newdata> <Newdata> <Newdata> <formula> <formula> <formula>
<Newdata> <Newdata> <Newdata> <Newdata> <formula> <formula> <formula>
<Newdata> <Newdata> <Newdata> <Newdata> <formula> <formula> <formula>
So the columns E,F and G have some formulas that are updated by the data in the columns A, B, C, D.
I try different options to do this. Concatenate both files and show the columns i try, load both files and create a new file with the new information... The main issue is that in the file1 i have several sheets, that i need to keep, because the columns E,F and G(The one with the formulas), will update other sheets.
So if someone give me a hand with this please. Thanks i will appreciate the help
回答1:
There is without a doubt a better way to do this but this is how I can do it:
from openpyxl import load_workbook
import os
os.chdir("Directory Path here")
wb = load_workbook('file.xlsx')
ws = wb.active
#or use the below to pick sheet as by name
# ws = wb.get_sheet_by_name
inde = []
val = []
for col in ws.iter_cols():
for cell in col:
h = cell.coordinate
inde.append(h)
v = cell.value
val.append(v)
diction = dict(zip(inde,val))
wb1=load_workbook('file1.xlsx')
ws1 = wb1.active
for i in diction.keys():
ws1[i] = diction[i]
wb1.save('file1.xlsx')
来源:https://stackoverflow.com/questions/42234155/copying-from-xlsx-to-an-specific-sheet-in-another-xlsx