shan
shan

Reputation: 11

convert txt file to different sheet in excel

I wrote a code that passed information from a text file to excel.I sorted according to specific parameters I want to take from the file ("X,Y,O,P,E"). I neet to pass this information to sheet number 2. How can i do that ?

import xlsxwriter

def readFile(_path):
    f = open(_path, "r")
    return f.readlines()

def test():
    file = open("Test.txt", 'r')

    data = []
    line_data = ""

    for line in file:
        if "_____ X" in line:
            line_data = line[24:].replace("\t", "").replace("\n", "").split(":")[0]
        elif "Y:" in line:
            line_data = line.replace("\t", "").replace("\n", "").split(" ")[1]
        elif "O:" in line:
            line_data = line.replace("\t", "").replace("\n", "").split(" ")[1]
        elif "P:" in line:
            line_data = line.replace("\t", "").replace("\n", "").split(" ")[1]
        elif "E=" in line:
            line_data = line[21:].replace("\t", "").replace("\n", "").split[0]

        if len(line_data) > 0:
            data.append(line_data)
        line_data = ""

    writeToxlsx(data)

def writeToxlsx(data):
    _output_path = "Book1.xlsx"
    workbook = xlsxwriter.Workbook(_output_path)
    worksheet = workbook.add_worksheet()
    row = 0
    for item in data:
        worksheet.write(row, 1, item)
        row += 1
    workbook.close()

test()

Upvotes: 0

Views: 113

Answers (1)

Nesha25
Nesha25

Reputation: 408

Are you trying to write to an existing sheet? If so, you need to use openpyxl, not xlsxwriter. How to write/update data into cells of existing XLSX workbook using xlsxwriter in python

If you are writing to a new sheet, then where you have the line:

worksheet = workbook.add_worksheet()

instead write:

worksheet = workbook.add_worksheet('The Sheetname You Want')

or if you really need it to be the second sheet, you will have to create a dummy sheet for the front page. You can use the example provided here: Python XlsxWriter - Write to many sheets

Upvotes: 1

Related Questions