1.利用pandas模块

# encoding: utf-8
import time
import pandas as pd
import pymysql def getrel(sql):
'''
连接mysql数据库,根据条件查询出来我们所需要数据
:return: 根据条件从sql查询出来的数据
'''
conn = pymysql.connect(host='localhost', user='root', password='',
db='db_test', charset='utf8mb4')
cur = conn.cursor()
cur.execute(sql) # 输入要查询的SQL
rel = cur.fetchall()
cur.close()
conn.close()
return rel def getxlsx(rel):
'''
把从数据库中查询出来的数据写入excel文件
:param rel:
:return:
'''
file_name = time.strftime('%Y-%m-%d') + '.xlsx'
dret = pd.DataFrame.from_records(list(rel)) # mysql查询的结果为元组,需要转换为列表
dret.to_excel(file_name, index=False, header=("平台货号", "商品名称", "售价")) # header 指定列名,index 默认为True,写行名 if __name__ == '__main__':
sql = 'select goods_commonid,goods_name,goods_price from mall_goods_common where store_id=110 and set_new_time>1560182400;'
rel = getrel(sql)
getxlsx(rel)

2.使用xlwt模块

import pymysql
import xlwt def get_sel_excel(sql):
'''
连接mysql并把查询出来的数据写入excel表格
:param sql:
:return:
'''
conn = pymysql.connect(
host="localhost",
port=3306,
user="root",
passwd="",
db="db_test",
charset="utf8mb4"
) # 建立游标
cursor = conn.cursor()
print("开始查询表!")
# 执行sql语句
cursor.execute(sql)
# 获取查询到结果
res = cursor.fetchall()
print(res)
w_excel(res) def w_excel(res):
'''
把数据写入excel表格中
:param res:
:return:
'''
book = xlwt.Workbook() # 新建一个excel
sheet = book.add_sheet('vehicle_land') # 新建一个sheet页
title = ['平台货号', '商品名称', '售价']
# 写表头
i = 0
for header in title:
sheet.write(0, i, header)
i += 1 # 写入数据
for row in range(1, len(res)):
for col in range(0, len(res[row])):
sheet.write(row, col, res[row][col])
row += 1
col += 1
book.save('vehicle_land.xls')
print("导出成功!") if __name__ == "__main__":
sql = 'select goods_commonid,goods_name,goods_price from mall_goods_common where store_id=110 and set_new_time>1560182400;'
get_sel_excel(sql)

3.pandas

import pandas as pd
from sqlalchemy import create_engine # 初始化数据库连接,使用pymysql模块
# MySQL的用户:root, 密码:你的密码, 端口:3306,数据库:trustengine = create_engine("mysql+pymysql://root:password@localhost:3306/trust",encoding='utf-8')
# 查询语句,选出testexcel表中的所有数据
sql = """select goods_commonid,goods_name,goods_price from mall_goods_common where store_id=110 and set_new_time>1560182400;""" # read_sql_query的两个参数: sql语句, 数据库连接
df = pd.read_sql_query(sql,con=engine) # 输出testexcel表的查询结果
print(df) # 创建一个writer对象, 里面的参数是一个新的表格文件名
writer = pd.ExcelWriter('mydf.xlsx')
# 利用to_excel()方法将不同的数据框及其对应的sheet名称写入该writer对象中
df.to_excel(writer,sheet_name='test1',index=False)
# 数据写出到excel文件中,最后保存
writer.save()

4.pandas

# coding=utf-8
import pandas as pd
from pandas import DataFrame
from sqlalchemy import create_engine
import time # 开始时间
start = time.time()
# 建立链接
engine = create_engine('mysql+pymysql://root:123@192.168.148.61:3306/ppx_mall_dev_db')
# 查询语句
sql = '''select goods_commonid,goods_name,goods_price from mall_goods_common where store_id=110 and set_new_time>1560182400;'''
# 读取mysql
df = pd.read_sql_query(sql, engine)
print("从mysql中读取数据成功!开始将数据导入到excel表格中...")
# 将读取的数据格式化成DataFrame类型
test_data = DataFrame.from_records(df)
# 将数据写入excle中
test_data.to_excel("E:\\testdata.xlsx", index=False)
print("导出成功!")
# 程序结束时间
end = time.time()
# 打印出程序的运行时间
print('Running time: {} Seconds'.format(end - start))

如需修改表格样式,可参数:https://www.cnblogs.com/phoebechiang/p/10512337.html

