0

我目前正在通过 API 请求学习 Excel Office 脚本。当然我不是程序员。

在这里,我在 Jquery 中很容易做的事情在 Excel Office Script 中让我头疼。我似乎无法正确构造对象以便在页面上设置值,并在 Power Automate 中使用该对象。

最后我的错误与我必须构建与“接口”相关的数组的方式有关。我仍然无法弄清楚如何构造它:错误最终出现在 setValues 处——setValues 的尺寸不正确。

出于理解目的:我要求将 JotForm 直接提交到 Excel Online,因此我无法完全提供我的代码。但我可以展示一个编辑过的 Json 并解释我的过程。

1° Excel办公脚本


    async function main(workbook: ExcelScript.Workbook): Promise<void> {
        
        const workSheet = workbook.getActiveWorksheet();
        let fetchResult = await fetch(myApiQuery)
        
        let json: JSONData[] = await fetchResult.json();
        
        // From here, I don't need the complete answer, I filter the Json Object from ["content"]
        const result: JSONData[] = json["content"]
        const rows: (string | boolean | number)[][] = [];

// FROM HERE, I want to iterate through the object.
// Basically, the structure of my code should work like this : 
// iterate through "CONTENT" -> Iterate THROUGH "ANSWERS" -> IS "answer" UNDEFINED ? (if UNDEFINED : return empty, if not return the answer). 
//See JSON below.

        for (const [key, value] of Object.entries(result)) {
           
            rows.push([value["id"],value["created_at"],value["answers"]])
                  
            for (const [subKey, subValue] of Object.entries(value["answers")) {
                if (typeof subValue["answer"] !== "undefined") {
                   rows.push([subValue["answer"]])
                }
                else {
                    rows.push([""])
                }
         }


     console.log(rows);
     const targetRange = workSheet.getRange('A2').getResizedRange(rows.length - 1, rows[0].length - 1);
     targetRange.setValues(rows);


return;


}


// This is what I understood will be important for Power Automate
   interface JSONData {
        id?:number
        created_at?:number
        answers?:SUBDATA;
    }

    interface SUBDATA{
            answer?:string;


    }


2°) 这是来自我的 console.log (console.log(rows)) 的 JSON 对象。我编辑了个人信息并将其从数以千计的行中删除。如您所见,在“ANSWERS”(复数)中,有时定义了“answer”(单数),有时没有定义。我需要能够有所作为,如果未定义以保持问题和答案之间的对应关系,则返回空白。

[
    {
        "id": "---",
        "form_id": "---",
        "ip": "---",
        "created_at": "2021-09-18 07:39:14",
        "updated_at": null,
        "answers": {
            "1": {
                "name": "vousAvez",
                "order": "6",
                "text": "QUESTION",
                "type": "control_head"
            },
            "2": {
                "name": "email",
                "order": "7",
                "text": "Email",
                "type": "control_email",
                "answer": "email Address" }
        }
    ],
    [""],
    [""],
    [""],
    ["emailAdress"],
    ["Name"],
    ["FristName"],
    [""],
    [""],
]

这是一个适用于 JQUERY 的示例

 $.each(responseText["content"], function (index, element) {
       items.push("<br/><span style='color:red'>" + element["id"] + " - " + element["created_at"] + "</span><br/><br/>");
       $.each(element["answers"], function (subIndex, subElement) {
          if (typeof subElement["answer"] !== "undefined") {
             items.push("<li id='" + subIndex + "'>" + subElement["name"] + "<span style='color:blue'> " + subElement["answer"] + "</span></li>");
          }
          else {
             items.push("<li id='" + subIndex + "'>" + subElement["name"] + ": </li > ");
          }
          items.push('<br/>');
          })
})
 $("<ul/>", {
       "class": "my-new-list",
       html: items.join("")
 }).appendTo("body");

4

1 回答 1

1

在 TypeScript Playground 中试试这个例子

我建议dataArrayInput用您的数据替换 并在 TypeScript Playground 中使用它,直到该printDataAnswers方法按您的预期工作并返回您正在寻找的值。然后,您可以将其复制到现有逻辑中。



// define data interface

interface Data {
    id: string;
    form_id: string;
    ip: string;
    created_at: string;
    updated_at: string | null;
    answers: {
        [key: string]: {
            name: string;
            order: string;
            text: string;
            type: string;
            answer?: string;
        }
    }
}

// example of static data
const dataArrayInput: Data[] = [
    {
        "id": "---",
        "form_id": "---",
        "ip": "---",
        "created_at": "2021-09-18 07:39:14",
        "updated_at": null,
        "answers": {
            "1": {
                "name": "vousAvez",
                "order": "6",
                "text": "QUESTION",
                "type": "control_head"
            },
            "2": {
                "name": "email",
                "order": "7",
                "text": "Email",
                "type": "control_email",
                "answer": "email Address" }
        }
    },
];


/**
 * Iterates through all answers in an array of data and returns and array all the string answers.
 */
function printDataAnswers(dataArray: Data[]) {

// iterate through data and pull out answers
    const allAnswers: string[] = []
    dataArray.forEach((data) => {
        const {answers} = data; // destructure object
        if (answers) {
            // iterate through answer key and values
            for (const [key, value] of Object.entries(answers)) {
                console.log(key);
                const {answer} = value; // destructure object
                const answerOrEmpty = answer || "";
                console.log(answerOrEmpty);        
                allAnswers.push(answerOrEmpty);    
            }
        }
    });

    return allAnswers;
}

const answerArray = printDataAnswers(dataArrayInput);
console.log(answerArray);

于 2021-10-06T21:27:06.207 回答