将列表写入 excel 中的特定列

Writing List to specific column in excel

我在列表中有数据,我想将列表写入 excel 中的特定列。 我有 list = [Apple, Pear, Fruit] 我需要将其写入 excel,因为 A 列 = 苹果,C 列 = 梨,F 列 = 水果。 当我使用 append 时,它正在写入 A、B 和 C 列。但这不是我想要的。

这是我的代码:

import openpyxl

path = r"C:\Folder\Filename.xlsx"
wb = load_workbook(path)
sheet = wb[sheet_name]
list = [Apple, Pear, Fruit]
sheet.append(list)

这里有 4 种方法可以使用 openpyxl 在一行中的不同列中设置值。
这些将创建一行,A 列 = Apple,C 列 =梨和 F 列 = 水果。

  1. 用值列表追加新行(使用 None 值跳过一列)
fruit = ['Apple', None, 'Pear', None, None, 'Fruit']
sheet.append(fruit)
  1. 使用指定行字母的字典追加新行。
fruit = {'A' : 'Apple', 'C' : 'Pear', 'F' : 'Fruit'}
sheet.append(fruit)
  1. 使用绝对引用在单元格中设置值
sheet["A1"] = "Apple"
sheet["C1"] = "Pear"
sheet["F1"] = "Fruit"
  1. 按索引指定列和下一行
row = sheet.max_row + 1
sheet.cell(row=row, column=1, value="Apple")  # => column A
sheet.cell(row=row, column=3, value="Pear")   # => column C
sheet.cell(row=row, column=6, value="Fruit")  # => column F

您可以使用 xlsxwriter:

import xlsxwriter

fdata = ['Apple', 'Pear', 'Fruit']
column = [1, 3, 6]

with xlsxwriter.Workbook('file.xlsx') as workbook:
    file = workbook.add_worksheet()

    for col, data in zip(column, fdata):
        file.write(0, col-1, data)