script-lab icon indicating copy to clipboard operation
script-lab copied to clipboard

Viewing contents of an XML file to Word Task Pane

Open JohnDBCT opened this issue 4 years ago • 2 comments

I have a customized dictionary in text format that is converted to an XML file. ``$("#run").click(() => tryCatch(run));

async function run() { await Word.run(async (context) => { const body = context.document.body;

document.open("C:/Users/.../Documents/Words.xml");
await context.sync();

}); }

/** Default helper for invoking an action and handling errors. */ async function tryCatch(callback) { try { await callback(); } catch (error) { // Note: In a production add-in, you'd want to notify the user through your add-in's UI. console.error(error); } } `` How would I proceed with this task?

Regards,

JohnDBCT

JohnDBCT avatar May 02 '21 03:05 JohnDBCT

For the security reason, You can't read local file by the javascript code. You need to upload the xml file to a server, and use the fetch API to do this.

chenxizhang avatar Sep 04 '22 14:09 chenxizhang

If you are developing a custom web add-in for word, you actually already have a server.

chenxizhang avatar Sep 04 '22 14:09 chenxizhang

This is a great question for Stack Overflow.

I recommend something like the following to prompt for a file to upload.

export function uploadFileJson(): Promise<string> {
    return new Promise((resolve) => {
        console.log("uploadFileJson");
        const element = document.createElement("input");
        element.setAttribute("type", "file");
        element.setAttribute("accept", ".json");
        element.onchange = async (ev) => {
            const target = ev.target as HTMLInputElement;

            const files = target.files || [];

            if (files.length !== 1) {
                console.error(`can only load a single file`);
                return;
            }

            const file = files[0];
            const name = file.name;
            console.log(`uploaded ${name}`);
            const text = await file.text();
            //console.log(text);
            resolve(text);
        };

        element.click();
    });
}

wandyezj avatar Apr 16 '24 17:04 wandyezj