protobi / js-xlsx

XLSX / XLSM / XLSB (Excel 2007+ Spreadsheet) / ODS parser and writer
http://oss.sheetjs.com/js-xlsx
Other
814 stars 416 forks source link

Loading this fork #92

Open Suncatcher opened 6 years ago

Suncatcher commented 6 years ago

How to properly load this for onto webpage?

<script lang="javascript" src="dist/xlsx.core.min.js"></script>

This way doesn't work. What is the dist in this link? Can anybody give me the full link to fork lib?

Suncatcher commented 6 years ago

Are the differences between original SheetJS and this fork are significant? The code written for original doesn't work with fork. Are modules cpexcel.js and ods.js are essential for functioning? If I load xlsx.core.full.js, does it include these modules?

pietersv commented 6 years ago

The module cptable is part of the core SheetJS/xlsx library, and I believe it is important. It comes from the repo https://github.com/SheetJS/js-codepage which defines single- or double-byte character sets which Excel uses in lieu of Unicode encodings.

The dist reference is folder dist in the top-level directory of this repo. One approach is to copy the file down to a directory in your project, e.g. /public/javascripts and reference it that way from the web page.

I believe the file xlsx.full.min.js should have the dependencies including cptable included.

Suncatcher commented 6 years ago

Thanks for your response!

I believe the file xlsx.full.min.js should have the dependencies including cptable included.

I removed cptable+xlsx.core.min declaration from my project and included xlsx.full.min instead, and my coding stopped working. So your assumption seems to be wrong.

pietersv commented 6 years ago

Below is a working browser example based on http://sheetjs.com/demos/table.html.

The cptable and ods modules are core library methods outside the scope of this styles branch, so one one hand they shouldn't have changed here. Try code from the latest version of this repo, it's possible it's ahead of the npm version. Do you have a small example of the code that isn't working?

<!DOCTYPE html>
<!-- (C) 2013-present  SheetJS http://sheetjs.com -->
<!-- vim: set ts=2: -->
<html>
<head>
  <title>SheetJS JS-XLSX In-Browser HTML Table Export Demo</title>
  <style>
    .xport, .btn {
      display: inline;
      text-align:center;
    }
    a { text-decoration: none }
  </style>
</head>
<body>
<!-- SheetJS js-xlsx library -->
<script type="text/javascript" src="//rawgit.com/protobi/js-xlsx/master/shim.js"></script>
<script type="text/javascript" src="//unpkg.com/xlsx/dist/xlsx.full.min.js"></script>

<!-- FileSaver.js is the library of choice for Chrome -->
<script type="text/javascript" src="//rawgit.com/eligrey/Blob.js/master/Blob.js"></script>
<script type="text/javascript" src="//rawgit.com/eligrey/FileSaver.js/master/FileSaver.js"></script>

<!-- FileSaver doesn't work in older IE and newer Safari; Downloadify is the flash fallback -->
<script type="text/javascript" src="http://sheetjs.com/demos/swfobject.js"></script>
<script type="text/javascript" src="http://sheetjs.com/demos/downloadify.min.js"></script>
<script type="text/javascript" src="http://sheetjs.com/demos/base64.min.js"></script>

