简体   繁体   中英

Python xlsx insert columns at cell location

I am trying to copy data from a column and insert that data into another column at a specific cell location preserving the data above it, while shifting right the other column data.

I have been trying to do this in Openpyxl and with Pandas with no luck. I'm attaching pictures of the desired outcome to help clarify the question.

Before :

前

After :

后

--Updated with Code and output--

from openpyxl import *
def setupAfter():
    flag=False
    for cols in beforesheet.iter_cols():
        for cell in cols:
            if cell.row == 2 and cell.column == 2:
                aftersheet.insert_cols(cell.column, amount=1)
                flag=True
                break
        if flag:break
        else:
            continue
    aftersheet['B3'].value = beforesheet['A1'].value
    aftersheet['B4'].value = beforesheet['A2'].value
    aftersheet['B5'].value = beforesheet['A3'].value

outputwb = load_workbook(filename='aftertest.xlsx')
startwb = load_workbook(filename='beforetest.xlsx',keep_vba=True,data_only=True)
beforesheet = startwb.active
aftersheet = outputwb.active
setupAfter()
outputwb.save(filename=str(datetime.now().strftime("%Y%m%d_%H%M%S"))+"_aftertest.xlsx")

脚本输出

Updated with functionality I'm trying to replicate in Excel: Excel 功能

let's say you have this dataframe:

   a  b  c
0  1  2  3
1  4  5  6
2  7  8  9

and you are trying to copy A[1:2] to C[1:2] like this:

    a   b   c
0   1   2   3
1   4   5   4
2   7   8   7

Here is how you do this:

df['c'].iloc[1:2] = df['a'].iloc[1:2]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM