如何将对象或 json stringify 传递给 office js 中的自定义函数?

How to pass object or json stringify to custom function in office js?

我正在开发一个 office js 加载项,现在我已经创建了一个按预期工作的自定义函数,但是当我在自定义函数中传递 JSON stringify 字符串时,它不起作用并且不提供任何错误。如果我必须通过一个简单的评论,那么它就可以正常工作。我遵循此解决方案,但运气不佳 https://docs.microsoft.com/en-us/office/dev/add-ins/excel/custom-functions-parameter-options?tabs=javascript。这是我的代码请指导我做错了什么。提前致谢

await Excel.run(async (context) => {
          const wb = context.workbook;
          const range = wb.getSelectedRange();
    
          const abc={id:1,name:"KC"}

         serialzedFieldMappings=JSON.stringify(abc)
    
          try {
            range.formulas = [[`=ANALYST.LOG(${serialzedFieldMappings})`]];
           
          } catch (error) {
            console.log(error);
          }
       
          return context.sync();
        });   

function.json 文件

{
        "functions": [
      {
    "description": "Writes a message to console.log().",
                "id": "LOG",
                "name": "LOG",
                "parameters": [
                    {
                        "description": "String to write.",
                        "name": "message",
                        "type": "string"
                    }
                ],
                "result": {}
            }
        ]
    }

function.js

function logMessage(message) {
  console.log("message", message);
  return `Cmarix Example${message}`;
}
CustomFunctions.associate("LOG", logMessage);

如果要让 Excel 将双引号视为公式中的文字文本,则需要将其转义。试试下面的代码看看是否有帮助:

await Excel.run(async (context) => {
    const wb = context.workbook;
    const range = wb.getSelectedRange();

    const abc = { id: 1, name: "KC" }

    // An additional double quote will escape a double quote.
    let serialzedFieldMappings = JSON.stringify(abc).replace(/"/g, `""`)

    try {
      range.formulas = [[`=("${serialzedFieldMappings}")`]];

    } catch (error) {
      console.log(error);
    }

    return context.sync();
  });

谢谢!

润东

请按照以下解决方案解决您的问题

 await Excel.run(async (context) => {
      console.log("data");
      const wb = context.workbook;
      const range = wb.getSelectedRange();

      const timeDimension: any = selectedTimeDimensions[0];
      const dimension: any = selectedDimensions[0];
      //Create jsonstringfy
      const serialzedFieldMappings = new CellDimensionMapSerializer().Serialize(
        selectedScenario,
        [timeDimension],
        [dimension]
      );
     
      const abc = { id: 1, name: "KC" }
      let datastring = JSON.stringify(abc).split('"').join("'");

      try {
        range.formulas = [[`=ANALYST.COMMENT("${datastring}")`]];
      } catch (error) {
        console.log(error);
      }
      return context.sync();
    });