我已经解决了许多关于同一问题的问题,但是没有找到令人满意的答案。
下面是一堆用于将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个不同的列表中。
谢谢
答案 0 :(得分:0)
在代码的下半部分进行了一些更改,我认为它工作得很好。
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")
任何进一步的改进都是很明显的。
谢谢