Skip to content

Instantly share code, notes, and snippets.

@MiaofeiWang
Created October 31, 2023 08:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MiaofeiWang/003b0ed6bddca6276c6d39d317bb46a6 to your computer and use it in GitHub Desktop.
Save MiaofeiWang/003b0ed6bddca6276c6d39d317bb46a6 to your computer and use it in GitHub Desktop.
name: Get SVG image of chart
description: ''
host: EXCEL
api_set: {}
script:
content: |
$("#setup").click(() => tryCatch(setup));
$("#run").click(() => tryCatch(run));
const sheetName = "Sample";
async function run() {
await Excel.run(async (context) => {
const sheet = context.workbook.worksheets.getActiveWorksheet();
const chart = sheet.charts.getItemAt(0);
chart.load("id");
await context.sync();
const shapeChart = sheet.shapes.getItem(chart.id);
let svgString = shapeChart.getAsImage(Excel.PictureFormat.svg);
await context.sync();
console.log(svgString.value);
$("#content-main").html(svgString.value);
// $("#content-main").html(
// '<img src="data:image/png;base64,' + imgString.value + '" style="background-color:black;" />'
// );
});
}
// Add sample worksheet
async function setup() {
await Excel.run(async (context) => {
context.workbook.worksheets.getItemOrNullObject(sheetName).delete();
const sheet = context.workbook.worksheets.add(sheetName);
let range = sheet.getRange("A1:B3");
range.values = [
[12, 5],
[17, 60],
[33, 80]
];
// Add chart
let chart = sheet.charts.add(Excel.ChartType.xyscatterLinesNoMarkers, range, Excel.ChartSeriesBy.columns);
await context.sync();
sheet.activate();
await context.sync();
console.log("done");
});
}
/** 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);
}
}
language: typescript
template:
content: |-
<button id="setup" class="ms-Button">
<span class="ms-Button-label">Setup Chart</span>
</button>
<button id="run" class="ms-Button">
<span class="ms-Button-label">Run</span>
</button>
<h2>Show image blow:</h2>
<div id="content-main"></div>
language: html
style:
content: |-
section.samples {
margin-top: 20px;
}
section.samples .ms-Button, section.setup .ms-Button {
display: block;
margin-bottom: 5px;
margin-left: 20px;
min-width: 80px;
}
language: css
libraries: |
https://appsforoffice.microsoft.com/lib/1/hosted/office.js
@types/office-js
office-ui-fabric-js@1.4.0/dist/css/fabric.min.css
office-ui-fabric-js@1.4.0/dist/css/fabric.components.min.css
core-js@2.4.1/client/core.min.js
@types/core-js
jquery@3.1.1
@types/jquery@3.3.1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment