众所周知,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)
输出结果为: