-
-
Save icedfish/481581e5cb04c05906b54ca0474b06aa to your computer and use it in GitHub Desktop.
MySQL Workbench Plugin: Export Result Set As Excel Xlsx
This file contains 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.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", "", "") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
works fine with v8.0.20