0
点赞
收藏
分享

微信扫一扫

打印,excel、pdf导出及导入

<font color=#999AAA >

</font>

@TOC

<hr style=" border:solid; width:100px; height:1px;" color=#000000 size=1">

前言

<font color=#999AAA >
</font>

<hr style=" border:solid; width:100px; height:1px;" color=#000000 size=1">

一、引入依赖

1.引入页面依赖

<!-- 引入Ajax库 -->
<script type="text/javascript" src="${urlPath }js/axios.min.js"></script>
<script type="text/javascript" src="${urlPath }js/qs.js"></script>
<!-- 引入打印控件 -->
<script type="text/javascript" src="${urlPath }js/LodopFuncs.js"></script>
<!-- UEditor富文本编辑器 -->
<script type="text/javascript" src="${urlPath }ueditor/ueditor.config.js"></script>
<script type="text/javascript" src="${urlPath }ueditor/ueditor.all.min.js"></script>

2.引入maven依赖


        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.12</version>
        </dependency>
        <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-base</artifactId>
            <version>3.0.1</version>
        </dependency>
        <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-web</artifactId>
            <version>3.0.1</version>
        </dependency>
        <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-annotation</artifactId>
            <version>3.0.1</version>
        </dependency>

        <!-- itextpdf -->
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>font-asian</artifactId>
            <version>7.0.4</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>kernel</artifactId>
            <version>7.0.4</version>
        </dependency>
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>io</artifactId>
            <version>7.0.4</version>
        </dependency>
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>layout</artifactId>
            <version>7.0.4</version>
        </dependency>
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>forms</artifactId>
            <version>7.0.4</version>
        </dependency>
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>pdfa</artifactId>
            <version>7.0.4</version>
        </dependency>
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>pdftest</artifactId>
            <version>7.0.4</version>
        </dependency>

