码迷,mamicode.com
首页 > 编程语言 > 详细

JS-XLS/X读取和解析Excel表格文件(xls/xlsx)的JavaScript插件

时间:2017-05-09 11:25:47      阅读:601      评论:0      收藏:0      [点我收藏+]

标签:demo   object   对象   enter   work   agent   nload   转换   excel表格   

最近有一个要求,我的一个项目中解析Excel文件(与xls/xlsx扩展)在浏览器(使用JavaScript当然)。所以我在网上看了一下,发现了这2个有用的库:

让我们看看他们是如何工作的。

兼容性

支持读取文件格式

  • Excel 2007+ XML Formats (XLSX/XLSM)
  • Excel 2007+ Binary Format (XLSB)
  • Excel 2003-2004 XML Format (XML “SpreadsheetML”)
  • Excel 97-2004 (XLS BIFF8)
  • Excel 5.0/95 (XLS BIFF5)
  • OpenDocument Spreadsheet (ODS)

支持写文件格式

  • XLSX
  • CSV (and general DSV)
  • JSON and JS objects (various styles)

Demo: http://oss.sheetjs.com/js-xlsx

Source: http://git.io/xlsx

JS-XLS

JS-XLS的安装是很简单的,在浏览器中使用该脚本文件,并使用脚本标记加载它:

<!-- https://github.com/SheetJS/js-xls/blob/master/xls.js -->
<script src="/path/to/xls.js"></script>

对于Node.js,只要通过NPM安装:

$ npm install xlsjs
$ node
> require(‘xlsjs‘).readFile(‘excel_file.xls‘);

然后,我们可以简单地使用他们提供的代码在他们的index.html文件解析和转换的xls文件JSON,CSV或公式为基础的输出。

function get_radio_value( radioName ) {
  var radios = document.getElementsByName( radioName );
  for( var i = 0; i < radios.length; i++ ) {
    if( radios[i].checked ) {
      return radios[i].value;
    }
  }
}
 
function to_json(workbook) {
  var result = {};
  workbook.SheetNames.forEach(function(sheetName) {
    var roa = XLS.utils.sheet_to_row_object_array(workbook.Sheets[sheetName]);
    if(roa.length > 0){
      result[sheetName] = roa;
    }
  });
  return result;
}
 
function to_csv(workbook) {
  var result = [];
  workbook.SheetNames.forEach(function(sheetName) {
    var csv = XLS.utils.make_csv(workbook.Sheets[sheetName]);
    if(csv.length > 0){
      result.push("SHEET: " + sheetName);
      result.push("");
      result.push(csv);
    }
  });
  return result.join("\n");
}
 
function to_formulae(workbook) {
  var result = [];
  workbook.SheetNames.forEach(function(sheetName) {
    var formulae = XLS.utils.get_formulae(workbook.Sheets[sheetName]);
    if(formulae.length > 0){
      result.push("SHEET: " + sheetName);
      result.push("");
      result.push(formulae.join("\n"));
    }
  });
  return result.join("\n");
}
 
var tarea = document.getElementById(‘b64data‘);
function b64it() {
  var cfb = XLS.CFB.read(tarea.value, {type: ‘base64‘});
  var wb = XLS.parse_xlscfb(cfb);
  process_wb(wb);
}
 
function process_wb(wb) {
  var output = "";
  switch(get_radio_value("format")) {
    case "json":
      output = JSON.stringify(to_json(wb), 2, 2);
      break;
    case "form":
      output = to_formulae(wb);
      break; 
    default:
      output = to_csv(wb);
  }
  if(out.innerText === undefined) out.textContent = output;
  else out.innerText = output;
}
 
var drop = document.getElementById(‘drop‘);
function handleDrop(e) {
  e.stopPropagation();
  e.preventDefault();
  var files = e.dataTransfer.files;
  var i,f;
  for (i = 0, f = files[i]; i != files.length; ++i) {
    var reader = new FileReader();
    var name = f.name;
    reader.onload = function(e) {
      var data = e.target.result;
      var cfb = XLS.CFB.read(data, {type: ‘binary‘});
      //var arr = String.fromCharCode.apply(null, new Uint8Array(data));
      //var cfb = XLS.CFB.read(btoa(arr), {type: ‘base64‘});
      var wb = XLS.parse_xlscfb(cfb);
      process_wb(wb);
    };
    reader.readAsBinaryString(f);
    //reader.readAsArrayBuffer(f);
  }
}
 
function handleDragover(e) {
  e.stopPropagation();
  e.preventDefault();
  e.dataTransfer.dropEffect = ‘copy‘;
}
 
