问题
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!
回答1:
Try replacing the file url with the data url....
var ctx = { worksheet: 'Worksheet', table: '<img src="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAA..." alt="" />' };
回答2:
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
来源:https://stackoverflow.com/questions/43925959/javascript-export-image-into-excel