How to read txt file as input and write into Excel using Python?

How to read txt file as input and write into Excel using Python?

I am trying to read txt file and write into Excel using Python.

I tried this code but it is not working: import xlwt, openpyxl. Import xlrd. Workbook = openpyxl.Workbook() sheet = workbook.active row = 1. Txtfile = open("C:UsersuserDesktop. Ew.txt", "r") for line in txtfile.readlines(): sheet.cell(row = row, column = 0).save("C:UsersuserDesktopexcel.xlsx")
When I run the code I get error like this: Traceback (most recent call last): File "C:UsersuserDesktop. Ew.txt", line 1, in NameError: name 'txtfile' is not defined. Here's a much better way of doing things: import openpyxl. Workbook = xlwt.Workbook() sheet = workbook.addsheet('Inputs') sheet.write(0, "What is your name?") sheet.write(1, 0, "Hello") workbook.save('inputs.xlsx')

Here, we create a new worksheet called Inputs and put a single cell in the first row and column. We then print out a question and a reply. The file gets saved automatically.

In case you are unfamiliar with the syntax, the following line: sheet.write(0, "What is your name?") is equivalent to the following:

How do I iterate an Excel spreadsheet in Python?

I have code that retrieves all the cells in column 1 and copies it to a new sheet.

In the new sheet, I then copy cells 1:8 in the old sheet and cells A1 through H10 in the new one. I'm currently using xlrd but it's taking too long. I'd like to iterate through all the cell locations and copy it to a new sheet.

Import xlrd. Wb = xlrd.openworkbook('Book1.xls')
Worksheet1 = wb.sheetbyname('Sheet1') worksheet2 = wb.sheetbyname('Sheet2') newsheet = 'MyExcelNewSheetName'. Newsheetloc = wb.addsheet(newsheet) cell1 = newsheetloc.rowiterator(cell2, 'A') for cell in cellslist: worksheet1.write(cell, cell3) #Add columns and rows as necessary as shown above. The problem is, I need to paste the new columns. How can I do that? Currently, I only know how to paste down.write(cell4, cell4) This puts cell4 in column1 of the new sheet. Instead, I want it to move down two rows below that cell and be placed in column2 of the new sheet.

Does anyone have any suggestions?

Related Answers

How can I open a PDF file in Excel for free?

How to Convert PDF to Excel for Free. Convert PDF to Exce...

How do I pull data from a website into Excel?

This is a basic question. Everyon...

How do I write to an existing Excel file in Python?

Let's take a step back. In this post, we'll write a simple Python script...