pandas把读取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=‘123‘,
                           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="123",
        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)

原文地址:https://www.cnblogs.com/tjp40922/p/11398406.html

时间: 2024-07-30 15:04:11

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

利用pandas将mysql查询出得结果写入到excel文件

#!/usr/bin/env python3 import pandas as pd import pymysql #返回SQL结果的函数 def getrel(sql): conn =  pymysql.connect(host='localhost',user='root',password='123456',db='test') cur = conn.cursor() cur.execute('set names utf8') cur.execute('select app,name  f

用PHPExcel类读取excel文件的内容

这里对PHPExcel类不做介绍,有兴趣的朋友可以自己查阅资料 在classes文件夹下有个PHPExcel.php文件,这个文件是这个类库的主要入口文件,在用之前,要引入这个类 其他的类,在此类中会自动加载 1 //建立reader对象 ,分别用两个不同的类对象读取2007和2003版本的excel文件 2 $PHPReader = new PHPExcel_Reader_Excel2007(); 3 if( ! $PHPReader->canRead($filePath)) 4 { 5 $P

使用poi读取Excel文件数据

除分数被转换为小数存储外,其他数据经本人测试无问题,如发现问题请留言,方便及时更新 package com.haiyisoft.iecp.util; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.text.DateFormat;

C#操作Excel文件(读取Excel,写入Excel)

看到论坛里面不断有人提问关于读取excel和导入excel的相关问题.闲暇时间将我所知道的对excel的操作加以总结,如今共享大家,希望给大家可以给大家带了一定的帮助.另外我们还要注意一些简单的问题1.excel文件仅仅能存储65535行数据,假设你的数据大于65535行,那么就须要将excel切割存放了.2.关于乱码,这主要是字符设置问题. 1.载入Excel(读取excel内容)返回值是一个DataSet //载入Excel public static DataSet LoadDataFro

已知s.txt文件中有一个这样的字符串 请编写程序读取数据内容,把数据排序后写入 ss.txt文件

package cn.idcast5; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.Arrays; /* * 需求:已知s.txt文件中有一个这样

使用SQL命令手动写入Discuz帖子内容

-- 转存表中的数据`forum_post` INSERT INTO `forum_post` (`pid`, `fid`,`tid`, `first`, `author`, `authorid`, `subject`, `dateline`, `message`,`useip`, `invisible`, `anonymous`, `usesig`, `htmlon`, `bbcodeoff`,`smileyoff`, `parseurloff`, `attachment`, `rate`,

java处理Excel文件---excel文件的创建,删除,写入,读取

这篇文章的代码是我封装的excel处理类,包含推断excel是否存在,表格索引是否存在,创建excel文件,删除excel文件,往excel中写入信息,从excel中读取数据. 尤其在写入与读取两个方法中,我採用了java反射机制去实现,以object对象作为參数就可以.代码自己主动解析该实体类的属性与方法.代码重用性高. 代码另一些须要改进和扩展的地方.大家能够依据实际情况进行简单改动. 上代码,首先是我封装的这个类(採用的是POI包): package module.system.commo

php从memcache读取数据再批量写入mysql的方法

这篇文章主要介绍了php从memcache读取数据再批量写入mysql的方法,可利用memcache缓解服务器读写压力,并实现数据库数据的写入操作,非常具有实用价值,需要的朋友可以参考下. 用 Memcache 可以缓解 php和数据库压力下面代码是解决高负载下数据库写入瓶颈问题,遇到最实用的:写入ip pv uv的时候,用户达到每分钟几万访问量,要记录这些数据,实时写入数据库必定奔溃. 用以下技术就能解决,还有如用户注册,同一时间断内,大量用户注册,可以缓存后一次性写入到数据库,代码如下 pu

java初始化数据库读取sql配置文件建表

在src/main/resources下sql文件夹建立一个init.sql文件,放入建表语句: CREATE TABLE {DB}.`AGENT_STATUS` ( `DEVICE_NUM` varchar(100) NOT NULL, `START_TIME` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, `STATUS` int(11) NOT NULL, `DURATION` int(1