2016-10-07 90 views
0

我是Python新手,我正在將Excel數據導入到PostgreSQL中。我的Excel中有空白空白,用於Traffic和Week_Ending的列。 Try語句似乎對Week_Ending功能正常,但對於Traffic,它會拋出一個錯誤。我檢查了Excel,並且由於其中一個單元中的單個空白空白而顯示錯誤。我認爲它適用於兩列,但不適用於流量。任何人都可以提供援助請。嘗試聲明錯誤

import psycopg2 
import xlrd 
import datetime 
book = xlrd.open_workbook("T:\DataDump\8888.xlsx") 
sheet = book.sheet_by_name("Builder_Traffic") 
database = psycopg2.connect (database = "***", user="*") 

cursor = database.cursor() 
delete = """Drop table if exists "Python".buildertraffic""" 
print (delete) 
mydata = cursor.execute(delete) 




cursor.execute('''CREATE TABLE "Python".buildertraffic 
    (Builder_Name varchar(55), 
Traffic integer, 
Week_Ending date, 
Project_ID integer 
    );''') 

print "Table created successfully" 

query = """INSERT INTO "Python".buildertraffic (Builder_Name, Traffic, Week_Ending, Project_ID) 
VALUES (%s, %s, %s, %s)""" 

for r in range(1, sheet.nrows): 
    Builder_Name = sheet.cell(r,0).value 
    Traffic = None 
    try: 
     Traffic = (sheet.cell(r,1).value) 
    except: 
     pass 
    Week_Ending = None 
    try: 
     Week_Ending = xlrd.xldate.xldate_as_datetime(sheet.cell(r,2).value,book.datemode) 
    except: 
     pass 
    Project_ID = sheet.cell(r,3).value 

values = (Builder_Name, Traffic, Week_Ending, Project_ID) 
cursor.execute(query, values) 

cursor.close() 
database.commit() 
database.close() 

print "" 
print "All Done! Bye, for now." 
print "" 
columns = str(sheet.ncols) 
rows = str(sheet.nrows) 
print "I just imported Excel into postgreSQL" 

和錯誤顯示爲:

Traceback (most recent call last): 
File "C:\Users\aqureshi\Desktop\Programming\PythonSQLNew\BuilderTraffic.py", line 47, in <module> 
DataError: invalid input syntax for integer: " " 
LINE 2: VALUES ('American Legend Homes', ' ', NULL, 2.0) 
            ^
+0

您沒有向我們展示您的整個程序。您向我們展示瞭如何從電子表格中獲取值,但不是將這些值插入到數據庫中的(重要的!)部分。 –

回答

0

你應該檢查該列中的空白或空的字符串:

traffic = sheet.cell(r, 1).value 

我沒有在你的代碼中看到您如何實際執行查詢,但是應該將int中的流量封裝爲解析字符串中的整數:How to convert strings into integers in Python?

try: 
    traffic = int(sheet.cell(r, 1).value) 
except: 
    traffic = -1 # or 0? some value to indicate this has NO traffic. 
+1

謝謝omouse我編輯了我原來的帖子。這是我用於其他表格的原始代碼和完整代碼,並且它工作正常。 –

+0

解析Excel文件時總是假設最差。測試空字符串,虛假空白,無效格式。如果你能想象它,你會發現它。如果你無法想象它,你會發現它。 :-) – intrepidhero

+0

@PLearner是的,那麼你的問題是,你需要一個良好的默認值的交通和其他值時解析他們失敗,像'Traffic = 0'在'except'塊應該工作。 –