python write a list to multiple columns in excel
Question:
I am trying to write many columns in excel. I have a list let’s say as below
list1=[1,2,3,4,5]
the other list will be like
list2=['a','b','c']
I will have many different sized(length) lists which is why I cannot create dataframe
in pandas and write it.
list3=['1a','2b','3c','4d']
I want it in excel be like
I am not sure which framework to use, openpyxl
or pandas
which will solve this issue
EDIT for user @Timeless
I have used your suggestion in this way;
with pd.ExcelWriter(var_path, engine='openpyxl', mode='r+', if_sheet_exists='overlay') as writer:
book = load_workbook(var_path)
current_sheet = book[var_sheetname]
Column_H = current_sheet['H']
try:
maxrow = max(c.row for c in Column_H if c.value is not None)
except ValueError:
maxrow = 1
print(var_sheetname,maxrow,'writing docs')
var_inp.to_excel(writer,startrow=maxrow,columns=Column_H,sheet_name=var_sheetname,index=False,header=False)
Answers:
Make a nested list :
L = [list1, list2, list3]
Then you can use Worksheet.append
:
from openpyxl import Workbook
wb = Workbook()
ws = wb.active
for sub_list in L:
ws.append(sub_list)
wb.save("book1.xlsx")
Or with pandas :
import pandas as pd
pd.DataFrame(L).to_excel("book2.xlsx", header=False, index=False)
Output (spreadsheet) :
I am trying to write many columns in excel. I have a list let’s say as below
list1=[1,2,3,4,5]
the other list will be like
list2=['a','b','c']
I will have many different sized(length) lists which is why I cannot create dataframe
in pandas and write it.
list3=['1a','2b','3c','4d']
I want it in excel be like
I am not sure which framework to use, openpyxl
or pandas
which will solve this issue
EDIT for user @Timeless
I have used your suggestion in this way;
with pd.ExcelWriter(var_path, engine='openpyxl', mode='r+', if_sheet_exists='overlay') as writer:
book = load_workbook(var_path)
current_sheet = book[var_sheetname]
Column_H = current_sheet['H']
try:
maxrow = max(c.row for c in Column_H if c.value is not None)
except ValueError:
maxrow = 1
print(var_sheetname,maxrow,'writing docs')
var_inp.to_excel(writer,startrow=maxrow,columns=Column_H,sheet_name=var_sheetname,index=False,header=False)
Make a nested list :
L = [list1, list2, list3]
Then you can use Worksheet.append
:
from openpyxl import Workbook
wb = Workbook()
ws = wb.active
for sub_list in L:
ws.append(sub_list)
wb.save("book1.xlsx")
Or with pandas :
import pandas as pd
pd.DataFrame(L).to_excel("book2.xlsx", header=False, index=False)
Output (spreadsheet) :