Html to excel images

I have got my html file with html table with the embedded image using tag
[ img src=»data:image/png;base64, ] . I would like to convert it to excel with image columns showing the actual image. When I open this html file in excel , the table is shown fine but the image is shown with red cross place holder as shownExcel import with embedded image

Is there any way to convert this base64 encoded image to be displayed in excel cells ?

regards

asked Jun 18, 2016 at 20:21

mahbh2001's user avatar

3

An update to the answer by Peter above. It took me another hour or so to figure out how to handle this. Here is an example of how to structure your html file:

MIME-Version: 1.0
Content-Type: multipart/mixed; boundary="12345"

--12345
Content-Type: image/jpg;name="logo.jpg"
Content-Transfer-Encoding: base64
Content-ID: <logo.jpg@site.com>

/9j/4QAYRXhpZgAASUkqAAgAAAAAAAA...
--12345
Content-Type: text/html; charset="utf-8"

<html>
    <!-- Your HTML -->
    <!-- Somewhere in the HTML, replace your images with this, matching the content-id you created above -->
    <img width="your width" height="your height" src="cid:logo.jpg@site.com" />
</html>
--12345--

This can be done multiple times for multiple images, just with different names / content-ids. You MUST have the line at the end in order for it to work too.

answered Jul 24, 2018 at 17:59

Corey Cunha's user avatar

1

Use mime type will work.
This is an example:

------BOUNDARY_1502961982957--
Content-Location: file:///tmp/1502961982957/main.files/1502961983076.png
Content-Transfer-Encoding: base64
Content-Type: image/png

iVBORw0KGgoAAAANSUhEUgAAAQQAAAEsCAYAAAAl981RAA...

Peter Tretyakov's user avatar

answered Aug 17, 2017 at 9:38

Sun Zhen's user avatar

Sun ZhenSun Zhen

331 silver badge4 bronze badges

2

give full path in img tag.
src=’full html path’

answered Aug 9, 2021 at 7:25

guest's user avatar

1

The following methods can be exported to Excel using JSON data to generate images to Excel, and data can also be exported to Excel.

Support for exporting images of HTTP or HTTS, temporarily not supporting the picture format of Base64.

effect

Code:

index.html

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Export images and data to Excel</title>
</head>
<body>
</body>
<script src="export2Excel.js"></script>
<script>
         // Theader and TBODY data need one answer
    let tHeader = [
		'Flowers',
		'colour',
		'photo'
	]
	let tbody = [
		{
			name: 'Rose',
			color: 'red',
			pic: 'https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=2801998497,4036145562&fm=27&gp=0.jpg'
		},
		{
			name: 'chrysanthemum',
			color: 'yellow',
			pic: 'https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=1506844670,1837003941&fm=200&gp=0.jpg'
		},
		{
			name: 'Morning glory',
			color: 'purple',
			pic: 'https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=3056120770,1115785765&fm=27&gp=0.jpg'
		},
		{
			name: 'Plum,
			color: 'white',
			pic: 'https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=2700343322,3431874915&fm=27&gp=0.jpg'
		},
		{
			name: 'Peach flower,
			color: 'Pink',
			pic: 'https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=602076004,4209938077&fm=27&gp=0.jpg'
		}
	]
	export2Excel(tHeader, tbody, 'I love flowers')
</script>
</html>

export2Excel.js

/* eslint-disable */
let idTmr;
const getExplorer = () => {
  let explorer = window.navigator.userAgent;
  //ie
  if (explorer.indexOf("MSIE") >= 0) {
    return 'ie';
  }
  //firefox
 
  else if (explorer.indexOf("Firefox") >= 0) {
    return 'Firefox';
  }
  //Chrome
  else if (explorer.indexOf("Chrome") >= 0) {
    return 'Chrome';
  }
  //Opera
  else if (explorer.indexOf("Opera") >= 0) {
    return 'Opera';
  }
  //Safari
  else if (explorer.indexOf("Safari") >= 0) {
    return 'Safari';
  }
}
/ / Judging whether the browser is IE
const exportToExcel = (data,name) => {
 
     / / Judgment is IE
  if (getExplorer() == 'ie') {
    tableToIE(data, name)
  } else {
    tableToNotIE(data,name)
  }
}
 
const Cleanup = () => {
  window.clearInterval(idTmr);
}
 
 // IE execution under IE browser
const tableToIE = (data, name) => {
  let curTbl = data;
  let oXL = new ActiveXObject("Excel.Application");
 
     // Create an AX object Excel
  let oWB = oXL.Workbooks.Add();
     / / Get Workbook objects
  let xlsheet = oWB.Worksheets(1);
     // Activate the current sheet
  let sel = document.body.createTextRange();
  sel.moveToElementText(curTbl);
     // Move the content in the table to TextRange
  sel.select;
     // All selection of textRange
  sel.execCommand("Copy");
     // Copy the contents of the TextRange
  xlsheet.Paste();
     // Paste into the EXCEL
 
  oXL.Visible = true;
     // Set an Excel visible attribute
 
  try {
    let fname = oXL.Application.GetSaveAsFilename("Excel.xls", "Excel Spreadsheets (*.xls), *.xls");
  } catch (e) {
    print("Nested catch caught " + e);
  } finally {
    oWB.SaveAs(fname);
 
    oWB.Close(savechanges = false);
    //xls.visible = false;
    oXL.Quit();
    oXL = null;
         // End the Excel process, exit completion
    window.setInterval("Cleanup();", 1);
    idTmr = window.setInterval("Cleanup();", 1);
  }
}
 
 // Not executing under non-IE browser
const tableToNotIE = (function() {
     // Encoding To use UTF-8, the default GBK will appear Chinese garbled
  let 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><meta 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>',
    base64 = function(s) {
      return window.btoa(unescape(encodeURIComponent(s)));
 
    },
 
    format = (s, c) => {
      return s.replace(/{(w+)}/g,
        (m, p) => {
          return c[p];
        })
    }
  return (table, name) => {
    let ctx = {
      worksheet: name,
      table
    }
 
         // Create download
    let link = document.createElement('a');
    link.setAttribute('href', uri + base64(format(template, ctx)));
 
    link.setAttribute('download', name);
 
 
    // window.location.href = uri + base64(format(template, ctx))
    link.click();
  }
})()
 
 // Export function
const export2Excel = (theadData, tbodyData, dataname) => {
 
  let re =  / http / // string contains http, then default is the image address
  let th_len =  ThetData.length // Length of the head
  let tb_len =  TBODYDATA.LENGTH / / number of records
  let width =  40 // Set the picture size
  let height = 60
 
     // Add a header information
  let thead = '<thead><tr>'
  for (let i = 0; i < th_len; i++) {
    thead += '<th>' + theadData[i] + '</th>'
  }
  thead += '</tr></thead>'
 
     / / Add each row of data
  let tbody = '<tbody>'
  for (let i = 0; i < tb_len; i++) {
    tbody += '<tr>'
    let row = tbodyData[i]  / / Get each row of data
 
    for (let key in row) {
      if (re.test(row[key])) {  // If you are a picture, you need to add a DIV to package the image.
        // 
        tbody += '<td style="width:' + width + 'px; height:' + height + 'px; text-align: center; vertical-align: middle"><div style="display:inline"><img src='' + row[key] + '' ' + ' ' + 'width=' + '"' + width + '"' + ' ' + 'height=' + '"' + height + '"' + '></div></td>'
      } else {
        tbody += '<td style="text-align:center">' + row[key] + '</td>'
      }
    }
    tbody += '</tr>'
  }
  tbody += '</tbody>'
 
  let table = thead + tbody
 
     // Export form
  exportToExcel(table, dataname)
}

My readers continuously asked me to work on how to export html table data to excel, CSV, PNG, PDF, TXT, Doc, JSON & XML instead of copying the records manually. So I thought to share this wonderful jquery plugin I have come across via google to my readers.

This plugin is very easy to implement it in your projects who wants to export the html table data instantly.

