Home > Mobile >  Writing List to specific column in excel
Writing List to specific column in excel

Time:10-14

I have data in list and I want to write the list to specific columns in excel. I have list = [Apple, Pear, Fruit] I need to write this to excel as Column A = Apple, Column C = Pear, Column F = Fruit. When I use append, it is writing to Column A, B and C. But that's not what I want.

Here is my code:

import openpyxl

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

CodePudding user response:

You can do this using 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)

CodePudding user response:

Here are 4 ways to set values in different columns in a row using openpyxl.
These will create a row with Column A = Apple, Column C = Pear, and Column F = Fruit.

  1. Append new row with list of values (use None value to skip a column)
fruit = ['Apple', None, 'Pear', None, None, 'Fruit']
sheet.append(fruit)
  1. Append new row using dictionary specifying row letter.
fruit = {'A' : 'Apple', 'C' : 'Pear', 'F' : 'Fruit'}
sheet.append(fruit)
  1. set values in the cells using absolute referencing
sheet["A1"] = "Apple"
sheet["C1"] = "Pear"
sheet["F1"] = "Fruit"
  1. Specify the column and next row by index
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
  • Related