#Python中,对EXCEL文件的读写操作需要安装、导入几个第三方模块#xlrd模块:只能读取EXCEL文件,不能进行写操作#xlwt模块:只能进行写操作,但是不能是覆盖写操作(也就是修改Excel文件),一旦覆盖写操作,会报错#xlutils模块:由于xlrd只能读操作,xlwt不能覆盖写操作,因为涉及到修改Excel文件中的内容,我们需要借助xlutils模块print("==============读EXCEL文件=============")import xlrd## #打开一个EXCEL文件# rbook = xlrd.open_workbook("app_student.xls")## #获取EXCEL中的页# rsheet = rbook.sheet_by_index(0)# rsheet = rbook.sheet_by_name("sheet1")## #总行数# print(rsheet.nrows)## #总列数# print(rsheet.ncols)## #得到指定单元格的值# print(rsheet.cell(0,0)) # 结果输出:text:'编号',是一个xlrd.sheet.Cell类# print(rsheet.cell_value(0,0)) #结果输出字符串:编号# print(rsheet.cell(0,0).value) #结果输出字符串:编号## #遍历每一行的数据,返回一个list# for i in range(rsheet.nrows):# print(type(rsheet.row_values(i)))# print(rsheet.row_values(i))## #遍历每一列的数据,返回一个list# for i in range(rsheet.ncols):# print(type(rsheet.col_values(i)))# print(rsheet.col_values(i))print("============写EXCEL=============")import xlwtimport pymysql# wbook = xlwt.Workbook()# wsheet = wbook.add_sheet("sheet1")# wsheet.write(0,0,"编号")# wsheet.write(0,1,"姓名")# wsheet.write(0,2,"性别")# wbook.save("student.xls")print("==========导出数据到Excel方法一========")def export_excel(table_name): host, user, passwd, db = '127.0.0.1', 'jxz', '123456', 'jxz' coon = pymysql.connect(user=user, host=host, port=3306, passwd=passwd, db=db, charset='utf8') cur = coon.cursor() # 建立一个普通游标 #cur = coon.cursor(cursor=pymysql.cursors.DictCursor) # 建立字典游标 sql = 'select * from %s ;'%table_name cur.execute(sql) # 执行sql fileds = [filed[0] for filed in cur.description] #所有的字段,cur.description 是一个二维元组 all_data = cur.fetchall() #cur.fetchall()返回的是一个二维元组 #cur.fetchmany() # 能传入一个数,返回多少条数据 #cur.fetchone() # 返回一条数据 wbook = xlwt.Workbook() wsheet = wbook.add_sheet('sheet1') for col,filed in enumerate(fileds): #写表头的 wsheet.write(0,col,filed) row = 1 #行数 for data in all_data: #行 for col, filed in enumerate(data): # 控制列 wsheet.write(row, col, filed) row+=1#每次写完一行,行就加1 wbook.save('%s.xls'%table_name)export_excel('app_student')print("============修改Excel=============")import xlutils.copy #或者:from xlutils import copy#1、先用xlrd模块,打开一个excelnewbook = xlrd.open_workbook("app_student.xls")#2、通过xlutils这个模块里面copy方法,复制一份excelnewbook = xlutils.copy.copy(newbook)#3、获取sheet页newsheet = newbook.get_sheet(0)lis = ['编号','名字','性别','年龄','地址','班级','手机号','金币']for col,filed in enumerate(lis): newsheet.write(0,col,filed)newbook.save('app_student_new.xls')
1 pymysql 字典游标数据格式
2 [{
'gold': 999,
'grade':
'天蝎',
'phone':
'13444444443',
'id': 1,
'age': 0,
'addr':
'testsql',
'sex':
'1',
'name':
'AAA'}]
3
4
5 pymysql 普通游标数据格式:
6 ((1,
'AAA',
'1', 0,
'testsql',
'天蝎',
'13444444443', 999))
转载于:https://www.cnblogs.com/mtszw/p/9021877.html
转载请注明原文地址: https://mac.8miu.com/read-15825.html