JQuery 导入导出 Excel

正在做一个小项目, 从数据库中查询数据放在 HTML Table 中. 现在想要从这个 table 中导出数据来. 另外用户需要选择导出的列. 使用 jQuery 的导出插件可以完成这个需求.

jQuery Plugin to Export HTML Tables

例子:

导入插件:

[javascript] view plain copy

  1. <script src="jquery-tableexport/tableExport.js"></script>
  2. <script src="jquery-tableexport/jquery.base64.js"></script>

html:

<a href="#" onClick ="$(‘#table-name‘).tableExport({type:‘excel‘, separator:‘;‘, escape:‘false‘});" id="buttonExportData" class="ui-btn ui-btn-inline ui-mini ui-shadow ui-corner-all">Export XLS</a>

插件还有以下这些参数选项:

separator: ‘,‘
ignoreColumn: [2,3],
tableName:‘yourTableName‘
type:‘csv‘
pdfFontSize:14
pdfLeftMargin:20
escape:‘true‘
htmlContent:‘false‘
consoleLog:‘false‘

通过 ignoreColumn 可以指定哪几列不被导出.

JS-XLSX

导入 excel 2007 以上版本, 可以使用 JS-XLSX 插件. 首先导入 js 包:

[javascript] view plain copy

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

Node.js 安装:

$ npminstall xlsx

$ node

> require(‘xlsx‘).readFile(‘excel_file.xlsx‘);

然后可以使用这个插件把 XLSX 文件转为 JSON, CSV, Formula 输出.

[javascript] view plain copy

  1. function get_radio_value( radioName ) {
  2. var radios = document.getElementsByName( radioName );
  3. for( var i = 0; i < radios.length; i++ ) {
  4. if( radios[i].checked ) {
  5. return radios[i].value;
  6. }
  7. }
  8. }
  9. function to_json(workbook) {
  10. var result = {};
  11. workbook.SheetNames.forEach(function(sheetName) {
  12. var roa = XLSX.utils.sheet_to_row_object_array(workbook.Sheets[sheetName]);
  13. if(roa.length > 0){
  14. result[sheetName] = roa;
  15. }
  16. });
  17. return result;
  18. }
  19. function to_csv(workbook) {
  20. var result = [];
  21. workbook.SheetNames.forEach(function(sheetName) {
  22. var csv = XLSX.utils.sheet_to_csv(workbook.Sheets[sheetName]);
  23. if(csv.length > 0){
  24. result.push("SHEET: " + sheetName);
  25. result.push("");
  26. result.push(csv);
  27. }
  28. });
  29. return result.join("\n");
  30. }
  31. function to_formulae(workbook) {
  32. var result = [];
  33. workbook.SheetNames.forEach(function(sheetName) {
  34. var formulae = XLSX.utils.get_formulae(workbook.Sheets[sheetName]);
  35. if(formulae.length > 0){
  36. result.push("SHEET: " + sheetName);
  37. result.push("");
  38. result.push(formulae.join("\n"));
  39. }
  40. });
  41. return result.join("\n");
  42. }
  43. var tarea = document.getElementById(‘b64data‘);
  44. function b64it() {
  45. var wb = XLSX.read(tarea.value, {type: ‘base64‘});
  46. process_wb(wb);
  47. }
  48. function process_wb(wb) {
  49. var output = "";
  50. switch(get_radio_value("format")) {
  51. case "json":
  52. output = JSON.stringify(to_json(wb), 2, 2);
  53. break;
  54. case "form":
  55. output = to_formulae(wb);
  56. break;
  57. default:
  58. output = to_csv(wb);
  59. }
  60. if(out.innerText === undefined) out.textContent = output;
  61. else out.innerText = output;
  62. }
  63. var drop = document.getElementById(‘drop‘);
  64. function handleDrop(e) {
  65. e.stopPropagation();
  66. e.preventDefault();
  67. var files = e.dataTransfer.files;
  68. var i,f;
  69. for (i = 0, f = files[i]; i != files.length; ++i) {
  70. var reader = new FileReader();
  71. var name = f.name;
  72. reader.onload = function(e) {
  73. var data = e.target.result;
  74. //var wb = XLSX.read(data, {type: ‘binary‘});
  75. var arr = String.fromCharCode.apply(null, new Uint8Array(data));
  76. var wb = XLSX.read(btoa(arr), {type: ‘base64‘});
  77. process_wb(wb);
  78. };
  79. //reader.readAsBinaryString(f);
  80. reader.readAsArrayBuffer(f);
  81. }
  82. }
  83. function handleDragover(e) {
  84. e.stopPropagation();
  85. e.preventDefault();
  86. e.dataTransfer.dropEffect = ‘copy‘;
  87. }
  88. if(drop.addEventListener) {
  89. drop.addEventListener(‘dragenter‘, handleDragover, false);
  90. drop.addEventListener(‘dragover‘, handleDragover, false);
  91. drop.addEventListener(‘drop‘, handleDrop, false);
  92. }

插件作者地址: author

