day7_讀excel內容,寫到數據庫裏
阿新 • • 發佈:2018-03-11
作業 open xls conn class 文件 nco cut read
# 需求分析:
# 1、讀出stu.xls文件裏的內容
# 2、判斷,如果是1用已交作業表示,如果是空用未交作業表示
# 3、拼接sql
# 4、插入到數據庫裏的jxz_stu表裏,四個字段為name,c1,c2,c3
def con_mysql(sql):
import pymysql
conn = pymysql.connect(host = ‘211.149.218.16‘,user = ‘jxz‘,password = ‘123456‘,db = ‘jxz‘,charset = ‘utf8‘)
cur = conn.cursor()
cur.execute(sql)
res = cur.fetchall()
cur.close()
conn.close()
return res
def is_send(a): # 判斷是否交作業了
if a:
return ‘已交作業‘
else:
return ‘未交作業‘
def readexcel(filename):
import xlrd
book = xlrd.open_workbook(filename) # 打開指定的excel表
sheet = book.sheet_by_name(‘Sheet1‘) # 讀取Sheet1頁的內容
# print(sheet.nrows) # 打印出excel表裏sheet1頁的行數
# print(sheet.ncols) # 打印出excel表裏sheet1頁的列數
# print(sheet.cell(1,1)) # 獲取第1行,第1列的值,打印出text:‘沙河‘
# print(sheet.cell(1,1).value) # 獲取到沙河
for i in range(sheet.nrows): # 按照行循環
lines= sheet.row_values(i) # 每行的內容
name = lines[0]
c1 = is_send(lines[1])
c2 = is_send(lines[2])
c3 = is_send(lines[3])
sql = ‘insert into jxz_stu values("{name}","{c1}","{c2}","{c3}";)‘.format(name = name,c1 = c1,c2 = c2,c3 = c3)
con_mysql(sql)
readexcel(‘stu.xls‘)
day7_讀excel內容,寫到數據庫裏