1

For my master thesis I've created a script.

Now I want that output to be printed to an excel sheet - I read that xlwt can do that, but examples I've found only give instructions to manually print one string to the file. Now I started by adding that code:

import xlwt

new_workbook = xlwt.Workbook(encoding='utf-8')
    new_sheet=new_workbook.add_sheet("1")

Now I have no clue where to go from there, can you please give me a hint? I'm guessing I need to somehow start a loop where each time it writes to a new line for each iteration it takes, but am not sure where to start. I'd really appreciate a hint, thank you!

2
  • Have you considered using pandas.Dataframe.to_excel() ? pandas.pydata.org/pandas-docs/stable/reference/api/… Commented Jun 25, 2021 at 6:50
  • There are some .write(..) and .save(..) methods in the api doc. But using pandas.Dataframe.to_excel() as @Nathan says seems more efficient if it is good enough for you. Commented Jun 25, 2021 at 7:40

3 Answers 3

2

since you are using pandas you can use to_excel to do that.

The usage is quite simple : Just create a dataframe with the values you need into your excel sheet and save it as excel sheet :

import pandas as pd

df = pd.DataFrame(data={
    'col1':["output1","output2","output3"],
    'col2':["output1.1","output2.2","output3.3"]
    })

df.to_excel("excel_name.xlsx",sheet_name="sheet_name",index=False)
Sign up to request clarification or add additional context in comments.

1 Comment

That is obviously the right approach unless you have a specific reason for wanting to manipulate excel directly.
1

What you need is openpyxl: https://openpyxl.readthedocs.io/en/stable/

from openpyxl import Workbook
wb = openpyxl.load_workbook('your_template.xlsx')
sheet = wb.active
sheet.cell(row=4, column=2).value = 'what you wish to write'
wb.save('save_file_name.xlsx')
wb.close()

Comments

0

Lets say you would save every result to a list total_distances like

total_distances = []
for c1, c2 in coords:
    # here your code
    total_distances.append(total_distance)

and than save it into worksheet as:

with Workbook('total_distances.xlsx') as workbook:
    worksheet = workbook.add_worksheet()
    data = ["Total_distance"]
    row = 0
    worksheet.write_row(row,0,data)
    for i in total_distances:
        row += 1
        data = [round(i,2)]
        worksheet.write_row(row,0,data)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.