二、elementui页面(含LODOP自动A4打印)

                <el-form :inline="true" :model="filterParams" size="mini" ref="filterParams" label-width="80px" label-position="left" @keyup.native.enter="handleQuery">
                    <el-form-item label="仓库" prop="warehouseid">
                        <el-select v-model="filterParams.warehouseid"  filterable @change="getCompanyIdList(filterParams.warehouseid)" >
                            <el-option v-for="warehousenameItem in warehousenameOptions" :key="warehousenameItem.id" :label="warehousenameItem.warehouseName" :value="warehousenameItem.id"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="企业名称" prop="companyId" >
                        <el-select v-model="filterParams.companyId"    filterable @focus="companyOnFocus()"  @change="getCompanyById(filterParams.companyId)" >
                            <el-option v-for="companyNameItem in companyIdOptions" :key="companyNameItem.id" :label="companyNameItem.name" :value="companyNameItem.id"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="地址" clearable prop="addrId">
                            <el-select v-model="filterParams.addrId" filterable >
                                <el-option v-for="addr in addrs" :key="addr.id" :label="addr.address" :value="addr.id"></el-option>
                            </el-select>
                    </el-form-item>
                    <el-form-item label="日期" prop="orderTime" >

                        <el-date-picker v-model="filterParams.orderTime" type="month" placeholder="选择对账时间">
                        </el-date-picker>

                    </el-form-item>
                    <el-form-item label="开票" prop="invoiceId" >
                        <el-select v-model="filterParams.invoiceId"  filterable  >
                            <el-option v-for="invoice in invoices" :key="invoice.id" :label="invoice.name" :value="invoice.id"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" icon="el-icon-search" @click="MonthUserQuery()">查询</el-button>
                        <el-button icon="icon iconfont icon-qingkong" @click="MonthUserClearQuery('filterParams','table')">清空</el-button>
                        <el-button icon="el-icon-printer" onclick="monthUserExportExcel()">导出Excel</el-button>
                        <el-button type="success" icon="el-icon-printer" @click="AutoA4monthUserPrint()">自动A4打印</el-button>
                        <el-button icon="el-icon-printer" @click="StopPrint()">停止自动</el-button>
                        <el-button size="mini" type="success" icon="el-icon-circle-plus-outline" :disabled="editForm" @click="handImport()">批量导入</el-button>
                    </el-form-item>
                </el-form>

                <!-- 导入文件 -->
             <el-dialog :title="dialogExcelTitle" :visible.sync="dialogExcelVisible"  width="500px">
                <el-form  label-width="100px" class="demo-ruleForm">

                  <el-upload
                  class="upload-demo"
                  :action="uploadUrl"
                  accept=".xls,.xlsx"
                  :on-preview="handlePreview"
                  :on-remove="handleRemove"
                  :before-remove="beforeRemove"
                  :on-success="fileSuccess"
                  multiple
                  :limit="1"
                  :on-exceed="handleExceed"
                  :file-list="fileList">
                  <el-button size="small" type="primary">点击上传</el-button>
                  <div slot="tip" class="el-upload__tip">只能上传excel文件</div>
                </el-upload>

                    <el-button @click="dialogExcelVisible = false">取消</el-button>
                </el-form>

            </el-dialog>

        ........................

    function exportExcel(type) {
        if (type == 1) {

            if (app.filterParams.companyId == null || app.filterParams.companyId == "") {
                app.$message({
                    message: '请至少选择一个企业!',
                    type: 'warning'
                });
                return;
            }
        }else{
            if(!app.filterParams.warehouseid){
                app.$message({
                    message: '请选择仓库!',
                    type: 'warning'
                });
                return;
            }
        }

        if(!app.filterParams.time){
            app.$message({
                message: '请选择时间范围!',
                type: 'warning'
            });
            return;
        }

        var str="";
        if(app.filterParams.orderTime!=null&&app.filterParams.orderTime.length>1){
            str+="&orderTime="+app.filterParams.orderTime;
        }
        if(app.filterParams.companyId!=null){
            str+="&companyId="+app.filterParams.companyId;
        }
        if(app.filterParams.addrId!=null){
            str+="&addrId="+app.filterParams.addrId;
        }

        if(app.filterParams.warehouseid!=null){
            str+="&warehouseid="+app.filterParams.warehouseid;
        }
        if(app.filterParams.warehouseid!=null){
            str+="&time="+app.filterParams.time;
        }
        if(app.filterParams.warehouseid!=null){
            str+="&invoiceId="+app.filterParams.invoiceId;
        }
        window.location.href = "${urlPath }report/"+(type == 1 ?"exportExcel": "exportExcelZip")+".do?type=1"+str;
    }
    function exportPDF(){
        var str="";
        if(app.filterParams.orderTime!=null&&app.filterParams.orderTime.length>1){
            str+="&orderTime="+app.filterParams.orderTime;
        }
        if(app.filterParams.companyId!=null){
            str+="&companyId="+app.filterParams.companyId;
        }
        if(app.filterParams.addrId!=null){
            str+="&addrId="+app.filterParams.addrId;
        }

        if(app.filterParams.warehouseid!=null){
            str+="&warehouseid="+app.filterParams.warehouseid;
        }
        if(app.filterParams.warehouseid!=null){
            str+="&time="+app.filterParams.time;
        }
        if(app.filterParams.warehouseid!=null){
            str+="&invoiceId="+app.filterParams.invoiceId;
        }
        window.location.href = "${urlPath }report/exportPDF.do?type=1"+str;
        }

.......................

AutoA4Print:function(){//自动A4打印
                    window.clearInterval(autoPrintTask);
                     var rtnData=null;
                     var _this = this;
                     LODOP = getLodop();
                     if(this.filterParams.warehouseid==null||this.filterParams.warehouseid==""){
                            this.$message({
                                  message: '请选择仓库!',
                                  type: 'warning'
                             });
                            return;
                        }
                     if(this.filterParams.orderTime==null||this.filterParams.orderTime==""){
                            this.$message({
                                  message: '请选择日期!',
                                  type: 'warning'
                             });
                            return;
                        }
                     if(this.filterParams.invoiceId==null||this.filterParams.invoiceId==""){
                            this.$message({
                                  message: '请选择开票类型!',
                                  type: 'warning'
                             });
                            return;
                        }

                     _this.$confirm("确认开始自动打印?", "系统提示", {
                            type : 'warning'
                        }).then(function() {
                    autoA4PrintTask = window.setInterval(function(){
                            //先要从数据库按照下单时间,将最新的数据拉出来并打印。
                            _this.doAsyncGetData(_this.autoPrintUrl, {warehouseid:_this.filterParams.warehouseid,dateTime:_this.filterParams.orderTime}, function(r) {
                        if(r.data!=null&&r.data.companyName!=null){
                            $("#companyname").html(r.data.companyName);
                            $("#readday").html(addDate(r.data.createTime,1));
                            $("#companyaddress").html(r.data.address);
                            $("#telephone").html(r.data.telephone);
                            $("#receiverName").html(r.data.receiverName);
                            $("#plate").html(r.data.plate + (r.data.remark? r.data.remark:''));
                            $("#sortNum").html(r.data.sortNum);
                            $("#serviceTel").html(r.data.serviceTel? r.data.serviceTel:'');
                            $("#monthlyBalance").html(r.data.monthlyBalance? "月结":'');
                            $("#isBag").html(r.data.isBag == "0"? "装筐":'');
                            _this.filterParams.companyId = r.data.companyId;
                            _this.filterParams.orderTime = r.data.createTime;
                            _this.filterParams.addrId=r.data.addrId;
                            _this.filterParams.orderId = r.data.id;
                            _this.filterParams.warehouseid  = r.data.warehouseid ;
                            debugger;
                            // 添加补货列表
                            _this.getOrderAddPrint(r.data.addrId);
                            // 添加减退列表
                            _this.getChangePrint(r.data.addrId);

                            if(r.data.isInvoice=="1"){//企业是需要开票
                                _this.doAsyncGetData(_this.dataInvoiceUrl,_this.filterParams,function(o){
                                    debugger;
                                    _this.tableData = o.data;
                                    var isTax = "0";
                                    for (var i in _this.tableData){
                                        var productName = _this.tableData[i].productName;
                                        if (productName == "运费"){
                                            isTax = "1";
                                            break;
                                        }
                                    }
                                    if(isTax == "1"){
                                        $("#chooseImageUrl").attr("src",r.data.taxImageUrl);
                                    } else {
                                        $("#chooseImageUrl").attr("src",r.data.imageUrl);
                                    }

                                        //然后需要将已经打印的打上标记
                                        _this.doAsyncPostDataNoRefresh(_this.insertInvoicePrintUrl, {id:r.data.id},function(p) {// 请求数据成功回调
                                            if(o.data.length>0){
                                            _this.pritFunc();
                                            }
                                        });
                                });

                            }
                            else
                                {
                                    //企业不需要开票就查询所有
                                     _this.doAsyncGetData(_this.dataUrl,_this.filterParams,function(o){
                                         _this.tableData = o.data;
                                         debugger;

                                            //然后需要将已经打印的打上标记
                                                _this.doAsyncPostDataNoRefresh(_this.insertInvoiceNoPrintUrl, {id:r.data.id},function(p) {// 请求数据成功回调
                                                    if(o.data.length>0){
                                                    _this.pritFunc();
                                                    }
                                                });

                                    });
                                    $("#chooseImageUrl").attr("src",r.data.taxImageUrl);

                                }

                        }
                    });
                        }, _this.printSpeed * 1000)});
                    },

                pritFunc:function(){//打印方法
                    debugger;
                    LODOP = getLodop();
                     LODOP.PRINT_INIT("单个打印");
                     var tableToPrint = document.getElementById('printReport');//将要被打印的表格
                     var str='<style type="text/css">.el-table__header{font-size:5mm;} .el-table__body{font-size:5mm;} .el-table__footer{font-size:5mm;} .cell{ text-align:center;}</style>'
                   //var newWin= window.open('','','width=1027,height=600,top=0, left=0, toolbar=no, menubar=no, scrollbars=no, resizable=no, location=no, status=no');//新打开一个空窗口
                     var parent = document.getElementById('printReport').childNodes[14];
                       var child =  parent.childNodes[8];

                       if(parent!=null&&parent!=undefined&&child!=null&&child!=undefined){
                           parent.removeChild(child);
                       }

                       var child2= parent.childNodes[7]
                       if(parent!=null&&parent!=undefined&&child2!=null&&child2!=undefined){
                           parent.removeChild(child2);
                       }
                       var printContent= tableToPrint.outerHTML.replace(/border="0"/g,'border="1"')+str;
                       LODOP.ADD_PRINT_HTM("0mm","2mm","241mm","250mm",printContent);
                       LODOP.PRINT();
                    },
             StopPrint:function(){//停止自动打印
                 this.$confirm("确认停止自动打印?", "系统提示", {
                        type : 'warning'
                    }).then(function() {
                        debugger;
                    window.clearInterval(autoPrintTask);
                    window.clearInterval(autoA4PrintTask)
                    });

                },
doAsyncPostDataNoRefresh : async function(url, params, func) {// POST数据请求
                // 获取实例对象
                var _this = this;
                loading();
                // 发送POST请求
                await axios.post(url, params)
                     .then(function (response) {
                         // 获取响应数据
                         var r = response.data;
                         if (r.success) {// 请求成功
                             /*if (_this.refreshData) {
                                 // 刷新数据表格
                                 _this.refreshData();
                             }*/
                             // 提示请求成功
                             _this.$message({
                                 message: r.message,
                                 type: "success"
                             });
                             // 隐藏提交表单
                             _this.dialogFormVisible = false;
                             if (func) {// 回调
                                 func(r);
                             }
                         } else {// 请求失败,服务器响应错误信息
                             // 提示错误
                             _this.$message.error(r.message);
                         }
                         unloading();
                     }).catch(function (error) {// 请求失败
                         unloading();
                         // 提示错误
                         _this.$message.error("服务器异常!");
                     });
            },
    .......................
        //导入
        handImport:function(){
            var _table  = this;
            if(_table.editFormEntity.warehouseid==null||_table.editFormEntity.warehouseid==""){
                this.$message({
                      message: '请选择仓库!',
                      type: 'warning'
                 });
                return;
            }
            else{
                _table  = this;
                app.fileList= [];
                _table.dialogExcelVisible = true;
            }
        },
                ..................
            handleRemove:function(file, fileList) {
                console.log(file, fileList);
              },
              handlePreview:function(file) {
                console.log(file);
              },
              handleExceed:function(files, fileList) {
                this.$message.warning(`当前限制选择 1个文件,本次选择了 ${files.length} 个文件,共选择了 ${files.length + fileList.length} 个文件`);
              },
              beforeRemove:function(file, fileList) {
                return this.$confirm(`确定移除 ${ file.name }?`);
              },
              fileSuccess:function(response, file, fileList){
                  debugger;
                  _table = this;
                 if( response.code=="0"){
                     alert("导入成功!");
                          _table.dialogExcelVisible = false;
                          _table.detailData = response.data;

                  }
              }

三、控制器及接口

1.单表多sheet


@RequestMapping("/exportExcel")
@ResponseBody
public void exportExcel(HttpServletResponse response, reportParam params) {
    try {
        List<Map<String, Object>> lists = this.exportExcelSheet(params);
        MyExcelExportUtil.exportExcel(lists,"送货单",ExcelType.HSSF,response);
    } catch (Exception e) {
        e.printStackTrace();
    }

}

/**
 * @Description 导出送货单添加多sheet
 * @return java.util.List<java.util.Map<java.lang.String,java.lang.Object>>
 **/
