Подтвердить что ты не робот

Экспортировать таблицу html в ppt на стороне клиента?

Я хочу знать, есть ли у нас jQuery или javascript-решение для преобразования html-таблицы в powerpoint. Единственное решение, которое я получил, - это экспорт таблицы html. Здесь у нас есть все опции экспорта, но я хочу решение только для powerpoint. Я могу использовать экспорт таблицы Html, но моя проблема в том, что для одного экспорта я должен использовать весь плагин. Есть ли пример кода только для ppt?

4b9b3361

Ответ 1

Если размер библиотеки вызывает у вас беспокойство, лучшим вариантом может быть изменение библиотеки js самостоятельно. Выделение фрагментов кода, которые не могут быть связаны с функциями точки питания. И затем тестирование, постепенно делая библиотеку все меньше и меньше. Кроме этого, я не нашел там, где очевидно, что уже доступно это решение.

Выполняя упражнение выше, я смог взять файл tableExport.js с 12 КБ до 5 КБ (не минимизированный), сохраняя при этом экспорт в функциональные возможности.

/*The MIT License (MIT)

Copyright (c) 2014 https://github.com/kayalshri/

Permission is hereby granted....
....
*/

(function($){
    $.fn.extend({
        tableExport: function(options) {
            var defaults = {
                    separator: ',',
                    ignoreColumn: [],
                    tableName:'yourTableName',
                    type:'powerpoint',
                    escape:'true',
                    htmlContent:'false',
                    consoleLog:'false'
            };

            var options = $.extend(defaults, options);
            var el = this;

            if(defaults.type == 'powerpoint'){
                //console.log($(this).html());
                var excel="<table>";
                // Header
                $(el).find('thead').find('tr').each(function() {
                    excel += "<tr>";
                    $(this).filter(':visible').find('th').each(function(index,data) {
                        if ($(this).css('display') != 'none'){                  
                            if(defaults.ignoreColumn.indexOf(index) == -1){
                                excel += "<td>" + parseString($(this))+ "</td>";
                            }
                        }
                    }); 
                    excel += '</tr>';                       

                });                 


                // Row Vs Column
                var rowCount=1;
                $(el).find('tbody').find('tr').each(function() {
                    excel += "<tr>";
                    var colCount=0;
                    $(this).filter(':visible').find('td').each(function(index,data) {
                        if ($(this).css('display') != 'none'){  
                            if(defaults.ignoreColumn.indexOf(index) == -1){
                                excel += "<td>"+parseString($(this))+"</td>";
                            }
                        }
                        colCount++;
                    });                                                         
                    rowCount++;
                    excel += '</tr>';
                });                 
                excel += '</table>'

                if(defaults.consoleLog == 'true'){
                    console.log(excel);
                }

                var excelFile = "<html xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:x='urn:schemas-microsoft-com:office:"+defaults.type+"' xmlns='http://www.w3.org/TR/REC-html40'>";
                excelFile += "<head>";
                excelFile += "<!--[if gte mso 9]>";
                excelFile += "<xml>";
                excelFile += "<x:ExcelWorkbook>";
                excelFile += "<x:ExcelWorksheets>";
                excelFile += "<x:ExcelWorksheet>";
                excelFile += "<x:Name>";
                excelFile += "{worksheet}";
                excelFile += "</x:Name>";
                excelFile += "<x:WorksheetOptions>";
                excelFile += "<x:DisplayGridlines/>";
                excelFile += "</x:WorksheetOptions>";
                excelFile += "</x:ExcelWorksheet>";
                excelFile += "</x:ExcelWorksheets>";
                excelFile += "</x:ExcelWorkbook>";
                excelFile += "</xml>";
                excelFile += "<![endif]-->";
                excelFile += "</head>";
                excelFile += "<body>";
                excelFile += excel;
                excelFile += "</body>";
                excelFile += "</html>";

                var base64data = "base64," + $.base64.encode(excelFile);
                window.open('data:application/vnd.ms-'+defaults.type+';filename=exportData.doc;' + base64data);

            }

            function parseString(data){

                if(defaults.htmlContent == 'true'){
                    content_data = data.html().trim();
                }else{
                    content_data = data.text().trim();
                }

                if(defaults.escape == 'true'){
                    content_data = escape(content_data);
                }

                return content_data;
            }

        }
    });
})(jQuery);

