Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@HiroshiOkada
Last active February 22, 2019 16:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save HiroshiOkada/3f55a8bfc58e4c3964cfbd847320d8d4 to your computer and use it in GitHub Desktop.
Save HiroshiOkada/3f55a8bfc58e4c3964cfbd847320d8d4 to your computer and use it in GitHub Desktop.
Google スプレッドシートの選択範囲をマークダウンの表にする
'use strict';
// ファイルを開いた時に実行
function onOpen() {
setupMenu();
}
// メニューを登録
function setupMenu(ss) {
var ui = SpreadsheetApp.getUi();
ui.createMenu('Utils').addItem('選択範囲をmarkdownの表に', 'markdownTable').addToUi();
}
// 選択範囲をmarkdownの表に変換しモーダルダイアログボックで表示
function markdownTable() {
// モーダルダイアログボックの表示
function showModal(title, htmlText) {
var ui = SpreadsheetApp.getUi();
var htmlOutput = HtmlService.createHtmlOutput(htmlText).setWidth(640).setHeight(480);
ui.showModalDialog(htmlOutput, title);
}
var range = SpreadsheetApp.getActiveRange();
if (range.getNumColumns() < 2 || range.getNumRows() < 2) {
SpreadsheetApp.getUi().alert("2×2以上の範囲を選択してください");
return;
}
var vals = range.getDisplayValues();
var rowVals = range.getValues();
var hAligns = range.getHorizontalAlignments();
var fStyles = range.getFontStyles();
var fWeights = range.getFontWeights();
var template = HtmlService.createTemplate('<?= txt ?>');
// 一つのセルを markdown にする
function renderCell(i, j) {
template.txt = vals[i][j];
var txt = template.evaluate().getContent();
if (/italic/.test(fStyles[i][j])) {
txt = '_' + txt + '_';
}
if (/bold/.test(fWeights[i][j])) {
txt = '**' + txt + '**';
}
return txt;
}
var maxCol = 12;
var lines = [];
// ヘッダー
var line = ['|'];
for (var j = 0; j < vals[0].length; j += 1) {
line.push(renderCell(0, j));
line.push('|');
}
var lineTxt = line.join(' ');
maxCol = Math.max(lineTxt.length, maxCol);
lines.push(lineTxt);
// 区切り
var line = ['|'];
for (var j = 0; j < vals[1].length; j += 1) {
if (/left/.test(hAligns[1][j]) || typeof(rowVals[1][j]) === 'number') {
line.push('----:|');
} else if (/center/.test(hAligns[1][j])) {
line.push(':---:|');
} else {
line.push('-----|');
}
}
var lineTxt = line.join(' ');
maxCol = Math.max(lineTxt.length, maxCol);
lines.push(lineTxt);
// データ
for (var i = 1; i < vals.length; i += 1) {
var line = ['|'];
for (var j = 0; j < vals[i].length; j += 1) {
line.push(renderCell(i, j));
line.push('|');
}
var lineTxt = line.join(' ');
maxCol = Math.max(lineTxt.length, maxCol);
lines.push(lineTxt);
}
template.txt = lines.join('\n');
var htmlText = '<textarea cols="' + maxCol + '" rows="' + lines.length + '">' + template.evaluate().getContent() + '</textarea>';
var texts = lines.join('\n');
showModal('markdown table', htmlText);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment