在javascript中将html内容导出为ex​​cel

时间:2016-12-23 07:56:18

标签: javascript html excel

我将Html内容导出到Excel并在JavaScript中下载Excel。它工作正常,但我的要求是下载没有网格线的Excel,我也想在浏览器中将内容呈现为我的html节目。是否有任何选项或建议在没有网格线的情况下在Excel中呈现Html内容?

以下是我的示例Html:

<div>
<div style="float:left">
NAME:some text
</div>
<div style="float:right">
Number:some number
</div>
</div>
<div>
<table>
  <tr>
    <th>Company</th>
    <th>Contact</th>
    <th>Country</th>
  </tr>
  <tr>
    <td>Alfreds Futterkiste</td>
    <td>Maria Anders</td>
    <td>Germany</td>
  </tr>
  <tr>
    <td>Centro comercial Moctezuma</td>
    <td>Francisco Chang</td>
    <td>Mexico</td>
  </tr>
  <tr>
    <td>Ernst Handel</td>
    <td>Roland Mendel</td>
    <td>Austria</td>
  </tr>
  <tr>
    <td>Island Trading</td>
    <td>Helen Bennett</td>
    <td>UK</td>
  </tr>
  <tr>
    <td>Laughing Bacchus Winecellars</td>
    <td>Yoshi Tannamuri</td>
    <td>Canada</td>
  </tr>
  <tr>
    <td>Magazzini Alimentari Riuniti</td>
    <td>Giovanni Rovelli</td>
    <td>Italy</td>
  </tr>
</table>
</div>

我的Excel表格:enter image description here

我不希望这些网格单元格和我的内容不会呈现为Html内容。

有没有办法在Javascript中使用没有网格线的Html数据准备Excel?

2 个答案:

答案 0 :(得分:5)

你只需添加:

<meta http-equiv="content-type" content="text/plain; charset=UTF-8"/>

在文档的开头,它将按预期开始工作:

<script type="text/javascript">
var tableToExcel = (function() {
  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]--><meta http-equiv="content-type" content="text/plain; charset=UTF-8"/></head><body><table>{table}</table></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]; }) }
  return function(table, name) {
    if (!table.nodeType) table = document.getElementById(table)
    var ctx = {worksheet: name || 'Worksheet', table: table.innerHTML}
    window.location.href = uri + base64(format(template, ctx))
  }
})()
</script>

Fiddle Here.

答案 1 :(得分:0)

我认为您可以使用Apache POI库更新Excel文件。有关详细信息,请参阅https://poi.apache.org/

关于使线条消失,请参阅http://apache-poi.1045710.n5.nabble.com/how-to-make-the-gridline-disappeared-by-API-td2297448.html

Workbook workbook = new HSSFWorkbook();
Sheet sheet = workbook.createSheet("sheet");
sheet.setDisplayGridlines(false);

Remove all borders on a specific excel worksheet using Apache POI

的更多详情