不使用 HTML5 的话, 就要上传文件到服务器端, 服务器再来解析处理文件.例子如下:

[html] view plain copy

  1. @using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
  2. {
  3. <input type="file" name="file" />
  4. <input type="submit" value="OK" />
  5. }
public class HomeController : Controller
{
    // This action renders the form
    public ActionResult Index()
    {
        return View();
    }

    // This action handles the form POST and the upload
    [HttpPost]
    public ActionResult Index(HttpPostedFileBase file)
    {
        // Verify that the user selected a file
        if (file != null && file.ContentLength > 0)
        {
            // extract only the fielname
            var fileName = Path.GetFileName(file.FileName);
            // store the file inside ~/App_Data/uploads folder
            var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
            file.SaveAs(path);
        }
        // redirect back to the index action to show the form once again
        return RedirectToAction("Index");
    }
}

深圳一朋友说使用jquery.base64.js时发现对于中文直接抛出异常,作者压根不处理汉字的情况,因此

对其进行修正,关键函数为:

jQuery.base64 = (function ($) {

var _PADCHAR = "=",
_ALPHA = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",
_VERSION = "1.1"; //Mr. Ruan fix to 1.1 to support asian char(utf8)

function _getbyte64(s, i) {
// This is oddly fast, except on Chrome/V8.
// Minimal or no improvement in performance by using a
// object with properties mapping chars to value (eg. ‘A‘: 0)

var idx = _ALPHA.indexOf(s.charAt(i));

if (idx === -1) {
throw "Cannot decode base64";
}

return idx;
}

function _decode_chars(y, x) {
while (y.length > 0) {
var ch = y[0];
if (ch < 0x80) {
y.shift();
x.push(String.fromCharCode(ch));
} else if ((ch & 0x80) == 0xc0) {
if (y.length < 2) break;
ch = y.shift();
var ch1 = y.shift();
x.push(String.fromCharCode(((ch & 0x1f) << 6) + (ch1 & 0x3f)));
} else {
if (y.length < 3) break;
ch = y.shift();
var ch1 = y.shift();
var ch2 = y.shift();
x.push(String.fromCharCode(((ch & 0x0f) << 12) + ((ch1 & 0x3f) << 6) + (ch2 & 0x3f)));
}
}
}

function _decode(s) {
var pads = 0,
i,
b10,
imax = s.length,
x = [],
y = [];

s = String(s);

if (imax === 0) {
return s;
}

if (imax % 4 !== 0) {
throw "Cannot decode base64";
}

if (s.charAt(imax - 1) === _PADCHAR) {
pads = 1;

if (s.charAt(imax - 2) === _PADCHAR) {
pads = 2;
}

// either way, we want to ignore this last block
imax -= 4;
}

for (i = 0; i < imax; i += 4) {
var ch1 = _getbyte64(s, i);
var ch2 = _getbyte64(s, i + 1);
var ch3 = _getbyte64(s, i + 2);
var ch4 = _getbyte64(s, i + 3);

b10 = (_getbyte64(s, i) << 18) | (_getbyte64(s, i + 1) << 12) | (_getbyte64(s, i + 2) << 6) | _getbyte64(s, i + 3);
y.push(b10 >> 16);
y.push((b10 >> 8) & 0xff);
y.push(b10 & 0xff);
_decode_chars(y, x);
}
switch (pads) {
case 1:
b10 = (_getbyte64(s, i) << 18) | (_getbyte64(s, i + 1) << 12) | (_getbyte64(s, i + 2) << 6);
y.push(b10 >> 16);
y.push((b10 >> 8) & 0xff);
break;

case 2:
b10 = (_getbyte64(s, i) << 18) | (_getbyte64(s, i + 1) << 12);
y.push(b10 >> 16);
break;
}
_decode_chars(y, x);
if (y.length > 0) throw "Cannot decode base64";
return x.join("");
}

function _get_chars(ch, y) {
if (ch < 0x80) y.push(ch);
else if (ch < 0x800) {
y.push(0xc0 + ((ch >> 6) & 0x1f));
y.push(0x80 + (ch & 0x3f));
} else {
y.push(0xe0 + ((ch >> 12) & 0xf));
y.push(0x80 + ((ch >> 6) & 0x3f));
y.push(0x80 + (ch & 0x3f));
}
}

function _encode(s) {
if (arguments.length !== 1) {
throw "SyntaxError: exactly one argument required";
}

s = String(s);
if (s.length === 0) {
return s;
}

//s = _encode_utf8(s);
var i,
b10,
y = [],
x = [],
len = s.length;
i = 0;
while (i < len) {
_get_chars(s.charCodeAt(i), y);
while (y.length >= 3) {
var ch1 = y.shift();
var ch2 = y.shift();
var ch3 = y.shift();
b10 = (ch1 << 16) | (ch2 << 8) | ch3;
x.push(_ALPHA.charAt(b10 >> 18));
x.push(_ALPHA.charAt((b10 >> 12) & 0x3F));
x.push(_ALPHA.charAt((b10 >> 6) & 0x3f));
x.push(_ALPHA.charAt(b10 & 0x3f));
}
i++;
}

switch (y.length) {
case 1:
var ch = y.shift();
b10 = ch << 16;
x.push(_ALPHA.charAt(b10 >> 18) + _ALPHA.charAt((b10 >> 12) & 0x3F) + _PADCHAR + _PADCHAR);
break;

case 2:
var ch1 = y.shift();
var ch2 = y.shift();
b10 = (ch1 << 16) | (ch2 << 8);
x.push(_ALPHA.charAt(b10 >> 18) + _ALPHA.charAt((b10 >> 12) & 0x3F) + _ALPHA.charAt((b10 >> 6) & 0x3f) + _PADCHAR);
break;
}

return x.join("");
}

return {
decode: _decode,
encode: _encode,
VERSION: _VERSION
};

} (jQuery));

