mysql命令行输出结果转换为表格

众所周知,mysql输出其实有很多种方法都可以转换为excel表格,但是我目前只能使用命令行去获取到数据,而且从服务器下载excel文件也是个麻烦事,因此自己用python写了个脚本,用于将mysql查询到的数据转换为pandas的DataFrame格式,可以直接导出excel表格。

如果你的数据不敏感的话,可以试试这个网站:https://tableconvert.com/zh-cn/mysql-to-excel,还是蛮好用的。

直接上我的python代码:

import pandas as pd

def split_line(line: str):
    words = line.strip().split('|')
    split_word = []
    for w in words:
        if w == '':
            continue
        split_word.append(w.strip())

    return split_word


def split_multi_lines(lines: list, header: list):
    df_lines: pd.DataFrame = pd.DataFrame(lines)
    df_lines = df_lines[0].str.split('|', expand=True)
    df_lines.drop(df_lines.columns[[0, -1]], axis=1, inplace=True)  # 删掉空列
    df_lines.columns = header

    # 去掉空格
    for c in df_lines.columns:
        df_lines[c] = df_lines[c].str.strip()

    return df_lines


def process_with_head_sql_answer(txt: str):
    txt_list = txt.strip().split('\n')
    # 去掉标题的头尾
    txt_list.pop(2)
    txt_list.pop(0)
    # 获取列名
    head = split_line(txt_list[0])
    # 去掉标题
    txt_list.pop(0)
    # 去掉末尾横线
    txt_list.pop()

    split_table = split_multi_lines(txt_list, head)
    print(split_table)


if __name__ == '__main__':
    txt = '''
+----+---------+-----+--------+
| id | name    | age | gender |
+----+---------+-----+--------+
| 1  | Roberta | 39  | M      |
| 2  | Oliver  | 25  | M      |
| 3  | Shayna  | 18  | F      |
| 4  | Fechin  | 18  | M      |
+----+---------+-----+--------+
    '''

    process_with_head_sql_answer(txt)

输出结果为:
在这里插入图片描述

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值