if(drop.addEventListener) {
  drop.addEventListener(‘dragenter‘, handleDragover, false);
  drop.addEventListener(‘dragover‘, handleDragover, false);
  drop.addEventListener(‘drop‘, handleDrop, false);
}

JS代码很容易理解,它使用了HTML5拖放API允许我们上传文件然后看他们为二进制字符串。二进制,然后直接传递到库,并进一步分析使用此代码:

var cfb = XLS.CFB.read(data, {type: ‘binary‘});
var wb = XLS.parse_xlscfb(cfb);

最终,WB(Workbook)对象是处理并转换成需要的格式(JSON,CSV和Excel公式)。这没有HTML5拖放文件阅读器的API,可用于Node.js代码相同。

注:此模块不支持xlsx。为了克服这一限制,我们可以通过同一作者称为JS-XLSX用另一个包。

JS-XLSX

再次,安装和使用与上一节几乎相同。使用浏览器加载jszip.js和xlsx文件:

<!-- https://github.com/SheetJS/js-xlsx/blob/master/jszip.js -->
<script src="/path/to/jszip.js"></script>
<!-- https://github.com/SheetJS/js-xlsx/blob/master/xlsx.js -->
<script src="/path/to/xlsx.js"></script>

对于Node.js,只要通过NPM安装:

$ npm install xlsx
$ node
> require(‘xlsx‘).readFile(‘excel_file.xlsx‘);

我们可以再次使用项目中的index.html提供代码转换xlsx JSON,CSV或公式为基础的输出。

function get_radio_value( radioName ) {
    var radios = document.getElementsByName( radioName );
    for( var i = 0; i < radios.length; i++ ) {
        if( radios[i].checked ) {
            return radios[i].value;
        }
    }
}
 
function to_json(workbook) {
    var result = {};
    workbook.SheetNames.forEach(function(sheetName) {
        var roa = XLSX.utils.sheet_to_row_object_array(workbook.Sheets[sheetName]);
        if(roa.length > 0){
            result[sheetName] = roa;
        }
    });
    return result;
}
 
function to_csv(workbook) {
    var result = [];
    workbook.SheetNames.forEach(function(sheetName) {
        var csv = XLSX.utils.sheet_to_csv(workbook.Sheets[sheetName]);
        if(csv.length > 0){
            result.push("SHEET: " + sheetName);
            result.push("");
            result.push(csv);
        }
    });
    return result.join("\n");
}
 
function to_formulae(workbook) {
    var result = [];
    workbook.SheetNames.forEach(function(sheetName) {
        var formulae = XLSX.utils.get_formulae(workbook.Sheets[sheetName]);
        if(formulae.length > 0){
            result.push("SHEET: " + sheetName);
            result.push("");
            result.push(formulae.join("\n"));
        }
    });
    return result.join("\n");
}
 
var tarea = document.getElementById(‘b64data‘);
function b64it() {
    var wb = XLSX.read(tarea.value, {type: ‘base64‘});
    process_wb(wb);
}
 
function process_wb(wb) {
    var output = "";
    switch(get_radio_value("format")) {
        case "json":
        output = JSON.stringify(to_json(wb), 2, 2);
            break;
        case "form":
            output = to_formulae(wb);
            break; 
        default:
        output = to_csv(wb);
    }
    if(out.innerText === undefined) out.textContent = output;
    else out.innerText = output;
}
 
var drop = document.getElementById(‘drop‘);
function handleDrop(e) {
    e.stopPropagation();
    e.preventDefault();
    var files = e.dataTransfer.files;
    var i,f;
    for (i = 0, f = files[i]; i != files.length; ++i) {
        var reader = new FileReader();
        var name = f.name;
        reader.onload = function(e) {
            var data = e.target.result;
            //var wb = XLSX.read(data, {type: ‘binary‘});
            var arr = String.fromCharCode.apply(null, new Uint8Array(data));
            var wb = XLSX.read(btoa(arr), {type: ‘base64‘});
            process_wb(wb);
        };
        //reader.readAsBinaryString(f);
        reader.readAsArrayBuffer(f);
    }
}
 
function handleDragover(e) {
    e.stopPropagation();
    e.preventDefault();
    e.dataTransfer.dropEffect = ‘copy‘;
}
 
if(drop.addEventListener) {
    drop.addEventListener(‘dragenter‘, handleDragover, false);
    drop.addEventListener(‘dragover‘, handleDragover, false);
    drop.addEventListener(‘drop‘, handleDrop, false);
}

JS-XLS/X读取和解析Excel表格文件(xls/xlsx)的JavaScript插件

标签:demo   object   对象   enter   work   agent   nload   转换   excel表格   

原文地址:http://www.cnblogs.com/qxm9423/p/6829156.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!