Beauty of this Export HTML table to Excel jQuery plugin is which allows you to download any html table data into all downloadable formats like Excel, CSV, PDF, DOC and many more. This is the must required plugin for any reporting / statistics kind of projects.

Now a days Exporting Table Data into Specific Format is a very common feature in every web application.

Please check my popular post on Top 20 code snippets in jQuery

Export HTML Table Data to CSV, Excel, PNG, PDF, TXT, Doc, JSON & XML using jQuery

Export HTML Table Data to Excel, CSV, PDF

Contents

  • 1 Export HTML Table Data to Excel Plugin Features
    • 1.1 Installation
  • 2 Export html table data to Excel (XLSX) format
  • 3 Export html table data to PNG format
  • 4 Export html table data to PDF format
    • 4.1 Usage
    • 4.2 PDF export using jsPDF
    • 4.3 Other Types
  • 5 Download HTML Table Data to Excel, CSV, XML, PDF Plugin

Export HTML Table Data to Excel Plugin Features

We can easily export any html tables to the following formats. Not only table to excel instead you can export html table data to CSV, Excel, PNG, JSON, PDF, JSON, SQL & XML etc

  1. JSON
  2. XML
  3. PNG
  4. CSV
  5. TXT
  6. SQL
  7. MS-Word
  8. Ms-Excel
  9. Ms-Powerpoint
  10. PDF

Installation

You need an jquery plugin to support this feature

<script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.min.js"></script>

In order to save the exported files into your machine, please include the below js in your html code

<script type="text/javascript" src="libs/FileSaver/FileSaver.min.js"></script>

Export html table data to Excel (XLSX) format

To export the table data in excel 2007 format, please include the below js in your html code

<script type="text/javascript" src="libs/js-xlsx/xlsx.core.min.js"></script>

You need an below script to export html table data to PNG format. html2canvas.js.

I have added IE support also to export HTML table to PNG.

<!-- For IE support include es6-promise before html2canvas -->

<script type="text/javascript" src="libs/es6-promise/es6-promise.auto.min.js"></script>

<script type="text/javascript" src="libs/html2canvas/html2canvas.min.js"></script>

Export html table data to PDF format

<script type="text/javascript" src="libs/jsPDF/jspdf.min.js"></script>

<script type="text/javascript" src="libs/jsPDF-AutoTable/jspdf.plugin.autotable.js"></script>

Finally you have to include this table export plugin to work successfully in the html table

<script type="text/javascript" src="tableExport.min.js"></script>

Usage

<a href="#" onClick ="$('#tableID').tableExport({type:'json',escape:'false'});">JSON</a>
<a href="#" onClick ="$('#tableID').tableExport({type:'excel',escape:'false'});">XLS</a>
<a href="#" onClick ="$('#tableID').tableExport({type:'csv',escape:'false'});">CSV</a>
<a href="#" onClick ="$('#tableID').tableExport({type:'pdf',escape:'false'});">PDF</a>

PDF export using jsPDF

please use the below configuration to use jsPDF

$('#tableID').tableExport({
type:'pdf',
jspdf: {
orientation: 'p',
margins: {
left:20, top:10
},
autotable: false
}
});

Other Types

{type:'json',escape:'false'}
{type:'json',escape:'false',ignoreColumn:'[2,3]'}
{type:'json',escape:'true'}
{type:'xml',escape:'false'}
{type:'sql'}
{type:'csv',escape:'false'}
{type:'txt',escape:'false'}
{type:'excel',escape:'false'}
{type:'doc',escape:'false'}
{type:'powerpoint',escape:'false'}
{type:'png',escape:'false'}
{type:'pdf',pdfFontSize:'7',escape:'false'}

View Live Demo

Download HTML Table Data to Excel, CSV, XML, PDF Plugin

Please download this HTML table to EXCEL, CSV Format plugin by sharing this in your social media and support my work

Credit – https://github.com/kayalshri/tableExport.jquery.plugin

You May Also Like

This question has been asked a few other posts, but the solution is not provided.
I want to get an Excel output from a HTML table with photos and text. I found the following two plugins for the Excel output(The most complete plug in my opinion):