public  List<Map<String, Object>> exportExcelSheet(ReportParam params){

    List<Map<String, Object>> lists = new ArrayList<>();
    //sheet1
    List<ReportDto> dtos = reportService.excelAll(params);
    if(!dtos.isEmpty()){
        ExportParams exportParams = new ExportParams("送货单","送货单明细");
        exportParams.setTitleHeight((short) 6);
        exportParams.setStyle(ExcelExportMyStylerImpl.class);
        Map<String, Object> map = new HashMap<>();
        map.put("title",exportParams);
        map.put("entity", reportDto.class);
        map.put("data",dtos);
        lists.add(map);
    }

    //sheet2
    List<OrderReportDto> dtos1 = reportService.orderExcelAll(params);
    if(!dtos1.isEmpty()){
        ExportParams exportParams1 = new ExportParams("减退单","减退单明细");
        exportParams1.setTitleHeight((short) 6);
        exportParams1.setStyle(ExcelExportMyStylerImpl.class);
        Map<String, Object> map1 = new HashMap<>();
        map1.put("title",exportParams1);
        map1.put("entity", OrderReportDto.class);
        map1.put("data",dtos1);
        lists.add(map1);
    }
    return lists;
}

 /**
  * @Description 单表多sheet导出
  * @Param [list, headTitle, type, response]
  **/
 public static void exportExcel(List<Map<String, Object>> list, String headTitle,ExcelType type, HttpServletResponse response) {
     try {
         Workbook workbook = ExcelExportUtil.exportExcel(list,type);
         String fileName = headTitle + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
         fileName = URLEncoder.encode(fileName, "UTF8");
         response.setContentType("application/vnd.ms-excel;chartset=utf-8");
         response.setHeader("Content-Disposition", "attachment;filename="+fileName + ".xls");
         ServletOutputStream out=response.getOutputStream();
         workbook.write(out);
         out.flush();
         out.close();
     } catch (Exception e) {
         e.printStackTrace();
     }
 }

