精华内容
下载资源
问答
  • 在VUE中使用Export2Excel导出表格,导出多个sheet

    千次阅读 热门讨论 2020-04-22 15:28:32
    使用Export2Excel导出表格,导出多个sheet功能快捷键合理的创建标题,有助于目录的生成如何改变文本的样式插入链接与图片如何插入一段漂亮的代码片生成一个适合你的列表创建一个表格设定内容居中、居左、居右...

    使用Export2Excel导出表格,导出多个sheet


    最近做项目有个将table导出excel的功能,Export2Excel源码只能默认导出一个sheet,然后在网上搜了其他文章,发现导出的配置太繁琐了,我自己用不到那么多功能,所以自己优化了一下,精简了一下代码,就导出多个sheet的excel表格,excel的样式没有配置。
    1.安装依赖

    npm install -S file-saver
    npm install -S xlsx
    npm install -D script-loader
    

    2.在目录下创建excel文件夹,再建立Blob.js和Export2Excel.js
    在这里插入图片描述

    Blob.js代码如下

    /* eslint-disable */
    /* Blob.js
     * A Blob implementation.
     * 2014-05-27
     *
     * By Eli Grey, http://eligrey.com
     * By Devin Samarin, https://github.com/eboyjr
     * License: X11/MIT
     *   See LICENSE.md
     */
     
    /*global self, unescape */
    /*jslint bitwise: true, regexp: true, confusion: true, es5: true, vars: true, white: true,
     plusplus: true */
     
    /*! @source http://purl.eligrey.com/github/Blob.js/blob/master/Blob.js */
     
    (function (view) {
        "use strict";
     
        view.URL = view.URL || view.webkitURL;
     
        if (view.Blob && view.URL) {
            try {
                new Blob;
                return;
            } catch (e) {}
        }
     
        // Internally we use a BlobBuilder implementation to base Blob off of
        // in order to support older browsers that only have BlobBuilder
        var BlobBuilder = view.BlobBuilder || view.WebKitBlobBuilder || view.MozBlobBuilder || (function(view) {
                var
                    get_class = function(object) {
                        return Object.prototype.toString.call(object).match(/^\[object\s(.*)\]$/)[1];
                    }
                    , FakeBlobBuilder = function BlobBuilder() {
                        this.data = [];
                    }
                    , FakeBlob = function Blob(data, type, encoding) {
                        this.data = data;
                        this.size = data.length;
                        this.type = type;
                        this.encoding = encoding;
                    }
                    , FBB_proto = FakeBlobBuilder.prototype
                    , FB_proto = FakeBlob.prototype
                    , FileReaderSync = view.FileReaderSync
                    , FileException = function(type) {
                        this.code = this[this.name = type];
                    }
                    , file_ex_codes = (
                        "NOT_FOUND_ERR SECURITY_ERR ABORT_ERR NOT_READABLE_ERR ENCODING_ERR "
                        + "NO_MODIFICATION_ALLOWED_ERR INVALID_STATE_ERR SYNTAX_ERR"
                    ).split(" ")
                    , file_ex_code = file_ex_codes.length
                    , real_URL = view.URL || view.webkitURL || view
                    , real_create_object_URL = real_URL.createObjectURL
                    , real_revoke_object_URL = real_URL.revokeObjectURL
                    , URL = real_URL
                    , btoa = view.btoa
                    , atob = view.atob
     
                    , ArrayBuffer = view.ArrayBuffer
                    , Uint8Array = view.Uint8Array
                    ;
                FakeBlob.fake = FB_proto.fake = true;
                while (file_ex_code--) {
                    FileException.prototype[file_ex_codes[file_ex_code]] = file_ex_code + 1;
                }
                if (!real_URL.createObjectURL) {
                    URL = view.URL = {};
                }
                URL.createObjectURL = function(blob) {
                    var
                        type = blob.type
                        , data_URI_header
                        ;
                    if (type === null) {
                        type = "application/octet-stream";
                    }
                    if (blob instanceof FakeBlob) {
                        data_URI_header = "data:" + type;
                        if (blob.encoding === "base64") {
                            return data_URI_header + ";base64," + blob.data;
                        } else if (blob.encoding === "URI") {
                            return data_URI_header + "," + decodeURIComponent(blob.data);
                        } if (btoa) {
                            return data_URI_header + ";base64," + btoa(blob.data);
                        } else {
                            return data_URI_header + "," + encodeURIComponent(blob.data);
                        }
                    } else if (real_create_object_URL) {
                        return real_create_object_URL.call(real_URL, blob);
                    }
                };
                URL.revokeObjectURL = function(object_URL) {
                    if (object_URL.substring(0, 5) !== "data:" && real_revoke_object_URL) {
                        real_revoke_object_URL.call(real_URL, object_URL);
                    }
                };
                FBB_proto.append = function(data/*, endings*/) {
                    var bb = this.data;
                    // decode data to a binary string
                    if (Uint8Array && (data instanceof ArrayBuffer || data instanceof Uint8Array)) {
                        var
                            str = ""
                            , buf = new Uint8Array(data)
                            , i = 0
                            , buf_len = buf.length
                            ;
                        for (; i < buf_len; i++) {
                            str += String.fromCharCode(buf[i]);
                        }
                        bb.push(str);
                    } else if (get_class(data) === "Blob" || get_class(data) === "File") {
                        if (FileReaderSync) {
                            var fr = new FileReaderSync;
                            bb.push(fr.readAsBinaryString(data));
                        } else {
                            // async FileReader won't work as BlobBuilder is sync
                            throw new FileException("NOT_READABLE_ERR");
                        }
                    } else if (data instanceof FakeBlob) {
                        if (data.encoding === "base64" && atob) {
                            bb.push(atob(data.data));
                        } else if (data.encoding === "URI") {
                            bb.push(decodeURIComponent(data.data));
                        } else if (data.encoding === "raw") {
                            bb.push(data.data);
                        }
                    } else {
                        if (typeof data !== "string") {
                            data += ""; // convert unsupported types to strings
                        }
                        // decode UTF-16 to binary string
                        bb.push(unescape(encodeURIComponent(data)));
                    }
                };
                FBB_proto.getBlob = function(type) {
                    if (!arguments.length) {
                        type = null;
                    }
                    return new FakeBlob(this.data.join(""), type, "raw");
                };
                FBB_proto.toString = function() {
                    return "[object BlobBuilder]";
                };
                FB_proto.slice = function(start, end, type) {
                    var args = arguments.length;
                    if (args < 3) {
                        type = null;
                    }
                    return new FakeBlob(
                        this.data.slice(start, args > 1 ? end : this.data.length)
                        , type
                        , this.encoding
                    );
                };
                FB_proto.toString = function() {
                    return "[object Blob]";
                };
                FB_proto.close = function() {
                    this.size = this.data.length = 0;
                };
                return FakeBlobBuilder;
            }(view));
     
        view.Blob = function Blob(blobParts, options) {
            var type = options ? (options.type || "") : "";
            var builder = new BlobBuilder();
            if (blobParts) {
                for (var i = 0, len = blobParts.length; i < len; i++) {
                    builder.append(blobParts[i]);
                }
            }
            return builder.getBlob(type);
        };
    }(typeof self !== "undefined" && self || typeof window !== "undefined" && window || this.content || this));
    

    Export2Excel.js源码如下

    /* eslint-disable */
    require('script-loader!file-saver');
    require('./Blob');
    require('script-loader!xlsx/dist/xlsx.core.min');
    function generateArray(table) {
        var out = [];
        var rows = table.querySelectorAll('tr');
        var ranges = [];
        for (var R = 0; R < rows.length; ++R) {
            var outRow = [];
            var row = rows[R];
            var columns = row.querySelectorAll('td');
            for (var C = 0; C < columns.length; ++C) {
                var cell = columns[C];
                var colspan = cell.getAttribute('colspan');
                var rowspan = cell.getAttribute('rowspan');
                var cellValue = cell.innerText;
                if (cellValue !== "" && cellValue == +cellValue) cellValue = +cellValue;
     
                //Skip ranges
                ranges.forEach(function (range) {
                    if (R >= range.s.r && R <= range.e.r && outRow.length >= range.s.c && outRow.length <= range.e.c) {
                        for (var i = 0; i <= range.e.c - range.s.c; ++i) outRow.push(null);
                    }
                });
     
                //Handle Row Span
                if (rowspan || colspan) {
                    rowspan = rowspan || 1;
                    colspan = colspan || 1;
                    ranges.push({s: {r: R, c: outRow.length}, e: {r: R + rowspan - 1, c: outRow.length + colspan - 1}});
                }
                ;
     
                //Handle Value
                outRow.push(cellValue !== "" ? cellValue : null);
     
                //Handle Colspan
                if (colspan) for (var k = 0; k < colspan - 1; ++k) outRow.push(null);
            }
            out.push(outRow);
        }
        return [out, ranges];
    };
     
    function datenum(v, date1904) {
        if (date1904) v += 1462;
        var epoch = Date.parse(v);
        return (epoch - new Date(Date.UTC(1899, 11, 30))) / (24 * 60 * 60 * 1000);
    }
     
    function sheet_from_array_of_arrays(data, opts) {
        var ws = {};
        var range = {s: {c: 10000000, r: 10000000}, e: {c: 0, r: 0}};
        for (var R = 0; R != data.length; ++R) {
            for (var C = 0; C != data[R].length; ++C) {
                if (range.s.r > R) range.s.r = R;
                if (range.s.c > C) range.s.c = C;
                if (range.e.r < R) range.e.r = R;
                if (range.e.c < C) range.e.c = C;
                var cell = {v: data[R][C]};
                if (cell.v == null) continue;
                var cell_ref = XLSX.utils.encode_cell({c: C, r: R});
     
                if (typeof cell.v === 'number') cell.t = 'n';
                else if (typeof cell.v === 'boolean') cell.t = 'b';
                else if (cell.v instanceof Date) {
                    cell.t = 'n';
                    cell.z = XLSX.SSF._table[14];
                    cell.v = datenum(cell.v);
                }
                else cell.t = 's';
     
                ws[cell_ref] = cell;
            }
        }
        if (range.s.c < 10000000) ws['!ref'] = XLSX.utils.encode_range(range);
        return ws;
    }
     
    function Workbook() {
        if (!(this instanceof Workbook)) return new Workbook();
        this.SheetNames = [];
        this.Sheets = {};
    }
     
    function s2ab(s) {
        var buf = new ArrayBuffer(s.length);
        var view = new Uint8Array(buf);
        for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
        return buf;
    }
     
    export function export_table_to_excel(id) {
        var theTable = document.getElementById(id);
        console.log('a')
        var oo = generateArray(theTable);
        var ranges = oo[1];
     
        /* original data */
        var data = oo[0];
        var ws_name = "SheetJS";
        console.log(data);
     
        var wb = new Workbook(), ws = sheet_from_array_of_arrays(data);
     
        /* add ranges to worksheet */
        // ws['!cols'] = ['apple', 'banan'];
        ws['!merges'] = ranges;
     
        /* add worksheet to workbook */
        wb.SheetNames.push(ws_name);
        wb.Sheets[ws_name] = ws;
     
        var wbout = XLSX.write(wb, {bookType: 'xlsx', bookSST: false, type: 'binary'});
     
        saveAs(new Blob([s2ab(wbout)], {type: "application/octet-stream"}), "test.xlsx")
    }
     
    function formatJson(jsonData) {
        console.log(jsonData)
    }
    export function export_json_to_excel(th, jsonData, defaultTitle) {
     
        /* original data */
     
        var data = jsonData;
        data.unshift(th);
        var ws_name = "SheetJS";
     
        var wb = new Workbook(), ws = sheet_from_array_of_arrays(data);
     
     
        /* add worksheet to workbook */
        wb.SheetNames.push(ws_name);
        wb.Sheets[ws_name] = ws;
     
        var wbout = XLSX.write(wb, {bookType: 'xlsx', bookSST: false, type: 'binary'});
        var title = defaultTitle || '列表'
        saveAs(new Blob([s2ab(wbout)], {type: "application/octet-stream"}), title + ".xlsx")
    }
    

    再在asstes/js目录下创建excelexport.js文件暴露出方法

    export function export2Excel(columns,list,title){
        require.ensure([], () => {
            const { export_json_to_excel } = require('../../excel/Export2Excel');
            export_json_to_excel(columns, list, title);
        })
    }
    

    这里我传入的colums,list已经是数组了,所以这里不做处理

    找到Export2Excel.js文件
    找到export_json_to_excel这个方法,如下图所示,图1为源码

    export function export_json_to_excel(th, jsonData, defaultTitle) {
    
        /* original data */
    
        var data = jsonData;
        data.unshift(th);    
        
        var ws_name = "SheetJS";
    
        var wb = new Workbook(),ws = sheet_from_array_of_arrays(data);
    
        /* add worksheet to workbook */
        wb.SheetNames.push(ws_name);
        wb.Sheets[ws_name] = ws; 
        
        var wbout = XLSX.write(wb, {bookType: 'xlsx', bookSST: false, type: 'binary'});
        var title = defaultTitle || '列表'
        saveAs(new Blob([s2ab(wbout)], {type: "application/octet-stream"}), title + ".xlsx")
    }
    

    改成下方的代码

    export function export_json_to_excel(th, jsonData, defaultTitle) {
    
        var data = jsonData;
        //添加标题
        for (var i = 0; i < th.length; i++) {
          data[i].unshift([th[i]])
        }
        //这里是定义sheet的名称 有几个sheet就加几个
        var ws_name = ["Sheet1","Sheet2"];
    
        var wb = new Workbook(),ws=[];
        //数据转换
        for (var j = 0; j < th.length; j++) {
          ws.push(sheet_from_array_of_arrays(data[j]))
        }
    
        /* add worksheet to workbook */
        //生成多个sheet
        for (var k = 0; k < th.length; k++) {
          wb.SheetNames.push(ws_name[k])
          wb.Sheets[ws_name[k]] = ws[k]
        }
    
        var wbout = XLSX.write(wb, {bookType: 'xlsx', bookSST: false, type: 'binary'});
        var title = defaultTitle || '列表'
        saveAs(new Blob([s2ab(wbout)], {type: "application/octet-stream"}), title + ".xlsx")
    } 
    

    使用方法:
    1.在需要导出excel文件的vue页面 script标签里面引入

    /*
    titleNameArr excel表头名 thead type:arr 有几个标题就有几个sheet
    list excel表身 type:arr (多维数组) 格式如我下面写的
    excelTitleName 导出的文件名 type:string
     */
     
    <script type="text/javascript">
    	import { export2Excel } from '@/assets/js/excelexport';
    	export default{
    		data(){
    			return{
    				titleNameArr:['第一季度持仓','第二季度持仓'],
    				list:[[['代码','持仓','收益率','收益'],[1,2,3,4],[1,2,3,4]],[['代码','持仓','收益率','收益'],[5,6,5,6],[5,6,5,6]]],
    				excelTitleName:'养鸡报告'
    			}
    		},
    		methods{
    			goExport(){
    				export2Excel(this.titleNameArr,this.list,this.excelTitleName)
    			}
    		}
    	}
    </script>
    

    2.全局使用,main.js里面引入

    import { export2Excel } from '@/assets/js/excelexport';
    Vue.prototype.$export2Excel= export2Excel ;
    

    vue文件里面

    <script type="text/javascript">
    	export default{
    		data(){
    			return{}
    		},
    		methods{
    			goExport(){
    				this.$export2Excel(titleNameArr,list,excelTitleName);
    			}
    		}
    	}
    </script>
    
    展开全文
  • 1、进入PHP Excel官网后,找到右边的download按钮,下载,下载完成的是一个压缩文件,解压放到你的项目目录里。 2、查看解压文件是否有PHPExcel_Worksheet_Drawing图片文件类。... * PHP Excel表格导出图片方法 ...

    1、进入PHP Excel官网后,找到右边的download按钮,下载,下载完成的是一个压缩文件,解压放到你的项目目录里。

    2、查看解压文件是否有PHPExcel_Worksheet_Drawing图片文件类。

    3、创建一个excel.php文件,开始编写PHP Excel到出。

    实例代码:

    <?php
        /**
         * PHP Excel表格导出图片方法
         * 2015-07-30 
         */
        
         function ExcelCustomers(){
             
            /*引入phpexcel核心类文件*/
            
            include ROOT_PATH.'/system/libraries/phpExcel/PHPExcel.php';
            
            /*实例化excel类*/
            
            $excel = new PHPExcel();
            
            
            /*实例化excel图片处理类*/
            
            $objDrawing = new PHPExcel_Worksheet_Drawing();
            
            
            
            /*设置文本对齐方式*/
        
            $excel->getDefaultStyle()->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
            
            $excel->getDefaultStyle()->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
            
            $objActSheet = $excel->getActiveSheet();
    
            $letter = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N');
        
            /*设置表头数据*/
            $tableheader = array('导出日期','姓名', '身份证号', '民族','性别' ,'地址','房号','入住次数','身份头像');
            
            
        /*    填充表格表头*/
            
            for($i = 0;$i < count($tableheader);$i++) {
            
                $excel->getActiveSheet()->setCellValue("$letter[$i]1","$tableheader[$i]");
                /*设置font*/
                $excel->getActiveSheet()->getStyle("$letter[$i]1")->getFont()->setName(iconv('gbk', 'utf-8', '宋体'));
                $excel->getActiveSheet()->getStyle("$letter[$i]1")->getFont()->setSize(16);
                $excel->getActiveSheet()->getStyle("$letter[$i]1")->getFont()->setBold(true);
                /*设置下划线*/
                //$excel->getActiveSheet()->getStyle("$letter[$i]1")->getFont()->setUnderline(PHPExcel_Style_Font::UNDERLINE_SINGLE);
                /*设置字体颜色*/
                //$excel->getActiveSheet()->getStyle("$letter[$i]1")->getFont()->getColor()->setARGB(PHPExcel_Style_Color::COLOR_WHITE);
                //$excel->getActiveSheet()->getStyle("$letter[$i]1")->getFont()->getColor()->setARGB(PHPExcel_Style_Color::COLOR_WHITE);
                /*设置表格宽度*/
                $objActSheet->getColumnDimension("$letter[$i]")->setWidth(20);
                $objActSheet->getColumnDimension("$letter[2]")->setWidth(30);
                $objActSheet->getColumnDimension("$letter[5]")->setWidth(60);
            
    
    
            }
            
            $startdate = !empty($_POST['startdate']) ? $_POST['startdate'] : date('Y-m-d',time());
                        
            /* 设置表格数据*/
            $hotel_customer = M('hotel_customer');
            $sql = "SELECT addtime,username,idcard,gender,national,address,photo,photo_s,number,check_num FROM tc_hotel_customer WHERE last_checkin = '".$startdate."'";
            $Obj = $hotel_customer ->query($sql);
            if(!empty($Obj)){
                foreach ($Obj as $k=>$v){
                    $Obj[$k]['addtime'] = date('Y-m-d',time());
                    list($Oldrwidth, $Oldheight) = getimagesize($v['photo']);
                    if($Oldrwidth > 126 && $Oldheight > 102){
                        $Obj[$k]['photos'] = $v['photo_s'];
                    }else{
                        $Obj[$k]['photos'] = $v['photo'];
                    }
                    if($v['gender'] == 1){
                        $Obj[$k]['gender'] = '男';
                    }else{
                        $Obj[$k]['gender'] = '女';
                    }
                     unset($Obj[$k]['photo']);
                     unset($Obj[$k]['photo_s']);
                }
            }else{
            
                echo "<script>alert('亲,今天没人入住哟!');location.href='index.php?ac=hotel_customers';</script>";
                exit;
            }
                
            /*向每行单元格插入数据*/
            
            for ($i = 0;$i < count($Obj);$i++) {
                
                
                
                $j = $i + 2;
    
                /*设置表格高度*/
                
                $excel->getActiveSheet()->getRowDimension($j)->setRowHeight(50);
                $excel->getActiveSheet()->getStyle($j)->getFont()->setSize(12);
                /*设置表格格式*/
                $excel->getActiveSheet()->getStyle("$letter[2]$j")->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_NUMBER);
             for ($row = 0;$row < count($Obj[$i]);$row++) {
                    $photos = '';
                    if ($row == (count($Obj[$i]) - 1 )) {
                    
                    /*实例化excel图片处理类*/
            
                    $objDrawing = new PHPExcel_Worksheet_Drawing();
                    if(!empty($Obj[$i]['photos'])){
                            $photo = substr($Obj[$i]['photos'],7);
                            $photoAry = explode('/',$photo);
                        
                            if(in_array('uploadfiles',$photoAry)){
                                unset($photoAry[0]);
                                $photos = implode('/',$photoAry);
                                //var_dump($photos);exit;
                                /*设置图片路径 切记:只能是本地图片*/
                                $objDrawing->setPath($photos);
                            
                            }
                    
                    }else{
                    
                        $objDrawing->setPath($photos,false);
                    }
                    
                        
                        /*设置图片高度*/
                        $objDrawing->setWidth(20);
                        $objDrawing->setHeight(60);
                        
                        /*设置图片要插入的单元格*/
                        
                        $objDrawing->setCoordinates("$letter[$row]$j");
                        
                        /*设置图片所在单元格的格式*/
                        
                        $objDrawing->setOffsetX(50);
                        $objDrawing->setRotation(20);
                        
                        $objDrawing->getShadow()->setVisible(true);
                        
                        $objDrawing->getShadow()->setDirection(50);
                        
                        $objDrawing->setWorksheet($excel->getActiveSheet());
                        
                        continue;
                    
                    }
                    
                        $excel->getActiveSheet()->setCellValue("$letter[0]$j",$Obj[$i]['addtime']);
                        $excel->getActiveSheet()->setCellValue("$letter[1]$j",$Obj[$i]['username']);
                        $excel->getActiveSheet()->setCellValue("$letter[2]$j",$Obj[$i]['idcard']);
                        $excel->getActiveSheet()->setCellValue("$letter[3]$j",$Obj[$i]['national']);
                        $excel->getActiveSheet()->setCellValue("$letter[4]$j",$Obj[$i]['gender']);
                        $excel->getActiveSheet()->setCellValue("$letter[5]$j",$Obj[$i]['address']);
                        $excel->getActiveSheet()->setCellValue("$letter[6]$j",$Obj[$i]['number']);
                        $excel->getActiveSheet()->setCellValue("$letter[7]$j",$Obj[$i]['check_num']);
                    
                    
                    
                }
            
            }
            $date = $startdate."的住客资料";
      
            /*实例化excel输入类并完成输出excel文件*/
        
            $write = new PHPExcel_Writer_Excel5($excel);
            //var_dump($write);exit;
            
            header("Pragma: public");
            
            header("Expires: 0");
            
            header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
            
            header("Content-Type:application/force-download");
            
            header("Content-Type:application/vnd.ms-execl");
            
            header("Content-Type:application/octet-stream");
            
            header("Content-Type:application/download");;
            
            header("Content-Disposition:attachment;filename=$date.xls");
            
            header("Content-Transfer-Encoding:binary");
            
            $write->save('php://output');
                
                
            
    
    
            //var_dump($row);exit;
            
            
        }
        ?>

     

    转载于:https://www.cnblogs.com/520fyl/p/5420690.html

    展开全文
  • excel导出图片

    2017-02-10 17:07:10
    excel导出工作表为图片,用于快速把工作表表格导出为图片后,可以处理为海报,展板等,可以把普通表格用于平面设计中。
  • 如何将下图的表格图片导出excel? 前提是excel已激活,否则程序会异常结束或报错:QAxBase: Error calling IDispatch member Sheets: Unknown error。 本人没有发现将图片直接导出excel的方法,所以...

    如何将下图的表格和图片导出到excel?

    前提是excel已激活,否则程序会异常结束或报错:QAxBase: Error calling IDispatch member Sheets: Unknown error。

                                                                                                  

     

    本人没有找到可以将图片直接导出到excel的方法,所以想了一个比较笨的方法:先将图片保存在当前路径下,再将当前路径下图片插入excel,最后删除路径下的图片。不知道有没有大佬知道更好的方法,可以给小弟传授一下。

    void mainwindow::dataExport()
    {
    
        chartPic->grab(QRect(10, 10, 1330, 330)).save("image.png");
        QString filePath = QFileDialog::getSaveFileName(this, "数据导出", "untitle",
                                                        "Microsoft Excel 2013(*.xlsx)");
    
        if(!filePath.isEmpty()){
            QAxObject *excel = new QAxObject(this);
            excel->setControl("Excel.Application");
            excel->dynamicCall("SetVisible(bool Visible)", false);
            excel->setProperty("DisplayAlerts", false);
            QAxObject *workbooks = excel->querySubObject("WorkBooks");
            workbooks->dynamicCall("Add");
            QAxObject *workbook = excel->querySubObject("ActiveWorkBook");
            //获取工作表集合
            QAxObject *worksheets = workbook->querySubObject("Sheets");
            //获取工作表集合的工作表1,即sheet1
            QAxObject *worksheet = worksheets->querySubObject("Item(int)",1);
    
            //导出列表头
            for(int i = 2; i <= DataTable->columnCount()+1; i++)
            {
                QAxObject *cell=worksheet->querySubObject("Cells(int,int)", 1, i);
                cell->setProperty("ColumnWidth", 12);
                cell->setProperty("RowHeight", 40);
                cell->dynamicCall("SetValue(const QString&)", DataTable->horizontalHeaderItem(i-2)->data(0).toString());
            }
    
            //导出行表头
            for(int j = 2; j <= DataTable->rowCount()+1; j++)
            {
                QAxObject *cell=worksheet->querySubObject("Cells(int,int)", j, 1);
                cell->setProperty("ColumnWidth", 12);
                cell->setProperty("RowHeight", 40);
                cell->dynamicCall("SetValue(const QString&)", DataTable->verticalHeaderItem(j-2)->data(0).toString());
            }
            //导出表格内容
            for(int i = 2; i <= DataTable->rowCount()+1; i++){
                for(int j = 2; j <= DataTable->columnCount()+1; j++){
                    QAxObject *Range = worksheet->querySubObject("Cells(int,int)", i, j);
                    Range->dynamicCall("SetValue(const QString &)", DataTable->item(i - 2, j - 2)->text());
                }
            }
            QString picDir=QString("%1/image.png").arg(QDir::currentPath());
            QAxObject * shapes = worksheet->querySubObject("Shapes");
            shapes->dynamicCall("AddPicture( QString&, bool, bool, double, double, double, double)",QDir::toNativeSeparators(picDir),true,true,0,120,980,280);
            workbook->dynamicCall("SaveAs(const QString&)",QDir::toNativeSeparators(filePath));
            workbook->dynamicCall("Close()");                                                   
            //关闭工作簿
            excel->dynamicCall("Quit()");                                                       
            //关闭excel
            delete excel;
            excel=NULL;
            //保存图片
            QFile file(picDir);
            //删除保存在当前目录的图片
            file.remove();
    
            QMessageBox::information(this,QString("提示"), QString("导出成功,导出路径为:%1").arg(filePath));
        }
    }

    导出效果:

                                                                                               

     

    展开全文
  • zencart订单导出工具--导出图片excel表格
  • 导出excel表格图片

    2013-01-07 19:07:07
    当需要把当前图表导出excel或者图片时,首先在图表下面添加两个按钮:   &lt;div align="center"&gt; &lt;button id="report_export0"&gt;导出Excel&lt;/button&...

        当需要把当前图表导出成excel或者图片时,首先在图表下面添加两个按钮:

     

    	<div align="center">
    	    <button id="report_export0">导出Excel</button>
    	    <button id="report_image0">导出图片</button>
    	</div>

     

         然后在js文件中,添加这两个按钮的响应事件。

        $("#report_export" + i).unbind("click");

    $("#report_export" + i).bind("click",
    {
    	arg1: provinceID,
    	arg2: fromDate,
    	arg3: toDate,
    	arg4: type,
    	arg5: year,
    	arg6: month
    						},function(event){
    	var data = event.data;
    	exportReport(
    									data.arg1,data.arg2,data.arg3,
    									data.arg4,data.arg5,data.arg6);
    					});
     

     

          然后导出excel的任务应该是在exportReport里完成的

     

    function exportReport(provinceID, fromDate, toDate, type, year, month)
    {
    	var data = "provinceID=" + provinceID;
    	data += "&from=" + fromDate;
    	data += "&till=" + toDate;
    	data += "&type=" + type;
    	data += "&year=" + year;
    	data += "&month=" + month;
    	
    	var option = {
    			url: "ExportReport.action", 
    			data:data,
    			success: function(res, textStatus){
    				if (res.match("^http"))
    					window.location.href = res;
    				else
    					alert(res);
    			},
    			error:function(res,textStatus){
    				alert(textStatus);
    			}
    	};
    	$.ajax(option);
    }
     

     

     

          绑定导出图片的方法如下:

    $("#report_image" + i).unbind("click");
    $("#report_image" + i).bind("click",
    {
    	chart: chart,
    	title: title
    },function(event){
    	var data = event.data;
    	data.chart.exportChart({filename: data.title});
    });
     

     

     

     

     

     

     

     

     

     

     

    展开全文
  • 本篇讲下如何使用纯python代码将excel 中的图表导出图片。这里需要使用的模块有win32com、pythoncom模块。网上经查询有人已经写好的模块pyxlchart,具体代码如下:from win32...
  • 适用于图纸插表的制作。按给定列(该列应该但不限于页码),导出包含表头的png图片。源码。原创。
  • 摘自实际项目中关于带有图片excel表格的导入、导出功能。官方不要再提高下载积分了,不要再提高了!
  • 首先使用composerrequirephpoffice/phpexcel下载安装phpexcel包。... /** * 导出excel(不带图片) * @param string $fileName [description] * @param [type] $headArr [description] * @param [ty...
  • 这几天一直没写博文,但是为了让大山的孩子,能够像京城的富二代一样,可以开开心心公公平平地享受学习excel的权利,因此决定今天继续写,今天主要来谈谈excel图片批量导出,关于excel表格怎么批量导出图片的知识,...
  • thinkphp5.0导出图片excel表格不知道这个功能难不难,反正弄出来了,有点骄傲上代码 不知道这个功能难不难,反正弄出来了,有点骄傲 一天需要做这样一个功能,导出后台的信息,要求必须要导出图片,从网上查了很...
  • js-table2excel 导出图片excel

    千次阅读 2020-06-10 17:19:43
    第二步引入:在需要导出表格的页面引入 import table2excel from 'js-table2excel' 第三步使用 : <template> <el-button type="primary" @click="exportExcel">导出EXCEL</el-button> </...
  • excel的时候,我用过pear的库,也用过pack压包的头,同样那些利用smarty等作的简单替换xml的也用过,csv的就更不用...基本上导出的文件分为两种:1:类Excel格式,这个其实不是传统意义上的Excel文件,只是因为Exc...
  • ,可防止某一行数据无图片时出现表格图片混乱的情况;在设置图片宽高度位置加上$objDrawing[$i+4]->setResizeProportional(false);,可设置不按原图比例缩放;在113-125行添加用于纵向单元格合并的示例代码/* * ...
  • WPF 导出Excel 导出图片

    2013-08-30 15:46:00
    /// <summary> /// 导出Excel /// </summary> private void ExportExcel(DataTable ExcelDt) { //导出表格 HSSFWorkbook workBook ...
  • ElementUI 实现Excel表格导出(这里没有图片导出,需要图片导出请看上一篇博客) Java之SSM 实现导出数据(Excel表格,表格中显示图片导出js //导出 exportCar() { let app = this; app.loadingFlag = true; ...
  • 前几天需要将公众号中的用户发送的图片导出excel表格中,特此记录。 用户给公众号发送图片后,微信会推给开发者相关数据,比如openid,类型,图片地址等。 我需要做的是:获取图片地址,访问微信,获取图片, 写入...
  • 基本上导出的文件分为两种: 1:类Excel格式,这个其实不是传统意义上的Excel文件,只是因为Excel的兼容能力强,能够正确打开而已。修改这种文件后再保存,通常会提示你是否要转换成Excel文件。 优点:简单。 ...
  • 最近遇到一个需求,导出后台的数据,其中有一栏是图片也要一并导出。 首先查询mysql获取要导出的数据 $data=$this->model->whereIn('id',$ids)->select(); $data = collection($data)->toArray(); ...
  • 做公司内部系统时,经常会遇到做表格数据的导出表格导出很好实现,但是要实现带图片导出就有点困难,下面楼主我分享一下自己写的脚本。 导出数据里面需要包含图片连接,导出时会自动下载,并且保存到图片。 ...
  • Java之SSM 实现导出数据(Excel表格,表格中显示图片) 前端实现 页面上添加导出按钮<!-- 表格工具栏 --> <div id="toolbar" class="toolbar-btn-action"> <button id="btn_batch_delete" type=...
  • 老规矩上图,操作界面很简单,先看一下截面图 一秒钟识别一张,直接出来就是表格数据,前几天有人跟我说需要这样的系统 ...第三部、导出表格 完事啦 最后大家有好的建议或更改需求可以跟我联系 ...
  • poi版本为3.14public void excelOutput(){ try { HSSFWorkbook workbook = new HSSFWorkbook();//创建Excel工作簿对象 HSSFSheet sheet = workbook.createSheet();//在工作簿中创建工作表对象 workbook.setShee
  • // echarts图表容器 <div class="con-middle" id="shade2" v-show="type3 == 'D'">... //element表格 <div class="con-middle" v-show="type3 == ''" id="out-table3"> <el-table ...
  • POI excel导出插入图片无显示why

    千次阅读 2016-11-02 16:12:18
    代码如下,导出表格里无图片显示,图片路径正确。 @RequestMapping(value = "/exp/expScholarshipApply", method = RequestMethod.GET) public String exptest(HttpServletResponse response, HttpServletRequest...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 943
精华内容 377
关键字:

excel导出表格图片