Last active
May 4, 2016 03:31
-
-
Save zhwei/440881cb5e143346195b47975a52b9a7 to your computer and use it in GitHub Desktop.
MySQL Workbench Plugin: Export Result Set As Excel Xlsx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- 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.3") | |
@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.SaveFile) | |
path = fc.last_directory or mforms.Utilities.get_special_folder(mforms.Desktop) | |
filename = '{}/{}.{}.xlsx'.format(path, query_editor.name, time.strftime('%Y-%m-%d-%H%M%S')) | |
fc.set_path(filename) | |
if not fc.run_modal(): | |
return | |
# Initialize Excel Workbook and Worksheet | |
workbook = xlsxwriter.Workbook(fc.get_path()) | |
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() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment