Nov-09-2022, 03:13 PM
The easiest way to do the conversion is open the text file in excel and save as a spreadsheet. Using pandas isn't much harder.
import pandas as pd pd.read_csv("test.txt").to_excel("test.xlsx", index=False)Your odd text file format with all the extra spaces in the first row messes this up. Some special input processing is required.
import pandas as pd with open("test.txt", "r") as file: column_names = next(file).split() df = pd.read_csv(file, sep=" ", names=column_names) df.to_excel("test.xlsx", index=False)You also wanted to do some formatting in the excel file. That requires creating an excel writer object and adding styles.
import pandas as pd with open("test.txt", "r") as file: column_names = next(file).split() df = pd.read_csv(file, sep=" ", names=column_names) # Create a writer for doing formatting writer = pd.ExcelWriter("test.xlsx", engine="xlsxwriter", ) df.to_excel(writer, sheet_name="Data", index=False) sheet = writer.sheets["Data"] # Set column widths sheet.set_column(0, len(column_names)-1, 25) # Set font for column headers. May not need because writer already # uses a special font for the header. header_format = writer.book.add_format({'bold':True, 'font_size':14}) for index, name in enumerate(column_names): sheet.write(0, index, name, header_format) writer.save()