首页 > 解决方案 > 从 csv 输出中删除空数组

问题描述

我正在使用此脚本下载 Google 电子表格中的所有选项卡。

当我输出正在下载的行时,它包括空白数组:

输出Data 1: [[id, name], [1.0, John], [2.0, Smith], [, ], [, ], [, ], [, ], [, ], [, ], ...

function convertRangeToCsvFile_(csvFileName, sheet) {
  // get available data range in the spreadsheet
  var activeRange = sheet.getDataRange();
  try {
    var data = activeRange.getValues();
    Logger.log('Data 1: %s', data); <----- Logging here

如何从最终下载的 csv 中清除它?

在此处输入图像描述

标签: javascriptcsvgoogle-sheets

解决方案


问题:你为什么用%s它来记录它?鉴于您正在记录的实际上是一个数组,它可能会导致一些问题。

似乎在您展示的脚本中,他们在行和列之间执行了某种过滤,然后他们将其解析为字符串,我建议您尝试这样的事情:

const data = activeRange.getValues();
const filteredData = data.filter((item) => {
  // We will prevent non array elements that could break the your csv grid here
  if (!Array.isArray(item)){
    return false
  }
  // We will prevent rows with funny values (or no values) here
  for (var column = 0; column < item.length; column++) {
    if(!item[column]) {
      return false;
    }
  }
  // Add any extra condition before this return statement which basically means they are good to go
  return true;
});

然后将正确的解析应用于字符串或您需要传递给 csv 文件的任何内容。


推荐阅读