2.批量多表多sheet

    @RequestMapping("/monthUserExportExcelZip")
    @ResponseBody
    public void exportExcelZip(HttpServletResponse response, ReportParam params) {

        try {
            String fileName = "送货单-" + new SimpleDateFormat("yyyyMMdd").format(new Date());
            response.setContentType("application/vnd.ms-excel;chartset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF8") + ".zip");

            ZipOutputStream zipOut = new ZipOutputStream(response.getOutputStream());
            if (params.getInvoiceId() != null) {

                List<OrderGroupParam> list = reportService.getOrderGroup(params);
                list.forEach(e -> {
                    params.setCompanyId(e.getCompanyId());
                    params.setAddrId(e.getAddrId());
                    List<Map<String, Object>> lists = this.exportExcelSheet(params);
                    if(!lists.isEmpty()){
                        MyExcelExportUtil.exportExcel(lists,e.getCompanyName() + "-" + e.getStreet(),ExcelType.HSSF,zipOut);
                    }
                });

            }
            zipOut.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

/**
 * @Description 单表多sheet批量导出
 * @Param [list, headTitle, type, zipOS]
 **/
public static ZipOutputStream exportExcel(List<Map<String, Object>> list, String headTitle,ExcelType type, ZipOutputStream zipOS) {
    try {
        Workbook workbook = ExcelExportUtil.exportExcel(list,type);
        String fileName = headTitle + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        ZipEntry zipEntry = new ZipEntry(fileName+".xls");
        zipOS.putNextEntry(zipEntry);
        workbook.write(zipOS);
        return zipOS;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

3.PDF

    @RequestMapping("/exportPDF")
    @ResponseBody
    public Result exportPDF(HttpServletResponse response, MonthUserReportParam params) {
        try {
            String filePath = reportService.getPDF(params);

            if (StringUtils.isBlank(filePath)) {
                return Results.error("未知错误,请联系管理员");
            }

            File file = new File(filePath);
            // 取得文件名。
            String filename = file.getName();
            // 取得文件的后缀名。
            String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();

            // 以流的形式下载文件。
            InputStream fis = new BufferedInputStream(new FileInputStream(filePath));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            // 设置response的Header
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
            response.addHeader("Content-Length", "" + file.length());
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            toClient.write(buffer);
            toClient.flush();
            toClient.close();

        } catch (Exception e) {
            logger.error("导出送货单PDF失败!params:" + params.toString(), e);
        }
        return Results.error("导出送货单失败");
    }

    public String getPDF(ReportParam params) {
        // params.setInvoiceId("0");
        String companyName = "";
        String cachetImageUrl = null;   // 公章图片地址
        Calendar calendar = Calendar.getInstance();
        List<DeliveryNoteAllDto> deliveryNoteAllDtos = new ArrayList<DeliveryNoteAllDto>();
        try {
            Date btimeDate = params.getTime()[0];
            Date enDate = params.getTime()[1];
            int days = DateUtil.differentDays(btimeDate, enDate);

            for (int i = 0; i <= days; i++) {
                DeliveryDto deliveryDto = new DeliveryDto();
                calendar.setTime(btimeDate);
                if (i == 0) {
                    calendar.add(calendar.DATE, 0);
                } else {
                    calendar.add(calendar.DATE, 1);
                }

                btimeDate = calendar.getTime();

                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                params.setOrderTime(df.format(btimeDate));
                if (params.getOrderTime() == null || params.getOrderTime().equals("")) {
                    params.setOrderTime(sdf_day.format(new Date()));
                }
                if (params.getCompanyId() != null && !params.getCompanyId().equals("")) {

                    Date date = sdf_day.parse(params.getOrderTime());
                    params.setOrderTime(df.format(date));
                    List<ReportDto> dtos = this.listReport(params);
                    List<CompanyMessageDto> list = this.CompanyMessage(params);
                    CompanyMessageDto companyMessageDto = new CompanyMessageDto();
                    if (list.size() > 0) {
                        companyMessageDto = list.get(0);
                        deliveryDto.setAddress(companyMessageDto.getCompanyAddress());
                        deliveryDto.setBucketQuantity(companyMessageDto.getBucketQuantity());
                        deliveryDto.setCompanyName(companyMessageDto.getCompanyName());
                        deliveryDto.setCreateTime(companyMessageDto.getOrderTime());
                        deliveryDto.setPlateQuantity(companyMessageDto.getPlateQuantity());
                        deliveryDto.setReceiverName(companyMessageDto.getReceiverName());
                        deliveryDto.setTelephone(companyMessageDto.getTelephone());
                        companyName = companyMessageDto.getCompanyName();
                        if(params.getInvoiceId().equals("2")){
                            cachetImageUrl = companyMessageDto.getImageUrl();
                        }else{
                            cachetImageUrl = companyMessageDto.getTaxImageUrl();
                        }

                    }
                    if (dtos != null && dtos.size() > 0) {
                        ReportDto reportDto = new ReportDto();
                        reportDto.setProductName("合计");
                        BigDecimal itemAmount = EntityConvertor.count(dtos, ReportDto::getAllmoney);
                        reportDto.setAllmoney(itemAmount);
                        dtos.add(reportDto);
                    }
                    deliveryDto.setList(dtos);
                }
                deliveryDtos.add(deliveryDto);
            }

            // 添加减退
            List<OrderReportDto> orderAlterList = this.orderExcelAll(params);
            // 添加补货
            List<OrderAddReportDto> orderAddList = this.orderAddExcelAll(params);

            if(deliveryDtos.size()<=0 && orderAddList.isEmpty() && orderAddList.isEmpty()) {
                logger.error("导出送货单数据为0");
                return "";
            }
            return this.createPdf(deliveryDtos,orderAlterList,orderAddList,companyName, params.getEmail(),cachetImageUrl);

        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
            return "";
        }

    }

    /*
     * 送货单PDF
     */
    public String createPdf(List<DeliveryDto> dtos,List<OrderReportDto> orderAlterList,List<OrderAddReportDto> orderAddList,String companyName, String email,String cachetImageUrl) {
        Document document = null;
    //  logger.error("***************开始进入生产PDF文件");
        try {
            String fileName = companyName + UUID.randomUUID().toString().replace("-", "") + ".pdf";
            if (StringUtils.isBlank(pdfPath) ) {
                pdfPath = "C://songhuodan//";
            }
            String file = pdfPath + fileName;
            PdfWriter writer = new PdfWriter(file);
            PdfDocument pdf = new PdfDocument(writer);
            String fontPath = pdfFontPath + "STFANGSO.TTF";
            pdfFont = PdfFontFactory.createFont(fontPath, PdfEncodings.IDENTITY_H, true);
            document = new Document(pdf);
            boolean isNull = true;
            for (DeliveryDto deliveryDto : dtos) {

                if (deliveryDto.getList().size() <= 0) {
                    continue;
                }
                isNull = false;
                Paragraph title = new Paragraph(" 商 城 ").setFont(pdfFont).setFontSize(14)
                        .setTextAlignment(TextAlignment.CENTER).setBold();
                LocalDate date = LocalDate.parse(deliveryNoteAllDto.getCreateTime(), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                Paragraph p = new Paragraph("企业名称: " + deliveryDto.getCompanyName() + "     日期: "
                        + date.plusDays(1).toString()).setFont(pdfFont).setTextAlignment(TextAlignment.LEFT);
                Paragraph addr = new Paragraph("地址: " + deliveryDto.getAddress()).setFont(pdfFont)
                        .setWidthPercent(90).setTextAlignment(TextAlignment.LEFT);
                Paragraph pepole = new Paragraph("联系人: " + deliveryDto.getReceiverName()).setFont(pdfFont)
                        .setTextAlignment(TextAlignment.LEFT);
                Paragraph tel = new Paragraph("联系电话: " + deliveryDto.getTelephone()).setFont(pdfFont)
                        .setTextAlignment(TextAlignment.LEFT);
                Paragraph remark1 = new Paragraph("温馨提示:   ").setFont(pdfFont)
                        .setTextAlignment(TextAlignment.LEFT);
                Paragraph remark2 = new Paragraph(
                        "\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a02、误差;    ")
                                .setFont(pdfFont).setTextAlignment(TextAlignment.LEFT);
                Paragraph remark3 = new Paragraph(
                        "\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a03、联系客服,感谢您的配合;")
                                .setFont(pdfFont).setTextAlignment(TextAlignment.LEFT);
                Paragraph remark4 = new Paragraph(
                        "\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a04、请客户保存好")
                                .setFont(pdfFont).setTextAlignment(TextAlignment.LEFT);
                Paragraph remark5 = new Paragraph(
                        "\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0送_________框;回_________框;存_________框 ")
                                .setFont(pdfFont).setTextAlignment(TextAlignment.LEFT);
                // 定义表格
                Table table = new Table(new float[] { 50f, 150f, 120f, 60f, 60f, 80f });
                table.setWidth(UnitValue.createPercentValue(100));
                // 自定义的封装表格数据
                formatData(table, deliveryNoteAllDto.getList());
                document.add(title);
                document.add(p);
                document.add(addr);
                document.add(pepole);
                document.add(tel);
                document.add(table);
                document.add(remark1);
                document.add(remark2);
                document.add(remark3);
                document.add(remark4);
                document.add(remark5);

                // 为pdf添加公章图片水印
                int pageNum = pdf.getNumberOfPages();
                if(pageNum==1) {
                    this.watermarkImagePdf(pdf,cachetImageUrl,pageNum);
                }
                document.add(new AreaBreak(AreaBreakType.NEXT_PAGE));
                int pageNum1 = pdf.getNumberOfPages();
                if(pageNum1<=dtos.size() && pageNum1 != 1){
                    this.watermarkImagePdf(pdf,cachetImageUrl,pageNum1);
                }
            }

            // 添加减退
            if(!orderAlterList.isEmpty()){
                Paragraph title1 = new Paragraph("明 细").setFont(pdfFont).setFontSize(13)
                        .setTextAlignment(TextAlignment.CENTER).setBold();
                Table table1 = new Table(new float[] { 50f, 105f, 70f, 95f, 100f, 75f, 65f, 80f, 85f });
                formatAlterData(table1,orderAlterList);
                document.add(title1);
                document.add(table1);
            }

            // 添加补货
            if(!orderAddList.isEmpty()){
                Paragraph title2 = new Paragraph("明 细").setFont(pdfFont).setFontSize(13)
                        .setTextAlignment(TextAlignment.CENTER).setBold();
                Table table2 = new Table(new float[] { 50f, 105f, 70f, 125f, 130f, 80f });
                formatAddData(table2,orderAddList);
                document.add(title2);
                document.add(table2);
            }

            if(isNull){
                document.add(new Paragraph("无匹配数据").setFont(pdfFont).setFontSize(14).setTextAlignment(TextAlignment.CENTER).setBold());
            }
            document.close();

            String addressee = email;
            if (StringUtils.isAllBlank(addressee)) {
                addressee = "123456789@163.com";
            } else {
                /** 邮件标题 **/
                String subject = "送货单";
                /** 邮件正文 **/
                String content = "感谢您";
                /** 邮件文档 **/
                logger.error(addressee+"开始发送邮件");
                EmailHelp.sendEmail(file, addressee, content, subject);
                logger.error(addressee+"结束发送邮件");
            }
            logger.error("***************PDF文件生成完毕");
            return file;
        } catch (Exception e) {
            logger.error("*********生成的PDF报的错误***********"+e.getMessage());
            e.printStackTrace();

        }
        return "";
    }

4.批量导入excel

    @RequestMapping("/uploadExcel")
    @ResponseBody
    public Result uploadImage(MultipartFile file) {

        if(file!=null) {

         //检查文件
        try {
        MyExcelExportUtil.checkFile(file);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return Results.error("只能导入Excel格式文件");
        }
        List<ExcelImportDto> excelImportDtos = MyExcelExportUtil.importExcel(file, 1, 1, ExcelImportDto.class);
        List<ExcelImportDto> list = new ArrayList<ExcelImportDto>();
        if(excelImportDtos.size()>0) {
            for (ExcelImportDto excelImportDto : excelImportDtos) {
                if(excelImportDto!=null&&excelImportDto.getQuantity()!=null) {
                    int quantity = Integer.parseInt(excelImportDto.getQuantity());
                    if(quantity>0) {
                        if(excelImportDto.getTotalPrice()!=null) {
                            double AmountMoney = Double.parseDouble(excelImportDto.getTotalPrice());

                            double price = AmountMoney /quantity;
                            NumberFormat nf = NumberFormat.getNumberInstance();
                            nf.setMaximumFractionDigits(2);
                            excelImportDto.setPrice(nf.format(price));
                            excelImportDto.setId(UUID.randomUUID().toString());
                            list.add(excelImportDto);
                        }

                    }
                }
            }

        }

        return Results.listResult(list);
        }
        else {
            return Results.error("请选择文件");
        }

    }

    public static <T> List<T> importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class<T> pojoClass){
        if (file == null){
            return null;
        }
        ImportParams params = new ImportParams();
        params.setTitleRows(titleRows);
        params.setHeadRows(headerRows);
        List<T> list = null;
        try {
            list = ExcelImportUtil.importExcel(file.getInputStream(), pojoClass, params);
        }catch (NoSuchElementException e){
            throw e;
        } catch (Exception e) {
            e.printStackTrace();

        }
        return list;
    }

    /**
     * Excel 导入 数据源IO流,不返回校验结果 导入 字段类型 Integer,Long,Double,Date,String,Boolean
     * 
     * @param inputstream
     * @param pojoClass
     * @param params
     * @return
     * @throws Exception
     */
    public static <T> List<T> importExcel(InputStream inputstream, Class<?> pojoClass,
                                          ImportParams params) throws Exception {
        return new ExcelImportServer().importExcelByIs(inputstream, pojoClass, params).getList();
    }

在这里插入图<br/>片描述
在这里插入图片描述
在这里插入图片描述

<hr style=" border:solid; width:100px; height:1px;" color=#000000 size=1">

随心所往,看见未来。Follow your heart,see night!<br/>

欢迎点赞、关注、留言,一起学习、交流!

举报

相关推荐

0 条评论