Home » excel » Reading data from Excel sheets and building SQL statements, writing to output file in Python

Reading data from Excel sheets and building SQL statements, writing to output file in Python

Posted by: admin May 14, 2020 Leave a comment

Questions:

I have an excel book with a couple of sheets. Each sheet has two columns with PersonID and LegacyID. We are basically trying to update some records in the database based on personid. This is relatively easy to do TSQL and I might even be able to get it done pretty quick in powershell but since I have been trying to learn Python, I thought I would try this in Python. I used xlrd module and I was able to print update statements. below is my code:

import xlrd

book = xlrd.open_workbook('D:\Scripts\UpdateID01.xls')
sheet = book.sheet_by_index(0)

myList = []
for i in range(sheet.nrows):
   myList.append(sheet.row_values(i))


outFile = open('D:\Scripts\update.txt', 'wb')

for i in myList:
    outFile.write("\nUPDATE PERSON SET LegacyID = " + "'" + str(i[1]) + "'" + " WHERE personid = " + "'" + str(i[0])
                  + "'")

Two problems – when I read the output file, I see the LegacyID printed as float. How do I get rid of .0 at the end of each id? Second problem, python doesn’t print each update statement in a new line in the output text file. How to I format it?

Edit: Please ignore the format issue. It did print in new lines when I opened the output file in Notepad++. The float issue still remains.

How to&Answers:

Can you turn the LegacyID into ints ?

i[1] = int(i[1])

outFile.write(“\nUPDATE PERSON SET LegacyID = ” + “‘” + str(i[1]) + “‘” + ” WHERE personid = ” + “‘” + str(i[0])
+ “‘”)

Answer:

try this..

# use 'a' if you want to append in your text file
outFile = open(r'D:\Scripts\update.txt', 'a')

for i in myList:
    outFile.write("\nUPDATE PERSON SET LegacyID = '%s' WHERE personid = '%s'" %( int(i[1]), str(i[0])))

Answer:

Since you are learning Python (which is very laudable!) you should start reading about string formatting in the Python docs. This is the best place to start whenever you have a question light this.

Hint: You may want to convert the float items to integers using int().