把读取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文件作为数据源来读取: ...
随机推荐
- LeetCode Day 7
LeetCode0012 罗马数字包含以下七种字符: I, V, X, L,C,D 和 M. 字符 I V X L C D M 数值 1 5 10 50 100 500 1000 例如, 罗马数字 2 ...
- JavaScript学习总结(三)BOM和DOM详解
转自:http://segmentfault.com/a/1190000000654274 DOM介绍 D(文档)可以理解为整个Web加载的网页文档,O(对象)可以理解为类似window对象只来的东西 ...
- WPF中,如何屏蔽WebBrowser弹出的脚本错误窗口?
WPF没有自带屏蔽这些窗口的方法或属性,可以使用反射的方法来屏蔽弹出脚本错误窗口: public void SuppressScriptErrors(WebBrowser wb, bool Hide) ...
- 接受H0的坏处|试验误差|置信度由来|
生物统计与实验设计 置信度(0.05 0.01)是通过实验次数估计值的分布得到的,它是整个分布的期望,这个值的确立需要具体情况具体分析. 肯定很难,因为否定一次很容易.虽然如果没有否定(eg:得到p= ...
- linux有些sh文件,为什么要用 ./ 来执行
因为有环境变量PATH,里面包含了许多目录,这些目录下的可执行文件就无需输入完整路径来执行.你可以用 echo "$PATH"查看当前的环境变量包含的目录,自带的命令文件都是在PA ...
- Java IO: RandomAccessFile
原文链接 作者: Jakob Jenkov 译者: 李璟(jlee381344197@gmail.com) RandomAccessFile允许你来回读写文件,也可以替换文件中的某些部分.FileIn ...
- 吴裕雄--天生自然HTML学习笔记:HTML 表格
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title> ...
- 2019DDCTF部分Writeup
-- re Windows Reverse1 通过DIE查壳发现存在upx,在linux上upx -d脱壳即可,拖入IDA,通过关键字符串找到关键函数: main函数中也没有什么,将输入的字符串带到s ...
- loadrunner通过web的post请求方法测接口
loadrunner通过web的post请求方法测接口 loginapi() 模拟APP发送请求给Cloud, Action() "Name=input","Value= ...
- 为何滴滴会走Uber之路,研发无人驾驶?
近日,滴滴出行宣布完成新一轮超过55亿美元融资,以支持其全球化战略的推进和前沿技术领域的投资.其中,无人驾驶汽车将是这笔资金重要的投资方向.此前,滴滴在全球范围内的追赶对象Uber不断在无人汽车领域发 ...