Skip to content

Instantly share code, notes, and snippets.

@icedfish
Forked from zhwei/export_as_xlsx.py
Created April 19, 2016 01:37
Show Gist options
  • Save icedfish/481581e5cb04c05906b54ca0474b06aa to your computer and use it in GitHub Desktop.
Save icedfish/481581e5cb04c05906b54ca0474b06aa to your computer and use it in GitHub Desktop.
MySQL Workbench Plugin: Export Result Set As Excel Xlsx
# -*- coding: utf-8 -*-
#
# Export Result Set As Excel Xlsx File
#
# Installation:
# 1. Install Python(2.7) Module "XlsxWriter", See http://xlsxwriter.readthedocs.org/getting_started.html
# 2. In MySQL Workbench
# Scripting => Install Plugin/Module... => <select this script> => <restart mysql workbench>
#
# Usage:
# Tools => Utilities => Export Result Set As Excel Xlsx
#
# Author: zhwei
# Project Link: https://gist.github.com/zhwei/440881cb5e143346195b47975a52b9a7
#
# MySQL Workbench Python script
# Written in MySQL Workbench 6.2.5
import time
import grt
from wb import *
import mforms
import xlsxwriter
# define this Python module as a GRT module
ModuleInfo = DefineModule(name= "WbTableUtils", author= "zhwei", version="0.2")
@ModuleInfo.plugin(
"wb.sqlide.exportAsXlsx",
caption= "Export Result Set As Excel Xlsx",
input= [wbinputs.currentQueryEditor()],
pluginMenu= "SQL/Utilities"
)
@ModuleInfo.export(grt.LIST, grt.classes.db_query_Resultset)
def exportAsXlsx(query_editor):
resultset = query_editor.activeResultPanel.resultset
# Row Header
data = [[i.name for i in resultset.columns]]
# Data Rows
column_count = len(resultset.columns)
cursor = resultset.goToFirstRow()
while cursor:
data.append([resultset.stringFieldValue(i) for i in range(column_count)])
cursor = resultset.nextRow()
# Choose Directory
fc = mforms.FileChooser(mforms.OpenDirectory)
fc.set_directory(mforms.Utilities.get_special_folder(mforms.Desktop))
if not fc.run_modal():
return
path = fc.get_path()
filename = '{}/{}-{}.xlsx'.format(path, query_editor.name, time.strftime('%Y-%m-%d.%H%M%S'))
# Initialize Excel Workbook and Worksheet
workbook = xlsxwriter.Workbook(filename)
worksheet = workbook.add_worksheet()
for i, row in enumerate(data):
for j, item in enumerate(row):
worksheet.write(i, j, item.decode('utf-8') if item else item)
workbook.close()
mforms.Utilities.show_message('Done', 'Saved to ' + filename, "OK", "", "")
@aelabibi
Copy link

Hello,
Thank you for this script.
I have installed it and restarted MySql Workbench but I can't find Export Result Set As Excel Xlsx in Tools => Utilities
I have already Python 2.7 installed.
Thank you in advance.
Best regards,

@Nicolasclearleaf
Copy link

not working with v8.0.20, 64bits, any update here?

@changuelsami
Copy link

works fine with v8.0.20

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment