1

JavaScript function to create the line chart:

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");
            window.myLine = new Chart(ctx, {
                type: 'line',
                data: lineChartData,
                options: {
                    responsive : true,
                    scales: {
                        yAxes: [{
                            ticks: {
                                beginAtZero: true
                            }
                        }]
                    }
                }
            });

            // Export chart image to Excel
            exportToExcel();
        }
 // Function to export chart image to Excel
        function exportToExcel() {
            var canvas = document.getElementById("canvas");
            var image = canvas.toDataURL("image/png");

            var workbook = new ExcelJS.Workbook();
            var worksheet = workbook.addWorksheet('Chart Image');
            var imageId = workbook.addImage({
                base64: image,
                extension: 'png',
            });
            worksheet.addImage(imageId, 'A1');

            workbook.xlsx.writeBuffer().then(function(buffer) {
                saveAs(new Blob([buffer]), 'chart_image.xlsx');
            });
        }

        // Call the TyLyReport function when the window loads
        window.onload = TyLyReport;

By using the above code, I can able to download the excel and export the chart image seperately but image is not created inside the excel. Can anyone please guide me to export inside the excel. I need to export image in excel like the below image enter image description here

1 Answer 1

1

I am not sure what exactly happens in the code you posted, since the library versions that are used are not specified. It's possible that it actually works, but the image is hardly visible, very small, confined to one cell (A1) and transparent.

In order to be initially visible, the image should be given width and height values, so I adopted the solution in the "Add an image to a cell".

Since it was not specified in the question, I used the latest versions of all libraries; chart.js v4 required some alterations to the configuration object. It also required that the animation is disabled; an alternative would have been to set the exporting of the image after the animation has ended, using the onComplete handler.

I also added, if needed, the standard plugin solution for a colour-filled (white) background, since the default transparent one might not be adequate.

Here it is, the modified version:

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: canvas.offsetWidth, height: canvas.offsetHeight}
        }
    );

    workbook.xlsx.writeBuffer().then(function(buffer) {
        saveAs(new Blob([buffer]), 'chart_image.xlsx');
    });
}

TyLyReport();
<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>

The snippet seems to have disabled the download popup; here it is working, in a jsFiddle.

Sign up to request clarification or add additional context in comments.

6 Comments

Thank you @kikon for the perfect working example. can we able to do same process for pdf as well ? can you please help me with the export the chart in pdf
Can you please ask another question for the php part? Not only that stackoverflow has a "one issue per post" requirement, but I would like to see how you set up the code, what library have you chosen for php generation, and how it is different from the questions that are already answered here, like this one
Here's an example jsFiddle using jsPDF for the pdf generation part.
Thank you so much @kikon for the perfect working model. can we able to make the graph in excel interactive rather than image.
stackoverflow.com/questions/78060165/… --- I have added my comments in this question and asked the different question. can you please help me with that @kikon
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.