【问题标题】:EXTJs Export to excel in IE8EXTJs 导出到 IE8 中的 excel
【发布时间】:2011-07-25 08:09:55
【问题描述】:

extjs Gridpanel 导出到 excel 在 Firefox 和 Chrome 中都可以正常工作,但在 IE(甚至 IE8 也是)中无法正常工作

请提供建议

提前致谢

【问题讨论】:

  • 你用的是什么版本的extjs?你用什么插件导出?
  • 可能有助于添加代码的 sn-p。

标签: extjs


【解决方案1】:

我在 ExtJS 4 中编译了一种网格插件。它可以帮助您制作可打印版本和导出到 Excel。它可以准确地导出您所看到的内容,并且也可以与列渲染器一起使用。包含此脚本:

/**
 * Export grid data. Based on:
 * http://www.sencha.com/forum/showthread.php?125611-data-download-function-from-Grid-and-Chart
 * http://www123.ddo.jp/grid/array-grid.js
 * http://edspencer.net/2009/07/extuxprinter-printing-for-any-ext.html
 * @param {Object} opt (optional)
 *   format: 'html',
 *   headers: true,
 *   stylesheetPath: 'css/print.css'
*/
Ext.grid.GridPanel.prototype.exportData = function(opt){
    opt=opt||{};

    //Get the array of columns from a grid
    var me=this, columns=[], data=[];
    Ext.each(me.columns, function(col) {
        if (col.hidden != true && col.dataIndex) columns.push(col);
    });
    //Sometimes there's no colum header text (when using icons)
    Ext.each(columns, function(column) {
        if (!column.text || column.text == ' ') {
            column.text=column.dataIndex;
        }
    });

    //Build a useable array of store data for the XTemplate
    me.store.data.each(function(item) {
        var convertedData = {};

        //apply renderers from column model
        Ext.iterate(item.data, function(key, value) {
            Ext.each(columns, function(column) {
                if (column.dataIndex == key) {
                    if (column.renderer) {
                        if (column.xtype==='templatecolumn') {
                            convertedData[key] = column.renderer(value, {}, item);
                        } else {
                            convertedData[key] = column.renderer(value, undefined, undefined, undefined, columns.indexOf(column), undefined, me.view);
                        }
                    } else {
                        convertedData[key] =  value;
                    }
                    if (typeof convertedData[key]==='string') {
                        convertedData[key]=Ext.util.Format.htmlToText(convertedData[key]);
                    }
                    return false;
                }
            });
        });

        data.push(convertedData);
    });

    //generate finale template to be applied with the data
    var headings=[], body=[], str;
    if (opt.format==="html") {
        headings=opt.headers?new Ext.XTemplate(
            '<tr>',
              '<tpl for=".">',
                '<th>{text}</th>',
              '</tpl>',
            '</tr>'
        ).apply(columns):'';
        body=new Ext.XTemplate(
            '<tr>',
              '<tpl for=".">',
                '<td>\{{dataIndex}\}</td>',
              '</tpl>',
            '</tr>'
        ).apply(columns);

        var str=[
            '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">',
            '<html>',
              '<head>',
                '<meta content="text/html; charset=UTF-8" http-equiv="Content-Type" />',
                opt.stylesheetPath?'<link href="' + opt.stylesheetPath + '" rel="stylesheet" type="text/css" media="screen,print" />':'',
                me.title?'<title>' + me.title + '</title>':'',
              '</head>',
              '<body>',
                '<table>',
                Ext.String.format('{0}\n<tpl for=".">{1}\n</tpl>', headings, body),
                '</table>',
              '</body>',
            '</html>'
        ].join('\n');
    } else {
        Ext.each(columns, function(v) {
            headings.push(Ext.util.Format.htmlToText(v.text));
            body.push('{'+v.dataIndex+'}');
        });
        headings=opt.headers?headings.join('\t'):'';
        body    =body.join('\t');

        var str=Ext.String.format('{0}\n<tpl for=".">{1}\n</tpl>', headings, body);
    }

    //console.log('toText', columns, data, headings, body, str);
    return new Ext.XTemplate(str).apply(data);
};

现在,像这样打印一个网格:

var html=grid.exportData({
    format: 'html',
    headers: true,
    stylesheetPath: 'resources/css/print.css'
});

var name = grid.getXType ? Ext.String.format("print_{0}_{1}", grid.getXType(), grid.id) : "print";

name=name.replace(/\W*/g, ''); //IE disallows spaces and other special characters in window name (the second argument). You need to remove them before passing as argument.

var win = window.open(undefined, name);
win.document.write(html);
win.document.close();
win.print();

导出到 Excel 要求您将网格导出为制表符分隔的字符串。您发布到服务器的那个字符串 (download.php)

var html=grid.exportData({
    format: 'txt',
    headers: true,
    stylesheetPath: 'resources/css/print.css'
});

var form = Ext.DomHelper.append(document.body, {
    tag: 'form',
    style: 'display:none',
    action: 'download.asp',
    method: 'post',
    cn:[{
        tag:'textarea',
        name:'body',
        html:html
    },{
        tag:'input',
        name:'filename',
        value: grid.title||'download'
    },{
        tag:'input',
        name:'extension',
        value:'xls'
    }]
});
form.submit();
document.body.removeChild(form);

然后 download.php 需要回显发布的正文。使用:

Content-Disposition=attachment;filename=file.xls
Content-Type=application/vnd.ms-excel

现在,您的浏览器应该会显示要求您保存 xls 文件的提示。

【讨论】:

    【解决方案2】:

    我对库Ext.ux.Exporter中的代码做了一个小修改,改成这样:

    this.getEl().child('a', true).href = 'data:application/vnd.ms-excel;base64,' + Ext.ux.Exporter[config.exportFunction](this.component, null, config);
    

    通过这个:

    var domA = this.getEl().child('a', true),
                string64 = Ext.ux.Exporter[config.exportFunction](this.component, null, config);
    
            domA.href = '#';
            domA.rel = string64;
    
            this.getEl().child('a').addListener( {
                'click':{
                    fn: function(){
                        __exportExcel(this.getEl().child('a', true).rel);
                    },
                    scope: this
                }
            });
    

    然后使用“脏”函数__exportExcel

    __exportExcel = function(base64){
    
        Ext.DomHelper.useDom = true;
        var form = Ext.DomHelper.append('grid1', {
            tag:     'form',
            style: 'display:none',
            action: 'download.php',
            method: 'post',
            cn:[{
                tag:'textarea',
                name:'body',
                html: base64
            },{
                tag:'input',
                name:'filename',
                value: grid.title||'download'
            },{
                tag:'input',
                name:'extension',
                value:'xls'
            }]
        });
        form.submit();
        document.getElementById('grid1').removeChild(form);
        return false;
    }
    

    将base64字符串发送到php文件download.php

    <?php
    header('Content-type: application/ms-excel');
    header('Content-Disposition: attachment; filename=file.xls');
    
    echo base64_decode($_POST['body']);
    
    ?>
    

    这些更改在 IE8 和其他浏览器中都可以使用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-02
      • 2016-11-30
      • 2023-03-19
      • 1970-01-01
      • 2017-08-13
      • 2023-03-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多