我知道這是非常基礎的知識,即使我在這里搜索了答案,我仍然沒有得到正確的答案。我想將 2D 串列資料列印到電子表格中,但只有選定的列。
以下是來自 2dlist 的資料示例:
| 姓名 | 年齡 | 性別 | 國家 |
|---|---|---|---|
| 安妮 | 26 | 女性 | 一種 |
| 約翰 | 22 | 男性 | 乙 |
| 凱蒂 | 24 | 女性 | C |
| 羅納爾多 | 26 | 男性 | D |
但是,我只需要將前兩列列印到電子表格中,即Name和Age。我應該使用什么腳本?
謝謝你,我真的很感激你的幫助。
uj5u.com熱心網友回復:
給定您的表格,您的二維陣列如下所示:
const data = [
['Name', 'Age', 'Gender', 'Country'],
['Annie', 26, 'Female', 'A'],
['John', 22, 'Male', 'B'],
['Katie', 24, 'Female', 'C'],
['Ronaldo', 26, 'Male', 'D'],
];
下面的代碼段將回傳一個僅包含前 2 列的新 2D 陣列:
const data = [
['Name', 'Age', 'Gender', 'Country'],
['Annie', 26, 'Female', 'A'],
['John', 22, 'Male', 'B'],
['Katie', 24, 'Female', 'C'],
['Ronaldo', 26, 'Male', 'D'],
];
const getFirstTwoCols = data => data.map(row => [row[0], row[1]]);
console.log(getFirstTwoCols(data));
然后您可以將新資料粘貼到您喜歡的位置,例如:
const pasteData = () => {
const newData = getFirstTwoCols(data)
SpreadsheetApp
.getActive()
.getSheetByName('Sheet2')
.getRange(1, 1, newData.length, newData[0].length)
.setValues(newData);
}
uj5u.com熱心網友回復:
在您的情況下,以下示例腳本如何?
示例腳本:
function myFunction() {
// This is your 2D list.
const data = [["Name", "Age", "Gender", "Country"],
["Annie", "26", "Female", "A"],
["John", "22", "Male", "B"],
["Katie", "24", "Female", "C"],
["Ronaldo", "26", "Male", "D"]];
const selected = ["Name", "Age"]; // This is your selected columns.
// 1. Transpose the 2D list.
const transpose = data[0].map((_, c) => data.map(r => r[c]));
// 2. Retrieve the selected columns.
const cols = transpose.reduce((ar, c) => {
if (selected.includes(c[0])) ar.push(c);
return ar;
}, []);
// 3. Transpose the selected columns.
const values = cols[0].map((_, c) => cols.map(r => r[c]));
// 4. Put the values to the Spreadsheet.
const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1"); // Please set the sheet name.
sheet.getRange(1, 1, values.length, values[0].length).setValues(values);
}
- 我認為
data也可以從電子表格中檢索的值。
參考:
- 地圖()
uj5u.com熱心網友回復:
function myfunk() {
const ss = SpreadsheetApp.getActive();
const sh = ss.getSheetByName('Sheet0');//I pasted your list into spreadsheet
const list = sh.getDataRange().getValues();
const osh = ss.getSheetByName('Sheet1');
let oA = list.map(r => [r[0],r[1]]);
osh.getRange(1,1,oA.length,oA[0].length).setValues(oA);
SpreadsheetApp.flush();
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/358806.html
