Skip to content

Instantly share code, notes, and snippets.

@sahil-shubham
Created September 25, 2024 07:55
Show Gist options
  • Save sahil-shubham/2e3b827a0f55ab23111681ae3a90d36d to your computer and use it in GitHub Desktop.
Save sahil-shubham/2e3b827a0f55ab23111681ae3a90d36d to your computer and use it in GitHub Desktop.
Utility function to get the image of used range in sheet. It first stores the original cell dimensions, resizes them to a fixed width and height, takes an image and then resizes them back to original.
const CELL_WIDTH = 60;
const CELL_HEIGHT = 20;
export const getSheetImage = async (): Promise<string> => {
try {
const image = await Excel.run(async (context) => {
const sheet = context.workbook.worksheets.getActiveWorksheet();
const usedRange = sheet.getUsedRange();
usedRange.load("address,columnCount,rowCount,format/columnWidth,format/rowHeight");
await context.sync();
const columnWidths: Excel.Range[] = [];
const rowHeights: Excel.Range[] = [];
for (let i = 0; i < usedRange.columnCount; i++) {
const column = sheet.getRangeByIndexes(0, i, 1, 1);
column.load("format/columnWidth");
columnWidths.push(column);
}
for (let i = 0; i < usedRange.rowCount; i++) {
const row = sheet.getRangeByIndexes(i, 0, 1, 1);
row.load("format/rowHeight");
rowHeights.push(row);
}
await context.sync();
usedRange.format.columnWidth = CELL_WIDTH;
usedRange.format.rowHeight = CELL_HEIGHT;
await context.sync();
const usedRangeImage = usedRange.getImage();
await context.sync();
for (let i = 0; i < usedRange.columnCount; i++) {
sheet.getRangeByIndexes(0, i, 1, 1).format.columnWidth = columnWidths[i].format.columnWidth;
}
for (let i = 0; i < usedRange.rowCount; i++) {
sheet.getRangeByIndexes(i, 0, 1, 1).format.rowHeight = rowHeights[i].format.rowHeight;
}
return usedRangeImage.value;
});
return image;
} catch (error) {
console.log("ERROR WHILE TAKING RANGE IMAGE", error);
throw error;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment