python - 如何将列表值分配给excel文件中的列?

标签 python excel pandas openpyxl xlsxwriter

我有一个列表值,并希望将其分配到 excel 文件中的列中。我要更改的值在表 6 中。
我糟糕的代码看起来像这样我能做的最好的事情是首先尝试将 AF6:AF22 更改为固定值 5,希望我可以将其更改为列表。
但是有没有一种简单的方法可以将 AF6:AF22 值更改为列表?
简单的 ws['AF6:AF22'] = l?


from openpyxl import Workbook
import pandas as pd
from openpyxl import load_workbook

l = list(range(5))

FilePath = 'excel_file.xlsx'
wb = load_workbook(FilePath)

ws = wb.worksheets

sheet_number = 6 

for sheet_number in ws.iter_cols('AF6:AF22'):
    for cell in sheet_number:
        cell.value = 5

最佳答案

选项 1
嗨 - 我在这里添加了一种更快的方法。这可能会更好,因为它避免了 for 循环并一次更新一个单元格。

from openpyxl import Workbook
import pandas as pd
from openpyxl import load_workbook

l = list(range(17))  #The list - You can replace l with whatever you need

with pd.ExcelWriter('excel_file.xlsx', mode='a', engine = 'openpyxl') as writer: 
    pd.DataFrame(l).to_excel(writer, sheet_name='Sheet6', startrow = 5, startcol= 31, index=False, header=None)
选项 2
您可以使用下面的代码来做您需要的事情。添加评论,让您了解我的逻辑......
from openpyxl import Workbook
import pandas as pd
from openpyxl import load_workbook

l = list(range(17))  #The list - You can replace l with whatever you need

FilePath = 'excel_file.xlsx'
wb = load_workbook(FilePath)

ws = wb.worksheets[5]  #Worksheet 5 is the 6th sheet as numbering starts from zero
for i in range(6,23):  # Column numbers 6 through 22
    ws.cell(row=i, column=32).value = l[i-6]  #Write to cell in AF = column 32
    
wb.save("excel_file.xlsx")

关于python - 如何将列表值分配给excel文件中的列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72549633/

相关文章:

python - Tkinter:抓取和焦点有什么区别?

VBA Office2010 Shapes.PasteSpecial 失败

vba - 自动在小数点分隔符后写入 2 位数字

python - Pandas 更有效地过滤包含空字段的组?

python - 在 pandas 中追加到现有的 df 中,而不更改 df 的 id?

python - 标准输入 标准输出 python : how to reuse the same input file twice?

python - 在多个列上应用函数来创建多个新列

python - 我应该如何在 tensorflow 中规范化图像?

python - Pandas +xlsx : format cells based on another dataframe

python - Pandas 删除值小于给定值的行