1function onOpen() {
2 var ss = SpreadsheetApp.getActiveSpreadsheet();
3 var searchMenuEntries = [ {name: "Search in all files", functionName: "search"}];
4 var csvMenuEntries = [{name: "Save as CSV file", functionName: "saveAsCSV"},
5 {name: "Load from CSV file", functionName: "importFromCSV"}];
6 ss.addMenu("Search Google Drive", searchMenuEntries);
7 ss.addMenu("CSV", csvMenuEntries);
8}
9
1function saveAsCSV() {
2 // Prompts the user for the file name
3 var fileName = Browser.inputBox("Save CSV file as (e.g. myCSVFile):");
4
5 // Check that the file name entered wasn't empty
6 if (fileName.length !== 0) {
7 // Add the ".csv" extension to the file name
8 fileName = fileName + ".csv";
9 // Convert the range data to CSV format
10 var csvFile = convertRangeToCsvFile_(fileName);
11 // Create a file in Drive with the given name, the CSV data and MimeType (file type)
12 DriveApp.createFile(fileName, csvFile, MimeType.CSV);
13 }
14 else {
15 Browser.msgBox("Error: Please enter a CSV file name.");
16 }
17}
18
19function convertRangeToCsvFile_(csvFileName) {
20 // Get the selected range in the spreadsheet
21 var ws = SpreadsheetApp.getActiveSpreadsheet().getActiveSelection();
22 try {
23 var data = ws.getValues();
24 var csvFile = undefined;
25
26 // Loop through the data in the range and build a string with the CSV data
27 if (data.length > 1) {
28 var csv = "";
29 for (var row = 0; row < data.length; row++) {
30 for (var col = 0; col < data[row].length; col++) {
31 if (data[row][col].toString().indexOf(",") != -1) {
32 data[row][col] = "\"" + data[row][col] + "\"";
33 }
34 }
35
36 // Join each row's columns
37 // Add a carriage return to end of each row, except for the last one
38 if (row < data.length-1) {
39 csv += data[row].join(",") + "\r\n";
40 }
41 else {
42 csv += data[row];
43 }
44 }
45 csvFile = csv;
46 }
47 return csvFile;
48 }
49 catch(err) {
50 Logger.log(err);
51 Browser.msgBox(err);
52 }
53}
54