时间: 2024-08-28 14:36:43

JQuery 导入导出 Excel的相关文章

Java利用POI导入导出Excel中的数据

     首先谈一下今天发生的一件开心的事,本着一颗android的心我被分配到了PB组,身在曹营心在汉啊!好吧,今天要记录和分享的是Java利用POI导入导出Excel中的数据.下面POI包的下载地址http://poi.apache.org/download.html,有兴趣的朋友也可以去看看其中的API.      下面分享一下在对POI进行基本操作时觉得需要注意的两点:       1.POI中针对xlsx/xls是需要create different Workbook instance

导入导出Excel的Java工具类ExcelUtil

在编写ExcelUtil之前,在网上查了一些资料.java中用来处理Excel的第三方开源项目主要就是POI和JXL.poi功能强大,但是比较耗资源,对于大数据量的导入导出性能不是太好:jxl功能简单,但是性能比较好. 由于本项目的导入导出更多关注性能问题,而且jxl提供的功能基本也都够用了,于是选择了jxl作为支持. 实战 导出就是将List转化为Excel(listToExcel) 导入就是将Excel转化为List(excelToList) 导入导出中会出现各种各样的问题,比如:数据源为空

C#用Infragistics 导入导出Excel(一)

最近项目中有数据的导入导出Excel的需求,这里做简单整理. 公司用的是Infragistics的产品,付费,不需要本地安装Office. 有需要的朋友可以下载 Infragistics.2013.2.2098,提取密码:5u17 本文完整代码下载 Demo.Excel.zip 当然,我知道还有其他开源的类库来操作Excel,希望有资源的博友可以一起共享一下. Infragistics安装使用 直接安装Infragistics_WinForms_20132.msi后再项目Reference中引用

jxl导入/导出excel

转自:http://www.cnblogs.com/linjiqin/p/3540266.html 1.jxl导入/导出excel案例,黏贴即可运行 package junit.test; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import jxl.Cell; import jxl.Sheet; import jxl.Workbook;

页面导入导出EXCEL

引用 using Microsoft.Office.Interop.Excel;using System.Reflection;//反射命名空间using System.IO; protected void Button1_Click(object sender, EventArgs e) { //项目引入Microsoft.office.Excel组件 //导出二大部分 //第一部分,生成EXCEL文件 //对象1 应用程序对象 Microsoft.Office.Interop.Excel.A

使用PHPExcel导入导出excel格式文件

使用PHPExcel导入导出excel格式文件 作者:zccst 由于导出使用较多,下面是导出实现过程. 第一步,将PHPExcel的源代码复制到项目的lib下 文件包括:PHPExcel.php 和 文件夹PHPExcel 源代码见附件 注1:源代码是zip格式,能在windows和linux通用. 注2:PHPExcel.zip是干净代码,可以直接引用.PHPExcel2.zip有svn记录,不适合直接引用. 第二步:在需要导出的handler页面中引用 1,在头部引入三个文件 Php代码 

(C#)利用Aspose.Cells组件导入导出excel文件

Aspose.Cells组件可以不依赖excel来导入导出excel文件: 导入: [csharp] view plain copy print? public static System.Data.DataTable ReadExcel(String strFileName) { Workbook book = new Workbook(); book.Open(strFileName); Worksheet sheet = book.Worksheets[0]; Cells cells = 

【转】 (C#)利用Aspose.Cells组件导入导出excel文件

Aspose.Cells组件可以不依赖excel来导入导出excel文件: 导入: public static System.Data.DataTable ReadExcel(String strFileName) { Workbook book = new Workbook(); book.Open(strFileName); Worksheet sheet = book.Worksheets[0]; Cells cells = sheet.Cells; return cells.Export

php导入导出excel实例

这里实现的PHP导入导出excel功能用到的是开源PHPExcel,执行下面的操作之前请先下载该类库文件,官方网站:http://www.codeplex.com/PHPExcel,官网案例代码很多,导出pdf什么的都有,这里主要介绍PHP导入导出excel的功能,导出excel文件是office2007格式,同时兼容2003. php导入excel导入的excel文件的数据格式,截图如下:下面是将该excel文件的数据导入到数据库的具体代码 <?php require_once 'Classe