I have a list of values in Python that I need to loop over and write to an excel file. The caveat here is that the values need to occupy column 1, 2, and 3 and then repeat again. This is what I have so far:
# Writing all information to Excel
workbook = xlsxwriter.Workbook('NEW DOCUMENT')
worksheet = workbook.add_worksheet()
worksheet.write(0,0,"Value 1")
worksheet.write(0,1,"Value 2")
worksheet.write(0,2,"Value 3")
row = 1
col = 0
for code in master_list_of_values:
worksheet.write(row, col, code)
col = 1
How do I go about stopping it at column 3 and then looping again?
Example:
List = [1,2,3,4,5,6,7,8,9]
In excel it'd look like:
Column 1 Column 2 Column 3
1 2 3
4 5 6
7 8 9
CodePudding user response:
You can use Pandas framework to structure your data, and after this save in excel.
The code below can solution your problem:
import numpy as np
import pandas as pd
example_list = [1,2,3,4,5,6,7,8,9]
df = pd.DataFrame() #Create empty dataframe
N = 3 #Number of collumns
split_list = np.array_split(example_list,N) #split the list in N frames
for i in range(N):
df[f'Column_{i}'] = split_list[i] #Create a collums for each frame
print(df)
df.to_excel("./output.xlsx") #write excel output