Skip to content Skip to sidebar Skip to footer

Copying Text From File To Specified Excel Column

I've got a text file, say, 'A.txt' and an Excel file, say 'B.xlsx'. My goal is to copy all the text from A.txt to a specified column in B.xlsx using a python script. For example, l

Solution 1:

Use the win32com library to interface directly with microsoft excel, as you are working in excel:

import win32com.client

#Read text file lines into list
f = open("A.txt")
text_contents = f.readlines()

# Open excel and your workbook
col = 2 # column B
excel=win32com.client.Dispatch("Excel.Application")
excel.Visible=True # Note: set to false when scripting, only True for this example
wb=excel.Workbooks.Open('B.xlsx')
ws = wb.Worksheets('Sheet1')

#Write text contents to column range
ws.Range(ws.Cells(col ,1),ws.Cells(col,len(text_contents))).Value = text_contents

#Save the workbook and quit
wb.Close(True)
excel.Application.Quit() 

Post a Comment for "Copying Text From File To Specified Excel Column"