Search code examples
pythonexcelxlrdxlutils

Python - Appending data from one xlsx to another existing xlsx


I have gone through many existing questions about the same, but didn't find any satisfactory answer to my problem.

Here's a bunch of code for appending values from xlsx to existing xlsx:

from xlutils.copy import copy
import xlrd

wb = xlrd.open_workbook("cik_list.xlsx")

sheet = wb.sheet_by_index(0)

X0 = []; X1 = []; X2 = []; X3 = []; X4 = []; X5 = []
for row in range(1, sheet.nrows):
    X0.append(sheet.cell_value(row, 0))
    X1.append(sheet.cell_value(row, 1))
    X2.append(sheet.cell_value(row, 2))
    X3.append(sheet.cell_value(row, 3))
    X4.append(sheet.cell_value(row, 4))
    X5.append(sheet.cell_value(row, 5))

rb = xlrd.open_workbook("Output Data Structure.xlsx")

r_sheet = rb.sheet_by_index(0)

r = sheet.nrows 
wb1 = copy(rb)

sheet1 = wb1.get_sheet(0)

row=1
while(row < r):
    row=1
    for x in X0:
        sheet1.write(row, 0, x)
        row+=1
    row=1
    for x in X1:
        sheet1.write(row, 1, x)
        row+=1
    row=1
    for x in X2:
        sheet1.write(row, 2, x)
        row+=1
    row=1
    for x in X3:
        sheet1.write(row, 3, x)
        row+=1
    row=1
    for x in X4:
        sheet1.write(row, 4, x)
        row+=1
    row=1
    for x in X5:
        sheet1.write(row, 5, x)
        row+=1

wb1.save("Output Data Structure.xls")

Is there any way out I can save the Output Data Structure as .xlsx file without changing the first half of the code i.e. reading the values from cik_list.xlsx and storing them into 6 different lists.

Thanks


Solution

  • With a few changes in the lower half of the code, I got it working absolutely fine.

    from openpyxl import load_workbook
    
    rb = load_workbook("Output Data Structure.xlsx")
    
    sheet1 = rb.active
    
    r = sheet.nrows 
    
    row=2
    while(row <= r):
        row=2
        for x in X0:
            sheet1.cell(row, 1, x)
            row+=1
        row=2
        for x in X1:
            sheet1.cell(row, 2, x)
            row+=1
        row=2
        for x in X2:
            sheet1.cell(row, 3, x)
            row+=1
        row=2
        for x in X3:
            sheet1.cell(row, 4, x)
            row+=1
        row=2
        for x in X4:
            sheet1.cell(row, 5, x)
            row+=1
        row=2
        for x in X5:
            sheet1.cell(row, 6, x)
            row+=1
    
    rb.save("Output Data Structure.xlsx")
    

    Any further improvements would be highly appreciable.

    Thanks