JSFiddle - React, Tailwind, and code Playground
HTML
<div style="min-height: 60vh">
<canvas id="canvas" style="background-color: #fff">
</canvas>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.4.1/chart.umd.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/exceljs/4.4.0/exceljs.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2.0.5/FileSaver.min.js"></script>
JavaScript
function TyLyReport() {
var lineChartData = {
labels : ["Jan","Feb","Mar"],
datasets : [
{
label: 'Dataset 1',
borderColor: 'rgba(75, 192, 192, 1)',
backgroundColor: 'rgba(75, 192, 192, 0.2)',
data : [1000, 2000, 2500],
fill: false
},
{
label: 'Dataset 2',
borderColor: '#FF4848',
backgroundColor: 'rgba(255, 72, 72, 0.2)',
data : [1016, 1800, 2900],
fill: false
}
]
};
var ctx = document.getElementById("canvas").getContext("2d");
new Chart(ctx, {
type: 'line',
data: lineChartData,
options: {
responsive : true,
animation: false,
scales: {
y: {
beginAtZero: true
}
}
},
plugins:[
{
beforeDraw(chart){ // White background in the exported image
const {ctx, canvas} = chart;
ctx.save();
ctx.fillStyle = '#FFF';
ctx.fillRect(0, 0, canvas.offsetWidth, canvas.offsetHeight);
ctx.restore();
}
}
]
});
// Export chart image to Excel
exportToExcel();
}
// Function to export chart image to Excel
function exportToExcel() {
const canvas = document.getElementById("canvas");
const image = canvas.toDataURL("image/png").split(';base64,')[1];
// see https://stackoverflow.com/a/63494628/16466946 (not required)
const workbook = new ExcelJS.Workbook();
const worksheet = workbook.addWorksheet('Chart Image');
const imageId = workbook.addImage({
base64: image,
extension: 'png',
});
worksheet.addImage(imageId,
{
tl: { col: 0, row: 0 },
ext: { width:...