简体   繁体   English

在Excel中创建新工作表并使用openpyxl写入数据

[英]Creating new sheet in excel and writing data with openpyxl

I have already existing excel file and at the beginning in my code i import data from first sheet. 我已经有一个excel文件,在代码的开头,我从第一张纸中导入数据。

Now i cant write points from two variables (xw, yw) into new sheet in excel to two colmuns (A1-A[Q] and B1-B[Q]). 现在,我无法将两个变量(xw, yw)点写入excel中的两个新列(A1-A [Q]和B1-B [Q])。

xw and yw are arrays consisting of float numbers (example: 1.223, 2.434 etc.). xwyw是由浮点数组成的数组(例如:1.223、2.434等)。

Q = len(xw)
wb.create_sheet('Points')
sheet2 = wb.get_sheet_by_name('Points')
for q in range(1,Q):
    sheet2["A[q]"]=xw[q]
    sheet2["B[q]"]=yw[q]
wb.save('PARAMS.xlsx') 

EDIT: 编辑:

I want to fill third column with zeros (C1-CQ). 我想用零(C1-CQ)填充第三列。 My code is below, but its start from C2, not C1. 我的代码在下面,但是它是从C2而不是C1开始的。 I did sheet2[f"C{1}"]=0 but it looks bad. 我做了sheet2[f"C{1}"]=0但是看起来很糟糕。 What is the solution? 解决办法是什么?

Q = len(xw)
zw= np.zeros(Q)
sheet2 = wb.create_sheet('Points')
sheet2[f"A{1}"]=0
sheet2[f"B{1}"]=T_r
sheet2[f"C{1}"]=0
for i, row in enumerate(sheet2.iter_rows(min_row=2, max_col=3, max_row=Q+1)):
    row[0].value = xw[i]
    row[1].value = yw[i]
    row[2].value = zw[i]
wb.save('PARAMS.xlsx')

You are trying to acces literally the cell "A[q]" which of course does not exist. 您试图从字面上访问单元格"A[q]" ,该单元格当然不存在。 Change it to f"A{q}" (The same to B of course). 将其更改为f"A{q}" (当然与B相同)。

Also, openpyxl uses 1-based indexing so it means you will skip your first elements from the lists. 另外, openpyxl使用基于1的索引,因此这意味着您将跳过列表中的第一个元素。 Therefore you should do: 因此,您应该执行以下操作:

for q in range(Q):
    sheet2[f"A{q+1}"] = xw[q]
    sheet2[f"B{q+1}"] = yw[q]

Alternatively, you could use the API of openpyxl to access the cells using iter_rows and enumerate : 另外,您可以使用openpyxl的API通过iter_rowsenumerate来访问单元格:

for i, row in enumerate(sheet2.iter_rows(min_row=1, max_col=2, max_row=Q)):
    row[0].value = xw[i]
    row[1].value = yw[i]

Notice that create_sheet also returns the sheet created so you can simply do: 请注意, create_sheet返回创建的工作表,因此您可以执行以下操作:

sheet2 = wb.create_sheet('Points')

Where possible try and and avoid your own counters. 尽可能尝试避免使用自己的计数器。 openpyxl uses 1-based indexing for rows and columns so it can be confusing to mix this with Python's standard 0-based indexing. openpyxl对行和列使用基于1的索引,因此将其与Python的基于0的标准索引混在一起可能会造成混淆。 You can usually avoid this by looping directly over iterables like lists and arrays. 通常,您可以通过直接遍历列表和数组等可迭代对象来避免这种情况。

for idx, a, b in enumerate(zip(xw, yw), 1):
   ws.cell(row=idx, column=1, value=a)
   ws.cell(row_idx, column=2, value=b) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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