Convert a Python List to an Excel Column with openpyxl & pandas
This article walks through two practical methods for converting a Python list into the first column of an Excel file—first using openpyxl for direct cell writing, then leveraging pandas for a more concise DataFrame approach, plus additional pandas tricks for column manipulation.
Introduction
A fan asked how to turn a Python list containing many elements into the first column of an Excel sheet. Below are two solutions that demonstrate both a straightforward openpyxl approach and a concise pandas approach.
Solution 1 – openpyxl and pandas
Using openpyxl you can write each list element directly to a cell, while pandas allows creating a DataFrame and exporting it to Excel in a single line.
import openpyxl
excel_file = openpyxl.Workbook()
worksheet = excel_file.active
list1 = ['麦当', 'dcpeng', '月神', '王子', '冯诚', '亮哥', '沈复']
for i in range(len(list1)):
worksheet.cell(i+1, 1, list1[i])
excel_file.save('result.xlsx') import pandas as pd
list1 = ['麦当', 'dcpeng', '月神', '王子', '冯诚', '亮哥']
df = pd.DataFrame(list1)
df.to_excel('666.xlsx')Solution 2 – advanced pandas manipulations
The second contributor provides additional pandas techniques such as printing, transposing, replacing columns, adding new columns, and inserting columns at specific positions.
import pandas as pd
lst = list(range(10))
print(lst)
df = pd.DataFrame(lst)
print(df)
# df.to_excel('list.xlsx') # store as column
# df.T # transpose to row
df2 = df.T
print(df2)
new1 = [9,8,7,6,5,4,3,2,1,0]
new2 = [1,1,1,1,1,2,2,2,2,2]
new3 = [3,3,3,3,3,4,4,4,4,4]
# replace first column
df[0] = new1
# add a new column at the end
df["新"] = new2
# insert a column at the beginning (method 1)
col_names = df.columns.tolist()
col_names.insert(0, '新列1')
df3 = df.reindex(columns=col_names, fill_value=0)
print(df3)
# insert a column at the beginning (method 2)
df3.insert(0, '新列2', new3)
print(df3)Conclusion
The two methods successfully convert a Python list into the first column of an Excel file, offering both a low‑level cell‑by‑cell approach and a high‑level DataFrame solution, with additional pandas tricks for further column manipulation.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Python Crawling & Data Mining
Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
