Loop & Write Excel Data with openpyxl

You can loop through rows in an Excel spreadsheet using the iter_rows() method from the openpyxl module and write data using the cell() method. Here’s an example:

from openpyxl import Workbook

# 创建一个新的工作簿
workbook = Workbook()

# 选择活动的工作表
sheet = workbook.active

# 创建要写入的数据列表
data = [['姓名', '年龄', '性别'],
        ['张三', 20, '男'],
        ['李四', 25, '男'],
        ['王五', 30, '女']]

# 循环遍历数据列表,并将数据写入单元格
for row in data:
    sheet.append(row)

# 保存工作簿
workbook.save("data.xlsx")

In the above example, we start by creating a new workbook and selecting the active worksheet. Next, we create a list containing the data to be written. Then, we use the append() method to iterate through the data list and write each row of data to cells in the worksheet. Finally, we save the workbook to a file named “data.xlsx”.

I hope this helps you!

bannerAds