把读取sql的结果写入到excel文件
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文件的更多相关文章
- R—读取数据(导入csv,txt,excel文件)
导入CSV.TXT文件 read.table函数:read.table函数以数据框的格式读入数据,所以适合读取混合模式的数据,但是要求每列的数据数据类型相同. read.table读取数据非常方便,通 ...
- 用BCP从SQL Server 数据库中导出Excel文件
BCP(Bulk Copy Program)是一种简单高效的数据传输方式在SQL Server中,其他数据传输方式还有SSIS和DTS. 这个程序的主要功能是从数据库中查询Job中指定step的执行信 ...
- C# 读取txt文本内容写入到excel
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; usin ...
- python3+xlwt 读取txt信息并写入到excel中
# coding = utf-8 import os import xlwt import re def readTxt_toExcel(valueList, Pathlist): workbook ...
- 用python读取csv信息并写入新的文件
import csv fo = open("result.txt", "w+") reader = csv.reader(open('test.csv')) f ...
- Aspose.Cell篇章3,设置写入到Excel文件的各种样式及输出
Aspose.Cell的Style.Number设置全部设置 /// <summary> /// 单元格样式编号 /// 0 General General /// 1 Decimal 0 ...
- Python学习笔记_从CSV读取数据写入Excel文件中
本示例特点: 1.读取CSV,写入Excel 2.读取CSV里具体行.具体列,具体行列的值 一.系统环境 1. OS:Win10 64位英文版 2. Python 3.7 3. 使用第三方库:csv. ...
- Java读取、写入、处理Excel文件中的数据(转载)
原文链接 在日常工作中,我们常常会进行文件读写操作,除去我们最常用的纯文本文件读写,更多时候我们需要对Excel中的数据进行读取操作,本文将介绍Excel读写的常用方法,希望对大家学习Java读写Ex ...
- C#读取Excel文件:通过OleDb连接,把excel文件作为数据源来读取
转载于:http://developer.51cto.com/art/200908/142392.htm C#读取Excel文件可以通过直接读取和OleDb连接,把excel文件作为数据源来读取: ...
随机推荐
- Python-scapy学习
scapy-arpspoof from scapy.all import Ether,ARP,sendp,getmacbyip Ether:用来构建以太网数据包 ARP:构建ARP数据包的类 send ...
- 3DSMAX安装失败,如何卸载修复重新安装3dmax 2017?
一些同学安装3dmax出错了,也有时候想重新安装3dmax的时候会出现这种本电脑已安装3dmax,你要是不留意直接安装,只会按装3dmax的附件,3dmax是不会按装上的.这种原因呢就是大家在之前卸载 ...
- tomcat启动不了的问题
tomcat启动的几个问题 1.端口冲突 2.非端口冲突,需要加入配置host文件 日志文件: 解决办法:https://blog.csdn.net/u012949658/article/detail ...
- idea 集成svn
1.下载svn客户端 官网下载地址:https://tortoisesvn.net/downloads.html 2. 安装svn客户端 在安装svn客户端的时候一定要勾选,否则在idea上集成svn ...
- OpenWrt编译后生成的bin文件:jffs2与squashfs、factory与sysupgrade
OpenWrt编译后会生成多个bin文件,比如 openwrt-ar71xx-generic-tl-wr841nd-jffs2-factory.bin 8126464 openwrt-ar71xx-g ...
- Java IO: 异常处理
原文链接 作者:Jakob Jenkov 译者: 李璟(jlee381344197@gmail.com) 流与Reader和Writer在结束使用的时候,需要正确地关闭它们.通过调用close()方法 ...
- ffmpeg android移植
CMake语法简介(androidstudio中利用CMake开发NDK): http://blog.csdn.net/u013718120/article/details/62883711FFmpe ...
- btrace简单使用
基本安装 在github上btrace项目的release下 下载最新的btracehttps://github.com/btraceio/btrace/releases 解压完后,将btrace的b ...
- 吴裕雄--天生自然python编程:turtle模块绘图(2)
#彩色螺旋线 import turtle import time turtle.pensize(2) turtle.bgcolor("black") colors = [" ...
- 配置Maven本地仓库
以本机为例: 系统:Windows 开发工具:IDEA 如果想在dos窗口输mvn命令,需配置环境变量. 1. 在D盘新建repository文件夹,该目录用作maven的本地库. 2. 打开D:\P ...