Python操纵Excel,数据库

操作excel
xlwt:写入excel表格 ,用这个之前需要先导入模块 xlwt: import xlwt
xlrd:读取excel,用这个之前需要先导入模块 xlwt:import xlrd
注意:excel表中取值也是用索引,也是从0开
比如:(行的索引,列的索引)
(0,0)表示第一行,第一个空格
(0,3)表示第一行的第4个空格里面的值
(3,0)表示第4列,第一个空格里面的值
excel写数据'''
execel=xlwt.Workbook() #新建一个excle表格
sheet=execel.add_sheet('sheet1') #创建一个sheet
#在sheet中写入数据,0,0,表示excel表格中的第一行,第一列
sheet.write(0,0,'username')
execel.save('0519.xls') #保存这个excel文件,名称叫0529.xls,此时打开文件第一行第一列写入了数据'username'
'练习
将一个数组中的每个元素依次写入excel表格的第一行

list=['username','password','15902127953']


execel =xlwt.Workbook() # 新建一个excle表格
sheet = execel.add_sheet('sheet1') # 创建一个sheet
for i in range(len(list)):
'''list中的元素用list[下标]表示'''
sheet.write(0, i,list[i]) # 循环list,依次写入数据
execel.save('0519.xlsx') #循环结束之后,再保存excel。此时打开excel,第一行数据就是list中的每个元素



'''将list中的值依次写入第一列'''
excel=xlwt.Workbook()
sheet=excel.add_sheet('test')
for i in range(len(list)):
sheet.write(i,0,list[i])
excel.save('0519.xls')


xlrd:读取excle中的数据
'''
excel=xlrd.open_workbook('0519.xls') #先打开一个已有的excel文件
sheet=excel.sheet_by_index(0) #获得第一个sheet的数据

print(sheet.nrows) #打印excle的行数
print(sheet.ncols) #打印excle的列数

print(sheet.row_values(0,1,2))
#上面的0表示第一行,1,2表示从第几格取到第几格(类似切片,包含开始,不包含结尾)
#所以上面取的值应该是第一行的,第二格里面的值

print(sheet.col_values(0,1,2))




'''python连接数据库mysql'''
首先要导入 pymysql 模块

def connect():
'''连接数据库'''
db=pymysql.connect('localhost','root','test123456','robot')
return db

def create_table(db):
'''创建表'''
cursor = db.cursor()
sql="""
create table test(
id CHAR(20),
name CHAR (12),
number VARCHAR (13)
)
"""
cursor.execute(sql)


def insert_data(db):
'''表中插入数据'''
cursor = db.cursor()

sql='''insert into test values
(001,'jianhaohe',12345678978),
(002,'zhoujielun',1234567989)
'''
cursor.execute(sql)
db.commit()


def query_db(db):
'''查询数据'''
cursor = db.cursor()
sql='''select * from test
'''
cursor.execute(sql)
res=cursor.fetchall()
data=res[0][2]
print(data)
print(res)

def close_db(db):
'''关闭数据库'''
db.close()


def main():
'''方法执行顺序'''
db=connect()
create_table(db)
insert_data(db)
query_db(db)
close_db(db)

if __name__=='__main__':
main()
原文地址:https://www.cnblogs.com/cyq0528/p/9877688.html