用Python遍歷Excel的行和列,再寫入一個(gè)文件中

import pandas as pd

import numpy as np

filename ='demo_text.sql'

# 讀取excel

def readExcel(excelPath, sheet_name):

df = pd.read_excel(excelPath, sheet_name=sheet_name, header=None)

# 最大行

? ? nrows = df.shape[0]

print("行數(shù):\n" +str(nrows))

# 最大列

? ? ncols = df.columns.size

print("列數(shù):\n" +str(ncols))

for rowIndexin range(nrows):

source = df.iloc[rowIndex, 1]

npp = df.iloc[rowIndex, 2]

fuseCode = df.iloc[rowIndex, 3]

newFuseCode = df.iloc[rowIndex, 5]

sql =""

? ? ? ? print("source:" +str(source) +",npp:" +str(npp) +",fuseCode:" +str(fuseCode) +",newFuseCode:" +str(newFuseCode) +"\n")

if str(fuseCode) =="-" and str(npp) !="-":

if str(source) =="Others":

if str(newFuseCode) =="-":

sql ="update demo_table1 set reason = 'CancelOtherReInputReason' where fuse_policy_code = '" +str(

fuseCode) +"' ;"

? ? ? ? ? ? ? ? else:

sql ="update demo_table1 set new_fuse_code ='" +str(

newFuseCode).strip() +"',reason = 'CancelOtherReInputReason' where fuse_policy_code = '" +str(

fuseCode) +"' ;"

? ? ? ? ? ? if str(source) =="BACKDOOR" or str(source) =="Backdoor":

if str(newFuseCode) =="-":

sql ="update demo_table2?set reason = 'CancelOtherReInputReason' where npp = '" +str(npp) +"' ;"

? ? ? ? ? ? ? else:

sql ="update demo_table2?set new_fuse_code ='" +str(newFuseCode).strip() +"',reason = 'CancelOtherReInputReason' where npp = '" +str(npp) +"' ;"

? ? ? ? ? ? if str(source) =="Offline" or str(source) =="OFFLINE":

if str(newFuseCode) =="-":

sql ="update demo_table3?set reason = 'CancelOtherReInputReason' where associated_policy_code = '" +str(

npp) +"' ;"

? ? ? ? ? ? ? ? ? ? sql = sql +"\n" +"update demo_table4?set reason = 'CancelOtherReInputReason' where associated_policy_code = '" +str(

npp) +"' ;"

? ? ? ? ? ? ? ? else:

sql ="update demo_table3?set new_fuse_code ='" +str(

newFuseCode).strip() +"',reason = 'CancelOtherReInputReason' where associated_policy_code = '" +str(

npp) +"' ;"

? ? ? ? ? ? ? ? ? ? sql = sql +"\n" +"update demo_table4?set new_fuse_code ='" +str(newFuseCode).strip() +"',reason = 'CancelOtherReInputReason' where associated_policy_code = '" +str(

npp) +"' ;"

? ? ? ? ? ? print("==================================\n")

print(sql)

txt_file =open(filename, "a", encoding="utf-8")# 以寫的格式打開先打開文件

? ? ? ? ? ? txt_file.write(sql)

txt_file.write("\n")

txt_file.close()

# Main 入口

if __name__ =="__main__":

print("this is a excel \n")

readExcel("/Users/xiaobao/Desktop/rev_ops-manual.xlsx", "Sheet2")

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容