<script>
  function s2ab(s) {
    if(typeof ArrayBuffer !== 'undefined') {
      var buf = new ArrayBuffer(s.length);
      var view = new Uint8Array(buf);
      for (var i=0; i!=s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
      return buf;
    } else {
      var buf = new Array(s.length);
      for (var i=0; i!=s.length; ++i) buf[i] = s.charCodeAt(i) & 0xFF;
      return buf;
    }
  }

  function export_table_to_excel(id, type, fn) {
    var wb = XLSX.utils.table_to_book(document.getElementById(id), {sheet:"Sheet JS"});
    var wbout = XLSX.write(wb, {bookType:type, bookSST:true, type: 'binary'});
    var fname = fn || 'test.' + type;
    try {
      saveAs(new Blob([s2ab(wbout)],{type:"application/octet-stream"}), fname);
    } catch(e) { if(typeof console != 'undefined') console.log(e, wbout); }
    return wbout;
  }

  function doit(type, fn) { return export_table_to_excel('table', type || 'xlsx', fn); }
</script>
<pre>
<h3><a href="//sheetjs.com/">SheetJS</a> JS-XLSX In-Browser HTML Table Export Demo</h3>
<b>Compatibility notes:</b>
- Editable table leverages the HTML5 contenteditable feature, supported in <a href="http://caniuse.com/#search=contenteditable">most browsers</a>
- IE6-9 require a Flash-based shim to download files.  This demo uses <a href="https://github.com/dcneiner/downloadify">Downloadify.js</a>
- iOS Safari file download may not work. <a href="https://github.com/eligrey/FileSaver.js/issues/12">FileSaver.js known bug</a>

<b>Editable Data Table:</b> (click a cell to edit it)
</pre>
<div id="container"></div>
<script type="text/javascript">
  var aoa = [
    ["This",   "is",     "a",    "Test"],
    ["\u0BEE", "\u2603", "你好", "아침글"],
    [1,        2,        3,      4],
    ["Click",  "to",     "edit", "cells"]
  ];
  var ws = XLSX.utils.aoa_to_sheet(aoa);
  document.getElementById("container").innerHTML = XLSX.utils.sheet_to_html(ws, { editable:true }).replace("<table>", '<table id="table" border="1">');
</script>
<br />
<pre><b>Export it!</b></pre>
<table id="xport">
  <tr><td><pre>XLSX Excel 2007+ XML</pre></td><td>
    <!--[if gt IE 9]>-->
    <p id="xportxlsx" class="xport"><input type="submit" value="Export to XLSX!" onclick="doit('xlsx');"></p>
    <!--<![endif]-->
    <p id="xlsxbtn" class="btn">Flash required for actually downloading the generated file.</p>
  </td></tr>
  <tr><td><pre>XLSB Excel 2007+ Binary</pre></td><td>
    <!--[if gt IE 9]>-->
    <p id="xportxlsb" class="xport"><input type="submit" value="Export to XLSB!" onclick="doit('xlsb');"></p>
    <!--<![endif]-->
    <p id="xlsbbtn" class="btn">Flash required for actually downloading the generated file.</p>
  </td></tr>
  <tr><td><pre>XLS Excel 97-2004 Binary</pre></td><td>
    <!--[if gt IE 9]>-->
    <p id="xportbiff8" class="xport"><input type="submit" value="Export to XLS!"  onclick="doit('biff8', 'test.xls');"></p>
    <!--<![endif]-->
    <p id="biff8btn" class="btn">Flash required for actually downloading the generated file.</p>
  </td></tr>
  <tr><td><pre>ODS</pre></td><td>
    <!--[if gt IE 9]>-->
    <p id="xportods" class="xport"><input type="submit" value="Export to ODS!"  onclick="doit('ods');"></p>
    <!--<![endif]-->
    <p id="odsbtn" class="btn">Flash required for actually downloading the generated file.</p>
  </td></tr>
  <tr><td><pre>Flat ODS</pre></td><td>
    <!--[if gt IE 9]>-->
    <p id="xportfods" class="xport"><input type="submit" value="Export to FODS!"  onclick="doit('fods', 'test.fods');"></p>
    <!--<![endif]-->
    <p id="fodsbtn" class="btn">Flash required for actually downloading the generated file.</p>
  </td></tr>
</table>
<pre><b>Powered by the <a href="//sheetjs.com/opensource">community version of js-xlsx</a></b></pre>
<script type="text/javascript">var fallback = false;</script>
<!--[if lte IE 9]><script type="text/javascript">fallback = true;</script><![endif]-->
<script type="text/javascript">
  function tableau(pid, iid, fmt, ofile) {
    if(fallback) {
      if(document.getElementById(iid)) document.getElementById(iid).hidden = true;
      Downloadify.create(pid,{
        swf: 'media/downloadify.swf',
        downloadImage: 'download.png',
        width: 100,
        height: 30,
        filename: ofile, data: function() { var o = doit(fmt, ofile); return window.btoa(o); },
        transparent: false,
        append: false,
        dataType: 'base64',
        onComplete: function(){ alert('Your File Has Been Saved!'); },
        onCancel: function(){ alert('You have cancelled the saving of this file.'); },
        onError: function(){ alert('You must put something in the File Contents or there will be nothing to save!'); }
      });
    } else document.getElementById(pid).innerHTML = "";
  }
  tableau('biff8btn', 'xportbiff8', 'biff8', 'test.xls');
  tableau('odsbtn',   'xportods',   'ods',   'test.ods');
  tableau('fodsbtn',  'xportfods',  'fods',  'test.fods');
  tableau('xlsbbtn',  'xportxlsb',  'xlsb',  'test.xlsb');
  tableau('xlsxbtn',  'xportxlsx',  'xlsx',  'test.xlsx');

</script>
<script type="text/javascript">
  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-36810333-1']);
  _gaq.push(['_setDomainName', 'sheetjs.com']);
  _gaq.push(['_setAllowLinker', true]);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();
</script>
</body>
</html>
Suncatcher commented 6 years ago

First of all, your sample is not functional. This is what I get in Chrome 62:

untitled

Here is the sample of my code:

 var wb = new Workbook();
 var sheets = ['лист 1', 'лист 2'];
 var sheet;
 var raw_header;
 var raw_data;
 var result;
 var datas = [];
   for (var j=0; j<sheet_names.length; j++) {
       raw_header = buildHeader(sheet_names[j]);
       raw_data = buildTable(table_names[j]);
       result = raw_header.texts.concat(raw_data);
       sheet = sheet_from_array_of_arrays(result, sheet_names[j]);
       sheet['!cols'] = wscols[j];
       sheets.push(sheet);
       wb.SheetNames.push(sheet_names[j]);
       wb.Sheets[sheet_names[j]] = sheets[j];
   }
   var wbout = XLSX.write(wb,
   {autoWidth:true, bookType:'xlsx', bookSST:true, type: 'binary'} );
   saveAs(new Blob([s2ab(wbout)],{type:"application/octet-stream"}), "sample.xlsx");
   some_dummy_function();

I use Unicode names for my lists, maybe that is the problem. This part is dependent from cptable.js, which xlsx.full.min.js doesn't include. Also I don't use shim.js. What is the use of it?

pietersv commented 6 years ago

@Suncatcher Hm, the code is definitely functional, I'd run the code before posting. From the screenshot it looks like your machine isn't finding the JS source files like xlsx.full.min.js, blob.js, FileSaver.js and shim.js.

Did you open the HTML from a server (e.g. http://localhost:5000/example.html) or from the file system (e.g. file:///Users/me/myprojects/public/example.html)? if the latter, either download the JS files your file system or change the URLs to specify http: before the //

Looking at the content of shim.js it looks like it adds array functions that might not have been present in earlier browser versions.

Suncatcher commented 6 years ago

if the latter, either download the JS files your file system or change the URLs to specify http: before the //

Yep, it was the URL issue. But could you provide some example with styles? My style piece doesn't work with xlsx.full.min.js

function sheet_from_array_of_arrays(data, sheet) {
  var ws = {};
  var mline = 0;

  var range = {s: {c:10000000, r:10000000}, e: {c:0, r:0 }};
  for(var R = 0; R != data.length; ++R) {
    for(var C = 0; C != data[R].length; ++C) {
      if(range.s.r > R) range.s.r = R;
      if(range.s.c > C) range.s.c = C;
      if(range.e.r < R) range.e.r = R;
      if(range.e.c < C) range.e.c = C;
      var cell = {v: data[R][C] };
      if(cell.v == null) continue;
      var cell_ref = XLSX.utils.encode_cell({c:C,r:R});

      if(typeof cell.v === 'number') cell.t = 'n';
      else if(typeof cell.v === 'boolean') cell.t = 'b';
      else if(cell.v instanceof Date) {
        cell.t = 'n'; cell.z = XLSX.SSF._table[14];
        cell.v = datenum(cell.v);
      }
      else cell.t = 's';

      if(C < 15){
        cell.s={
          alignment:{
          vertical: "center",
          horizontal: "center",
          wrapText: true
          }
        }
      }

   if(R == 0){
        cell.s={
          font:{
            bold:true
          },
          fill:{
            fgColor:{ rgb: "D9D9D9" }
          },
          alignment:{
          vertical: "center",
          horizontal: "center",
          wrapText: true
          },
          border: {
              top: { style: "thin", color: { auto: 1} },
              right: { style: "thin", color: { auto: 1} },
              bottom: { style: "thin", color: { auto: 1} },
              left: { style: "thin", color: { auto: 1} }
          }
        }
     }
}

We are speaking in the xlsx-style section, not in the main branch indeed. The main intention of switching to this fork was style support.

CannonLock commented 4 years ago

I am having a similar problem where the library that I am loading does not support the style feature. This may be due to my lack of understanding of another greater concept. When I use am I not just loading the SheetJS file that does not support styling?

pietersv commented 4 years ago

I think the url //unpkg.com/xlsx/dist/xlsx.full.min.js is referencing the original SheetJS

pietersv commented 4 years ago

I'd recommend pulling the code straight from GitHub. Either save the actual file in your project under a directory like /src/vendor/xlsx.min.js/ or as we do in the limited cases where we use this library, use npm install github:protobi/js-xlsx, which adds the following line to package.json:

"dependencies": {
...
"xlsx": "github:protobi/js-xlsx"
}