Вы можете заменить файл tableExport.js на этот код и называть его таким же образом, передав Powerpoint в качестве типа, или его можно опустить, и он все равно будет работать.

Ответ 2

Вы можете использовать одно и то же решение, изменив файлы JS, чтобы использовать только часть, связанную с MS-Office. Фактически, функция, которая преобразует таблицу Porwerpoint, такая же, как и для Excel и Word.

Для этого вам понадобится только файл jquery.base64.js и файл tableExport.js, но измените всю таблицуExport.js содержимое следующего:

/*The MIT License (MIT)
Copyright (c) 2014 https://github.com/kayalshri/
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.*/

(function($){
        $.fn.extend({
            tableExport: function(options) {
                var defaults = {
                        separator: ',',
                        ignoreColumn: [],
                        tableName:'yourTableName',
                        type:'excel',
                        escape:'true',
                        htmlContent:'false',
                        consoleLog:'false'
                };

                var options = $.extend(defaults, options);
                var el = this;

                if(defaults.type == 'excel' || defaults.type == 'doc'|| defaults.type == 'powerpoint'  ){
                    //console.log($(this).html());
                    var excel="<table>";
                    // Header
                    $(el).find('thead').find('tr').each(function() {
                        excel += "<tr>";
                        $(this).filter(':visible').find('th').each(function(index,data) {
                            if ($(this).css('display') != 'none'){                  
                                if(defaults.ignoreColumn.indexOf(index) == -1){
                                    excel += "<td>" + parseString($(this))+ "</td>";
                                }
                            }
                        }); 
                        excel += '</tr>';                       

                    });                 


                    // Row Vs Column
                    var rowCount=1;
                    $(el).find('tbody').find('tr').each(function() {
                        excel += "<tr>";
                        var colCount=0;
                        $(this).filter(':visible').find('td').each(function(index,data) {
                            if ($(this).css('display') != 'none'){  
                                if(defaults.ignoreColumn.indexOf(index) == -1){
                                    excel += "<td>"+parseString($(this))+"</td>";
                                }
                            }
                            colCount++;
                        });                                                         
                        rowCount++;
                        excel += '</tr>';
                    });                 
                    excel += '</table>'

                    if(defaults.consoleLog == 'true'){
                        console.log(excel);
                    }

                    var excelFile = "<html xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:x='urn:schemas-microsoft-com:office:"+defaults.type+"' xmlns='http://www.w3.org/TR/REC-html40'>";
                    excelFile += "<head>";
                    excelFile += "<!--[if gte mso 9]>";
                    excelFile += "<xml>";
                    excelFile += "<x:ExcelWorkbook>";
                    excelFile += "<x:ExcelWorksheets>";
                    excelFile += "<x:ExcelWorksheet>";
                    excelFile += "<x:Name>";
                    excelFile += "{worksheet}";
                    excelFile += "</x:Name>";
                    excelFile += "<x:WorksheetOptions>";
                    excelFile += "<x:DisplayGridlines/>";
                    excelFile += "</x:WorksheetOptions>";
                    excelFile += "</x:ExcelWorksheet>";
                    excelFile += "</x:ExcelWorksheets>";
                    excelFile += "</x:ExcelWorkbook>";
                    excelFile += "</xml>";
                    excelFile += "<![endif]-->";
                    excelFile += "</head>";
                    excelFile += "<body>";
                    excelFile += excel;
                    excelFile += "</body>";
                    excelFile += "</html>";

                    var base64data = "base64," + $.base64.encode(excelFile);
                    window.open('data:application/vnd.ms-'+defaults.type+';filename=exportData.doc;' + base64data);

                }


                function parseString(data){

                    if(defaults.htmlContent == 'true'){
                        content_data = data.html().trim();
                    }else{
                        content_data = data.text().trim();
                    }

                    if(defaults.escape == 'true'){
                        content_data = escape(content_data);
                    }



                    return content_data;
                }

            }
        });
    })(jQuery);

Все остальные файлы, включая папку jspdf, можно удалить.

Таким образом вы можете экспортировать таблицу в формат excel, doc и PowerPoint (фактически, при экспорте в doc и powerpoint, вы делаете встраивание электронной таблицы Excel в документы, поэтому плагин одинаковый для всех трех форматов )

Используйте плагин так же, как оригинальный плагин