首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何导入制表符分隔的"CSV“

如何导入制表符分隔的"CSV“
EN

Stack Overflow用户
提问于 2014-07-10 14:20:39
回答 1查看 4.7K关注 0票数 1

在“与文档列表交互”教程中,从CSV文件导入数据展示了如何导入带有逗号分隔值的CSV文件。

但是,我将上传一个带有选项卡分隔值的.txt文件。(例如可以从Excel导出的。)

如何修改该脚本以将导入的电子表格识别为选项卡分隔的值而不是逗号分隔的值?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-07-10 19:22:08

使用Utilities.parseCsv(csv, delimiter)。以下内容来自Google脚本教程与文档列表交互,将CSVToArray()替换为Utilities.parseCsv()

要自动检测分隔符是制表符还是逗号是一件简单的事情:

代码语言:javascript
运行
复制
// Detect delimiter - tab or comma
var delim = ",";
if (csvFile.indexOf("\t") != -1) delim = "\t"; 

importFromCSV

代码语言:javascript
运行
复制
/**
 * Populates a sheet with contents read from a CSV file located
 * in the user's GDrive. If either parameter is not provided, the
 * function will open inputBoxes to obtain them interactively.
 *
 * Adapted from <I>Tutorial: Interacting With Your Docs List.</I>
 (https://developers.google.com/apps-script/articles/docslist_tutorial#section2)
 *
 * @param {string}fileName (Optional) The name of the input file.
 *
 * @param {string} sheetName (Optional) The name of the destination sheet.
 *        If the sheet does not exist, it will be created by
 *        this function. A pre-existing sheet will be cleared 
 *        before importing the CSV data.
 *
 * @returns {JsonObject} A summary of the import operation,
 *        including the date the input file was last updated
 *        [see <a href="https://developers.google.com/apps-script/class_file#getLastUpdated">File.getLastUpdated()</a>], and the number of rows
 *        and columns imported.
 * <PRE>
 *
 *   { lastUpdated : 5-Mar-2014, numRows : 2541, numCols : 22 }
 *  </PRE>
 *
 *  @throws {Error} "No Input File" if input CSV not found.
 */
function importFromCSV(fileName,sheetName) {
  var useBrowser = (!fileName);   // Assume that spreadsheet UI in use, if no args
  fileName = fileName || Browser.inputBox("Enter the name of the file in your Docs List to import (e.g. myFile.csv):");
  sheetName = sheetName || Browser.inputBox("Enter the name of the sheet to import into (e.g. Sheet1):");

  var files = DocsList.getFiles();
  var csvFile = "";
  var lastUpdated = 0;

  for (var i = 0; i < files.length; i++) {
    if (files[i].getName() == fileName) {
      csvFile = files[i].getContentAsString();
      lastUpdated = files[i].getLastUpdated();
      break;
    }
  }

  if (lastUpdated == 0) {
    Browser.msgBox("No Input File", "Either no file name was provided, or file does not exist.", Browser.Buttons.OK);
    throw new Error("No Input File");
  }
  else {
    // Detect delimiter - tab or comma
    var delim = ",";
    if (csvFile.indexOf("\t") != -1) delim = "\t"; 

    var csvData = Utilities.parseCsv(csvFile, delim);

    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var sheet = ss.getSheetByName(sheetName);
    if (sheet === null) {
      ss.insertSheet(sheetName);
      sheet = ss.getSheetByName(sheetName);
    }

    sheet.clear();

    var numRows = csvData.length;
    var numCols = csvData[0].length; // assume all rows are same width

    // Make a single call to spreadsheet API to write values to sheet.
    sheet.getRange(1, 1, numRows, numCols).setValues( csvData );

  }

  // Report results (if UI attached)  
  Browser.msgBox("Imported " + numRows + " rows x " + numCols + "columns");

  // Return an object with import results
  return { lastUpdated : lastUpdated, numRows : numRows, numCols : numCols };
}

电子表格菜单项

要创建自定义菜单前端:

代码语言:javascript
运行
复制
function onOpen() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var cMenuEntries = [{name: "Load CSV Data", functionName: "importFromCSV"}];
  ss.addMenu("Custom", cMenuEntries);
}

带参数调用

您还可以从其他脚本调用函数,为csv文件名和电子表格选项卡传递参数。

代码语言:javascript
运行
复制
function test_importFromCSV() {
  return importFromCSV("My CSV File.txt","Sheet1");
}
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24679048

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档