如何使用管道分隔符导出到.csv

时间:2018-03-13 04:48:18

标签: csv google-sheets export-to-csv delimiter

我使用Google表格(电子表格)为我的Gambio商店组合不同来源的文章数据。 要导入数据,我需要管道符号作为分隔符/分隔符,并“作为.csv文件中的文本分隔符。 在用于导出到.csv的Google表格菜单中,没有选项。

有没有办法在Google表格中使用管道分隔符导出到.csv?

1 个答案:

答案 0 :(得分:1)

有几种方法可以从Google表格导出电子表格和/或工作表。将工作表导出为csv文件内置于Google表格(文件,下载,CSV)。

在这种情况下,OP引入了两种“标准”方法无法解决的复杂问题。
1)要以'竖线'字符(|)分隔的字段,并且
2)所有字符串字段都用双引号引起来。

GitHub上有一些脚本可以自动将工作表另存为csv。 Michael Derazon(export-named-sheet-as-csv.gs)的https://gist.github.com/mderazon/9655893是一个示例,我以此为基础编写了这段代码。但是,这些脚本遵循使用逗号作为字段定界符的“常规”规则,并且没有对字符串进行特殊处理。

以下代码会将活动工作表另存为csv文件,并提供管道字段定界符和字符串周围的双引号。用户可以通过编辑“参数”表上的字段来决定这些参数,如本屏幕截图所示。


Parameter settings

该脚本使用typeof标识字符串,并使用Dmytro Shevchenko在Detecting an “invalid date” Date instance in JavaScript中指出的函数isValidDate

/*
 * 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
 * source: https://gist.github.com/mderazon/9655893
 * adapted by Ted Bell for https://stackoverflow.com/questions/49248498/how-can-i-export-to-csv-with-pipe-delimiter
 */
function onOpen() {
    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var csvMenuEntries = [{
        name: "export as csv file",
        functionName: "saveAsCSV"
    }];
    ss.addMenu("CSV Export", csvMenuEntries);
};

function saveAsCSV() {
    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var ssname = ss.getName();
    var sheet = ss.getActiveSheet();
    var sheetname = sheet.getSheetName();
    //Logger.log("DEBUG: the name of the spreadsheet is "+ssname);//DEBUG
    //Logger.log("DEBUG: the sheet name is "+sheetname);// DEBUG

    //// create a folder from the name of the spreadsheet
    var folder = DriveApp.createFolder(ssname.toLowerCase() + '_' + sheetname.toLowerCase().replace(/ /g, '_') + '_csv_' + new Date().getTime());
    //Logger.log("DEBUG: the folder name is "+folder);//DEBUG

    // append ".csv" extension to the sheet name
    var fileName = ssname + '_' + sheetname + ".csv";

    // convert all available sheet data to csv format
    var csvFile = so_4225484202(fileName);

    // create a file in the Docs List with the given name and the csv data
    folder.createFile(fileName, csvFile);

    Browser.msgBox('Files are waiting in a folder named ' + folder.getName());
}


function isValidDate(date) {
    return date && Object.prototype.toString.call(date) === "[object Date]" && !isNaN(date);
}


function so_4225484202(filename) {

    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var sheet = ss.getActiveSheet();
    var paramsheet = ss.getSheetByName("Parameters");

    var linearray = [];
    var rowdata = [];
    var csv = "";
    var fieldvalue = "";

    var param = paramsheet.getRange(2, 2, 2);
    var paramValues = param.getValues();
    //Logger.log("DEBUG: parameters = "+param.getA1Notation());//DEBUG
    var fieldDelimiter = paramValues[0][0];
    var textDelimiter = paramValues[1][0];
    //Logger.log("DEBUG: field delimiter: "+fieldDelimiter+", text delim: "+textDelimiter);//DEBUG


    var rangeData = sheet.getDataRange();
    var lastColumn = rangeData.getLastColumn();
    var lastRow = rangeData.getLastRow();
    //Logger.log("DEBUG: lastColumn: "+lastColumn+", lastRow: "+lastRow);//DEBUG

    // Get array of values in the Data Range
    var rangeValues = rangeData.getValues();

    // Loop through array and build values for csv
    for (i = 0; i < lastRow; i++) {
        for (j = 0; j < lastColumn; j++) {

            var value = rangeValues[i][j];
            var theType = typeof value;

            if (theType === "object") {
                var testdate = isValidDate(value);
                //Logger.log("if typeof is object: testdate: "+testdate);//DEBUG
                var testtype = typeof testdate;
                if (testtype === "boolean") {
                    // variable is a boolean
                    //Logger.log("Its a date");//DEBUG
                    theType = "date";
                } else {
                    //Logger.log("Its not a date");//DEBUG
                }
            }
            if (theType === "string") {
                value = textDelimiter + value + textDelimiter;
            }

            rowdata.push([value]);
        };

        //Logger.log("DEBUG: rowdata: "+rowdata);//DEBUG
        csv += rowdata.join(fieldDelimiter) + "\n";
        var rowdata = [];

    };

    //Logger.log("DEBUG: csv: "+csv);//DEBUG
    return csv;

}

spreadsheet包含示例数据。 处理包含约1,000条记录的工作表并在大约5秒钟内保存。