Python - 将数据从一个 xlsx 附加到另一个现有的 xlsx

Python - Appending data from one xlsx to another existing xlsx

我已经解决了很多关于相同问题的现有问题,但没有找到任何满意的答案。

这里有一堆代码,用于将值从 xlsx 附加到现有的 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")

有什么办法可以将 Output Data Structure 保存为 .xlsx 文件而不更改代码的前半部分,即从 cik_list.xlsx 读取值并将它们存储到 6 个不同的列出。

谢谢

在代码的下半部分做了一些改动,我让它工作得非常好。

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")

如有任何进一步改进,我们将不胜感激。

谢谢