Skip to content

Instantly share code, notes, and snippets.

@supertask
Last active June 15, 2023 04:22
Show Gist options
  • Save supertask/9de96dc8bed2fb527d034992cbb4b0e5 to your computer and use it in GitHub Desktop.
Save supertask/9de96dc8bed2fb527d034992cbb4b0e5 to your computer and use it in GitHub Desktop.
スプレッドシートの複数のシートを複数のCSVにエクスポートするGASファイル.
/*
* スプレッドシートの複数のシートを複数のCSVにエクスポートする.
* マイドライブに置かれる.
* script to export data in all sheets in the current spreadsheet as individual csv files
* files will be named according to the name of the sheet
* author: Michael Derazon
*/
function onOpen() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var csvMenuEntries = [{name: "export as csv files", functionName: "saveAsCSV"}];
ss.addMenu("csv", csvMenuEntries);
};
function saveAsCSV() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheets = ss.getSheets();
// create a folder from the name of the spreadsheet
var folder = DriveApp.createFolder(ss.getName().toLowerCase().replace(/ /g,'_') + '_csv_' + new Date().getTime());
for (var i = 0 ; i < sheets.length ; i++) {
var sheet = sheets[i];
// append ".csv" extension to the sheet name
fileName = i + "_" + sheet.getName() + ".csv";
// convert all available sheet data to csv format
var csvFile = convertRangeToCsvFile_(fileName, sheet);
// create a file in the Docs List with the given name and the csv data
folder.createFile(fileName, csvFile);
}
Browser.msgBox('フォルダー名' + folder.getName() + 'にCSVが保存されました.');
}
function convertRangeToCsvFile_(csvFileName, sheet) {
// get available data range in the spreadsheet
var activeRange = sheet.getDataRange();
try {
var data = activeRange.getValues();
var csvFile = undefined;
// loop through the data in the range and build a string with the csv data
if (data.length > 1) {
var csv = "";
for (var row = 0; row < data.length; row++) {
for (var col = 0; col < data[row].length; col++) {
if (data[row][col].toString().indexOf(",") != -1) {
data[row][col] = "\"" + data[row][col] + "\"";
}
}
// join each row's columns
// add a carriage return to end of each row, except for the last one
if (row < data.length-1) {
csv += data[row].join(",") + "\r\n";
}
else {
csv += data[row];
}
}
csvFile = csv;
}
return csvFile;
}
catch(err) {
Logger.log(err);
Browser.msgBox(err);
}
}
@onozuka
Copy link

onozuka commented Oct 21, 2022

参考にさせてもらいました。ありがとうございます。
使用時に2点ほど変更したので、同じことをしたい人がいたら、もし良かったら参考にしてください。

①saveAsCSV() ファイル名のナンバリングをゼロ埋め

    var num = ( '00' + i ).slice( -2 );
    fileName = num + "_" + sheet.getName() + ".csv";

②convertRangeToCsvFile_() 値に,が含まれているとき、値の"を""に変換

          if (data[row][col].toString().indexOf(",") != -1) {
            let replaceWord = /"/g;                                     // 追加
            data[row][col] = data[row][col].replace(replaceWord,"\"\"") // 追加
            data[row][col] = "\"" + data[row][col] + "\"";
          }

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