把读取sql的结果写入到excel文件的更多相关文章

  1. R—读取数据(导入csv,txt,excel文件)

    导入CSV.TXT文件 read.table函数:read.table函数以数据框的格式读入数据,所以适合读取混合模式的数据,但是要求每列的数据数据类型相同. read.table读取数据非常方便,通 ...

  2. 用BCP从SQL Server 数据库中导出Excel文件

    BCP(Bulk Copy Program)是一种简单高效的数据传输方式在SQL Server中,其他数据传输方式还有SSIS和DTS. 这个程序的主要功能是从数据库中查询Job中指定step的执行信 ...

  3. C# 读取txt文本内容写入到excel

    using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; usin ...

  4. python3+xlwt 读取txt信息并写入到excel中

    # coding = utf-8 import os import xlwt import re def readTxt_toExcel(valueList, Pathlist): workbook ...

  5. 用python读取csv信息并写入新的文件

    import csv fo = open("result.txt", "w+") reader = csv.reader(open('test.csv')) f ...

  6. Aspose.Cell篇章3,设置写入到Excel文件的各种样式及输出

    Aspose.Cell的Style.Number设置全部设置 /// <summary> /// 单元格样式编号 /// 0 General General /// 1 Decimal 0 ...

  7. Python学习笔记_从CSV读取数据写入Excel文件中

    本示例特点: 1.读取CSV,写入Excel 2.读取CSV里具体行.具体列,具体行列的值 一.系统环境 1. OS:Win10 64位英文版 2. Python 3.7 3. 使用第三方库:csv. ...

  8. Java读取、写入、处理Excel文件中的数据(转载)

    原文链接 在日常工作中,我们常常会进行文件读写操作,除去我们最常用的纯文本文件读写,更多时候我们需要对Excel中的数据进行读取操作,本文将介绍Excel读写的常用方法,希望对大家学习Java读写Ex ...

  9. C#读取Excel文件:通过OleDb连接,把excel文件作为数据源来读取

    转载于:http://developer.51cto.com/art/200908/142392.htm C#读取Excel文件可以通过直接读取和OleDb连接,把excel文件作为数据源来读取:   ...

随机推荐

  1. [LC] 236. Lowest Common Ancestor of a Binary Tree

    Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree. According ...

  2. 吴裕雄--天生自然python学习笔记:Beautiful Soup 4.2.0模块

    Beautiful Soup 是一个可以从HTML或XML文件中提取数据的Python库.它能够通过你喜欢的转换器实现惯用的文档导航,查找,修改文档的方式.Beautiful Soup会帮你节省数小时 ...

  3. js 实现排序算法 -- 插入排序(Insertion Sort)

    原文: 十大经典排序算法(动图演示) 插入排序 插入排序(Insertion-Sort)的算法描述是一种简单直观的排序算法.它的工作原理是通过构建有序序列,对于未排序数据,在已排序序列中从后向前扫描, ...

  4. 传统if 从句子——以条件表达式作为if条件

    传统if 从句子——以条件表达式作为 if条件if [ 条件表达式 ]then command command commandelse command commandfi   条件表达式 文件表达式 ...

  5. Spring Boot 鉴权之—— JWT 鉴权

    第一:什么是JWT鉴权 1. JWT即JSON Web Tokens,是为了在网络应用环境间传递声明而执行的一种基于JSON的开放标准((RFC 7519),他可以用来安全的传递信息,因为传递的信息是 ...

  6. 奇葩念头:微信能取代WP应用吗

         墙倒众人推,原本是再平常不过的事,但每次发生都显得特别凄凉--就和楼市买房买涨不买跌一样,在互联网行业,用户数量越多的产品或服务,就会越受到行业和大众青睐.而越是小众的产品或服务,虽然是要走 ...

  7. 【software】变异注释工具:annovar

    annovar提供三种注释方式 一,基于基因的注释 给定变异,看变异是否影响编码蛋白的改变 支持基因定义系统:RefSeq genes, UCSC genes, ENSEMBL genes, GENC ...

  8. QA、EPG、PMO各自的职能划分及关系是什么?

    团队 职能 主要工作内容 EPG 负责过程持续改进工作 公司规范的建设和推广,并持续改进.收集过程改进需求,制定过程改进计划,获得高层的支持,并实施改进工作. PMO 负责公司内所有项目的审核.管理 ...

  9. FBI今年最重要的任务:招募黑客

    ​ 当FBI(联邦调查局)一次又一次被爆出丑闻的时候,面临着一个又一个的尴尬局面.在这样的情况下,FBI发现了自己的一个巨大问题,那就是以前都依靠隐秘行动和人员的保密性来保证国家的安全,现在必须依靠更 ...

  10. USB小白学习之路(7) FPGA Communication with PC by CY7C68013,TD_init()解析

    注:这个TD_Init()只对EP6进行了配置,将其配置成为Bluk_In端口,而没有对EP2进行配置.这篇文章直接把寄存器的图片贴上来了,看起来比较杂.感兴趣的可以看下一篇文章,是转自CSDN,对E ...