Javascript - export image into excel
Asked Answered
D

3

3

Using this function, I can export image into excel(XLS). This code require physical location of the image. But instead of physical path, I want to pass dataUri of the image. e.g. data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAA...

Is it possible?

function exportExcel() {

    var template = { excel: '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><meta name=ProgId content=Excel.Sheet> <meta name=Generator content="Microsoft Excel 11"><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>' };

    var format = function (s, c) {
        return s.replace(new RegExp("{(\\w+)}", "g"), function (m, p) {
            return c[p];
        });
    };

    var base64 = function (s) {
        return window.btoa(window.unescape(encodeURIComponent(s)));
    };

    var ctx = { worksheet: 'Worksheet', table: '<img src="file://C:/Temp/chart.png" alt="" />' };

    var b64 = base64(format(template.excel, ctx));

    blob = b64toBlob(b64, 'application/vnd.ms-excel');
    var blobUrl = window.URL.createObjectURL(blob);

    var saveLink = document.createElement('a');

    saveLink.download = 'export.xls';
    saveLink.href = blobUrl;
    saveLink.click();
}


function b64toBlob(b64Data, contentType, sliceSize) {
    contentType = contentType || '';
    sliceSize = sliceSize || 512;

    var byteCharacters = window.atob(b64Data);
    var byteArrays = [];

    var offset;
    for (offset = 0; offset < byteCharacters.length; offset += sliceSize) {
        var slice = byteCharacters.slice(offset, offset + sliceSize);

        var byteNumbers = new Array(slice.length);
        var i;
        for (i = 0; i < slice.length; i = i + 1) {
            byteNumbers[i] = slice.charCodeAt(i);
        }

        var byteArray = new window.Uint8Array(byteNumbers);

        byteArrays.push(byteArray);
    }

    var blob = new window.Blob(byteArrays, {
        type: contentType
    });
    return blob;
}

Attached screenshot of requirement. enter image description here Thanks!

Daladier answered 11/5, 2017 at 21:35 Comment(0)
T
1

I ran into the same problem, after several hours researching I solved it this way.

// Code HTML
 <div id="chart-container" style="background: #fff;">
                            <canvas class="mt-5 w-100" id="doughnutChart"></canvas>
 </div>
// Code javascript
// Convert the div to image (canvas)
html2canvas(document.getElementById("chart-container"), {
    onrendered: function (canvas) {
        var img = canvas.toDataURL("image/jpeg", 0.9); //image data of canvas

        var a = document.createElement("a"); //Create <a>
        //a.href = "data:image/png;base64," + ImageBase64; 
        a.href = img;
        a.download = fileName + ".jpeg"; //File name Here

        var uri = 'data:application/vnd.ms-excel;base64,'
            , template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><img src="{table}" alt="grafica" /></body></html>'
            , base64 = function (s) { return window.btoa(unescape(encodeURIComponent(s))) }
            , format = function (s, c) { return s.replace(/{(\w+)}/g, function (m, p) { return c[p]; }) }

        var ctx = { worksheet: name || 'Hoja1', table: fileName + ".jpeg" }
        //window.location.href = uri + base64(format(template, ctx))
        var link = document.createElement("a");
        link.download = fileName+".xls";
        link.href = uri + base64(format(template, ctx));
        link.click();
    }
});

Result: enter image description here

Trellas answered 28/5, 2020 at 22:55 Comment(1)
Thank you @Trellas for the details. I tried this approach but I'm getting excel file without the image. I added a.click() after the a.download = fileName + ".jpeg". This downloaded the image as well and in excel I'm able to see the image. The problem here is, the image in the excel is a linked type. If i remove the image from disk, image in excel also getting removed. How to un-link the image source and keep copied image in excel. Any idea is much appreciatedSoapstone
T
0

Try replacing the file url with the data url....

var ctx = { worksheet: 'Worksheet', table: '<img src="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAA..." alt="" />' };
Tiv answered 11/5, 2017 at 21:42 Comment(1)
Thanks for answer! I tried it but it is NOT working. I observed that image displayed on webpage if I set dataURI to img src. But looks like this function do not handle it.Daladier
H
0

You can not export the image in base64 format to excel. Visit this page : https://www.infragistics.com/community/forums/f/ignite-ui-for-javascript/109480/adding-image-in-excel

Hautemarne answered 24/5, 2018 at 4:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.