在今天的项目中,我们需要实现一个导出功能,将jqgrid查询出的数据导出为Excel表格文件。在实现过程中,我们遇到了两个问题:1. 导出报错,提示INVALID_CHARACTER_ERR: DOM Exception 5,原因是插件不支持中文;2. 使用官方的导出代码时,生成的EXCEL文件没有表头,并且数据最上方多了一行空白行。下面我们来解决这两个问题。
首先,我们需要下载并引入这个插件。这个插件功能很强大,支持以下导出格式:JSON、XML、PNG、CSV、TXT、SQL、MS Word、MS Excel、MS Powerpoint和PDF。在这里,我们主要关注Excel的导出功能。
接下来,我们来解决第一个问题。打开jquery.base64.js文件,在`decode`方法上方添加两个方法:`_utf8encode`和`_utf8decode`。修改后的代码如下:
```javascript
function _utf8encode(string) {
var utftext = "";
for (var n = 0; n < string.length; n++) {
var c = string.charCodeAt(n);
if (c < 128) {
utftext += String.fromCharCode(c);
} else if (c > 127 && c < 2048) {
utftext += String.fromCharCode((c >> 6) | 192);
utftext += String.fromCharCode((c & 63) | 128);
} else {
utftext += String.fromCharCode((c >> 12) | 224);
utftext += String.fromCharCode(((c >> 6) & 63) | 128);
utftext += String.fromCharCode((c & 63) | 128);
}
}
return utftext;
}
function _utf8decode(utftext) {
var string = "";
for (var n = 0; n < utftext.length; n++) {
var c = utftext.charCodeAt(n);
if (c < 128) {
string += String.fromCharCode(c);
} else if (c > 191 && c < 224) {
string += String.fromCharCode((c >> 6) | 128);
string += String.fromCharCode(c & 63);
} else if (c > 223 && c < 240) {
string += String.fromCharCode((c >> 12) | 192);
string += String.fromCharCode(((c >> 6) & 63) | 128);
string += String.fromCharCode((c & 63) | 128);
} else if (c > 239 && c < 248) {
string += String.fromCharCode((c >> 6) | 224);
string += String.fromCharCode(((c >> 12) & 63) | 128);
string += String.fromCharCode(((c >> 6) & 63) | 128);
} else if (c > 247 && c < 592) {
string += String.fromCharCode((c >> 12) | 240);
string += String.fromCharCode(((c >> 6) & 63) | 128);
string += String.fromCharCode((c & 63) | 128);
} else if (c > 591 && c < 640) {
string += String.fromCharCode((c >> 18) | ((c >> 12) & ~31));
string += String.fromCharCode(((c >> 6) & ~15) | (c & ~63));
} else if (c > 639 && c < 648) {
string += String.fromCharCode((c >> 12) | ((c >> 6) & ~3)) | ((c & ~63) << fourBitMark[u]);
} else if (unicodeMarks[p]) string += markToUchar[unicodeMarks[p]];else string += String.fromCharCode(c);
++p;
++n; // 注意这里应该是 n++ 而不是++n,否则会造成死循环。感谢@xingyuqihuan指出这个问题。
}
return string;
}
```
修改完毕后,将原来的导出代码://$(''#jqgrid1').tableExport({ type: 'excel', filename: new Date().getTime(), escape: 'false' });替换为://$(''#jqgrid1'').tableExport({ type: 'excel', filename: new Date().getTime(), escape: 'false' });,即可解决问题。