代码:
import pymysql import xlwt # 要连接的数据库信息 db_ip = 'localhost' db_port = 3306 db_user_name = 'root' db_password = '123456' db_name = 'mysql' # 要查询的数据库名和表名 search_db_name = 'sakila' search_table_names = ['staff','customer','address'] # 连接数据库 db = pymysql.connect(host=db_ip,port=db_port,user=db_user_name,password=db_password,db=db_name) # 新建一个excel book = xlwt.Workbook() # 添加一个sheet页 sheet = book.add_sheet('table_schema') line = 0 # 控制行 # 设置某列的单元格宽度 sheet.col(0).width = 8000 sheet.col(1).width = 4500 sheet.col(2).width = 3000 sheet.col(3).width = 2200 sheet.col(4).width = 2500 sheet.col(5).width = 2000 sheet.col(6).width = 10000 for search_table_name in search_table_names: # 拼接sql #SELEC \ #column_name, column_comment, data_type, character_maximum_length, is_nullable, column_default, column_type \ sql = "SELECT \ "+"'"+search_table_name+"`"+"_id" +"\ FROM \ "+"`" + search_table_name + "`"+ "\ where \ table_schema =" + "`" + search_db_name + "`" + \ "AND \ table_name=" + "`" + search_table_name + "`" # 输出数据表名 title_style = xlwt.XFStyle() # 初始化样式 title_font = xlwt.Font() # 创建字体 title_font.name = u'宋体' # 字体类型 title_font.height = 280 # 字体大小 200等于excel字体大小中的10 title_style.font = title_font # 设定样式 sheet.write_merge(line,line,0,6,search_table_name,title_style) line+=1 # 字段名的中文描述 des_style = xlwt.XFStyle() # 初始化样式 des_font = xlwt.Font() # 创建字体 des_font.name = u'宋体' # 字体类型 des_font.height = 240 # 字体大小 200等于excel字体大小中的10 des_style.font = title_font # 设定样式 description = ['列名',"字段类型","长度","是否为空","默认值","数据类型"] des_col = 0 for des in description: sheet.write(line, des_col, des, des_style) des_col += 1 line += 1 try: cursor = db.cursor() cursor.execute(sql) results = cursor.fetchall() # 输出字段的信息 content_style = xlwt.XFStyle() # 初始化样式 content_font = xlwt.Font() # 创建字体 content_font.name = u'宋体' # 字体类型 content_font.height = 240 # 字体大小 200等于excel字体大小中的10 content_style.font = content_font # 设定样式 for row in results: col = 0 #控制列 for s in row: # 再循环里面list的值,每一列 sheet.write(line, col, s, content_style) col+=1 line+=1 for i in [0,1,2,3,4,5,6]: sheet.write(line,1,"") line+=1 for i in [0,1,2,3,4,5,6]: sheet.write(line,1,"") line+=1 except Exception as e: print(e) print("Error: unable to fetch data") book.save(r"D:/Edge Install/kettle/table.xls") #保存到当前目录下 #db.close()
解决办法:
将 ' 改成 `
解释:
这两个点是不一样的,第一个是用键盘的Enter左边的键打出来的,第二个是用Esc下面的键打出来的
反单引号位置:不管什么输入法,**切换到英文状态下,左上角Esc键下边,Tab键上边,数字1键左边那个就可以打出反引号**,中文状态下是一个小圆点