http://ngiriraj.com/pages/htmltable_export/demo.php

and

http://www.jqueryscript.net/table/Export-Html-Table-To-Excel-Spreadsheet-using-jQuery-table2excel.html

<table id="customers" border="1" width="100%" >
<thead>         
    <tr class='warning'>
        <th>Country</th>
        <th>Population</th>
        <th>Date</th>
        <th>%ge</th>
        <th>Photo</th>
    </tr>
</thead>
<tbody>
    <tr>
        <td>Chinna</td>
        <td>1,363,480,000</td>
        <td>March 24, 2014</td>
        <td>19.1</td>
         <td><img src="http://i.stack.imgur.com/CekuQ.jpg" width='60'  height='60'/></td>
    </tr>
    <tr>
        <td>India</td>
        <td>1,241,900,000</td>
        <td>March 24, 2014</td>
        <td>17.4</td>
       <td><img src="http://i.stack.imgur.com/CekuQ.jpg" width='60'  height='60'/></td>
    </tr>
    <tr>
        <td>United States</td>
        <td>317,746,000</td>
        <td>March 24, 2014</td>
        <td>4.44</td>
          <td><img src="http://i.stack.imgur.com/CekuQ.jpg" width='60'  height='60'/></td>
    </tr>
    <tr>
        <td>Indonesia</td>
        <td>249,866,000</td>
        <td>July 1, 2013</td>
        <td>3.49</td>
         <td><img src="http://i.stack.imgur.com/CekuQ.jpg" width='60'  height='60'/></td>
    </tr>
    <tr>
        <td>Brazil</td>
        <td>201,032,714</td>
        <td>July 1, 2013</td>
        <td>2.81</td>
        <td><img src="http://i.stack.imgur.com/CekuQ.jpg" width='60'  height='60'/></td>
    </tr>
</tbody>

and exporting as

<a href="#" onClick="$('#customers').tableExport({type:'excel',escape:'false'});">export</a>

I also included a column with images as shown in this fiddle as

If I export this table to Excel, the images are not showing. So how can I export those images too along with the data. What kind of output should be used?

If this is not possible in Excel output, what format should be used for output?

Продвинутый онлайн-сервис конвертации html файлов в XLS. Для mac & windows


Перетащите файлы сюда. 100 MB максимальный размер файла или Регистрация

Конвертировать в HTML

html

Язык гипертекстовой разметки

HTML ― это файл веб-формата. Исходный код HTML можно изменить в текстовом редакторе. HTML-файлы разрабатываются для будущего использования в веб-браузерах пользователей и позволяют форматировать сайты с текстом, изображениями и другими необходимыми материалами. В файлах этого формата используются теги для создания веб-страниц. Интерпретация HTML-кода выполняется веб-браузером, и этот код, как правило, не показывается пользователю.

Конвертер XLS

xls

Лист Microsoft Excel (97-2003)

Формат XLS используется для описания документов программы Microsoft Excel. Этот файл представляет собой электронную таблицу. Все данные в документе распределены по ячейкам и хранятся в них. Каждая ячейка имеет уникальный адрес, обозначаемый буквами и арабскими цифрами. Ячейка может содержать неизменяемые данные и данные в виде формул, которые связывают несколько ячеек.

Как сконвертировать HTML в XLS

Шаг 1

Загрузите html-файл(ы)

Выберите файлы с компьютера, Google Диска, Dropbox, по ссылке или перетащив их на страницу.

Шаг 2

Выберите «в xls»

Выберите xls или любой другой формат, который вам нужен (более 200 поддерживаемых форматов)

Шаг 3

Загрузите ваш xls-файл

Позвольте файлу сконвертироваться и вы сразу сможете скачать ваш xls-файл

Рейтинг HTML в XLS

4.0 (5,945 голосов)

Вам необходимо сконвертировать и скачать любой файл, чтобы оценить конвертацию!

Like this post? Please share to your friends:
  • Html to excel format text
  • Html files to word
  • Html to excel download
  • Html files to excel
  • Html to excel converters