• python使用pymysql和xlwt模块将mysql的数据以exel表格的形式导出


    class ExportView(APIView):
        authentication_classes = [JSONWebTokenAuthentication,]
        permission_classes = [IsAdminUser,]
        def get(self,request,*args,**kwargs):
            conn = pymysql.connect(
                host='127.0.0.1',
                user = '××××××××××',
                password = '××××××××××',
                database='××××××××××',
                charset='utf8',
            )
            cursor = conn.cursor()
            query = 'select * from nineth_article'
            cursor.execute(query)
            results = cursor.fetchall()
            fields = cursor.description
            workbook = xlwt.Workbook(encoding='UTF-8')
            sheet = workbook.add_sheet('nine_article')
            # for item in fields:
            #     print(item[0])
            # print(results[0][1].strftime('%Y-%m-%d %H:%M:%S'))
            #从fields中取出所有字段名,这里直接存成了excel表格的第0行(存成exel表格后是第一行),如果需要改变,可作调整
            for index,value in enumerate(fields):
                sheet.write(0,index,value[0])
            #从表格的第1行开始,一行一行写入数据
            for row_number in range(1,cursor.rowcount+1):
                for col_number in range(len(fields)):
                    #将datatime对象转成时间字符串的形式存入
                    if col_number in (1,2):
                        strftime = results[row_number - 1][col_number].strftime('%Y/%m/%d %H:%M:%S')
                        sheet.write(row_number, col_number, strftime)
                    elif col_number == 10:
                        strftime = results[row_number - 1][col_number].strftime('%Y/%m/%d')
                        sheet.write(row_number, col_number, strftime)
                    else:
                        sheet.write(row_number,col_number,results[row_number-1][col_number])
            #拼接文件保存的路径,这里需要注意文件后缀是xls,而不是xlsl(否则乱码打不开文件,原因不太清楚)
            filename = '/'.join([settings.MEDIA_ROOT,'export','article.xls'])
            workbook.save(filename)
            cursor.close()
            conn.close()
            return APIResponse(msg='ok')
    
  • 相关阅读:
    koa2跨域模块koa2-cors
    使用spring等框架的web程序在Tomcat下的启动顺序及思路理清
    logback 配置解析
    java 学习总结
    如何删除git远程分支
    C++11 锁 lock
    CAS 与 无锁队列
    docker 配置
    vim 中Taglist的安装和使用
    基于C++11的线程池,简洁且可以带任意多的参数
  • 原文地址:https://www.cnblogs.com/leilijian/p/13847276.html
Copyright © 2020-2023  润新知