strtus2 excel文件转pdf zip格式批量下载 java

5 篇文章 1 订阅
4 篇文章 0 订阅
package com.pageoffice.byb.yewu;

import com.byb.base.action.BaseAction;
import com.pageoffice.byb.util.MyUtil;
import com.pageoffice.byb.util.ZipUtilToFile;
import com.pageoffice.byb.yewu.pojo.Fxgc_Write;
import com.pageoffice.byb.yewu.services.YewuService;
import com.spire.xls.FileFormat;
import com.spire.xls.Workbook;
import com.spire.xls.Worksheet;
import org.apache.log4j.Logger;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


public class PdfDownLoadAction extends BaseAction {
    private Logger log = Logger.getLogger(PdfDownLoadAction.class);
    private String contentType;     // 保存文件类型
    private String fileName;        // 保存时的文件名//提供struts配置文件使用
    private InputStream inputStream;

    public String getContentType() {
        return contentType;
    }
    public void setContentType(String contentType) {
        this.contentType = contentType;
    }
    public String getFileName() {
        return fileName;
    }
    public void setFileName(String fileName) {
        this.fileName = fileName;
    }
    public InputStream getInputStream() {
        return inputStream;
    }
    public void setInputStream(InputStream inputStream) {
        this.inputStream = inputStream;
    }

    public String export_tables_byIds() {
        HttpServletRequest request = getRequest();
        YewuService yewuSer = new YewuService();
        String returnMeg = "error";
        try {
            String ids = request.getParameter("ids");
            String fileSuffix = ".pdf";
            List<Fxgc_Write> writes = yewuSer.getTableFilePathById(ids);
            ServletContext webRoot = request.getSession().getServletContext();
            //数据库存储文件路径
            String afilePath = null;
            //服务器文件磁盘存储位置
            String realPath = null;
            //服务器转换后pdf文件路径
            String fileOut = null;
            if (writes.size() > 0 && writes.size() <= 1) {
                //设置导出文件类型
                contentType = "application/pdf";
                afilePath = writes.get(0).getFilePath();
                //服务器磁盘excel文件存放路径
                realPath = webRoot.getRealPath(afilePath);
                fileOut = realPath.replaceAll(".xls$|.xlsx$", ".pdf");
                //转换pdf
                File file = new File(fileOut);
//excel 文件转pdf
                Workbook workbook = new Workbook();
                workbook.loadFromFile(realPath);
                Worksheet sheet = workbook.getActiveSheet();
                sheet.getPageSetup().setFitToPagesTall(1);
                sheet.getPageSetup().setFitToPagesWide(1);
                workbook.saveToFile(fileOut, FileFormat.PDF);
                inputStream = new FileInputStream(file);
                String dName = writes.get(0).getCode() + writes.get(0).getTitle() + fileSuffix;
                fileName = MyUtil.toUTF8String(dName);
            }else {
                contentType = "application/x-zip-compressed";
                ArrayList<String> zipFiles = new ArrayList<String>();
                //打成压缩包批量下载
                for(int w = 0; w < writes.size(); w++) {
                    afilePath = writes.get(w).getFilePath();
                    //服务器磁盘excel文件存放路径
                    realPath = webRoot.getRealPath(afilePath);
//                    fileOut = realPath.replaceAll(".xls$|.xlsx$", ".pdf");
                    //转换pdf
                    Integer index =  realPath.lastIndexOf("\\");
                    String a = realPath.substring(0, index+1);
                    String zipPdf = writes.get(w).getCode() + writes.get(w).getTitle() + fileSuffix;
                    String newFileName = a + zipPdf;
                    File newF = new File(newFileName);
                    if(!newF.exists()) {
                        newF.createNewFile();
                    }
                    Workbook workbook = new Workbook();
                    workbook.loadFromFile(realPath);
                    Worksheet sheet = workbook.getActiveSheet();
                    sheet.getPageSetup().setFitToPagesTall(1);
                    sheet.getPageSetup().setFitToPagesWide(1);
                    workbook.saveToFile(newFileName, FileFormat.PDF);
                    zipFiles.add(newFileName);
                }
                String zipPath = webRoot.getRealPath("/downloadZip/");
                String formatDate = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
                String zipfileName = formatDate + ".zip";
                String path = zipPath + File.separator + zipfileName;
                File zipdir = new File(path);
                File zipdirPar = zipdir.getParentFile();
                if(!zipdirPar.exists()) {
                    zipdirPar.mkdir();
                }
                if(!zipdir.exists()) {
                    zipdir.createNewFile();
                }
                ZipUtilToFile.compressFile(zipFiles, path);
                inputStream = new FileInputStream(zipdir);
                fileName = MyUtil.toUTF8String(zipfileName);
            }
            returnMeg = SUCCESS;
        } catch (Exception e) {
            log.error("下载文件失败原因:", e);
            e.printStackTrace();
        }
        return returnMeg;
    }
}

 

//转utf-8
public class MyUtil {
    public static String toUTF8String(String str){
        StringBuffer sb = new StringBuffer();
        int len = str.length();
        for (int i = 0; i < len; i++)
        {
            // 取出字符中的每个字符
            char c = str.charAt(i);
            // Unicode码值在0~255之间,不做处理
            if(c>=0 && c <= 255){
                sb.append(c);
            }else {
                // 转换 UTF-8 编码
                byte b[];
                try{
                    b = Character.toString(c).getBytes("UTF-8");
                }catch(UnsupportedEncodingException e){
                    e.printStackTrace();
                    b = null;
                }
                // 转换为%HH的字符串形式
                for(int j = 0;j < b.length ; j++){
                    int k = b[j];
                    if(k < 0){
                        k &= 255;
                    }
                    sb.append("%" + Integer.toHexString(k).toUpperCase());
                }
            }
        }
        return sb.toString();
    }
}

 

 

import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
import org.apache.tools.zip.ZipOutputStream;

import java.io.*;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.CRC32;
import java.util.zip.CheckedInputStream;

public class ZipUtilToFile {
    /**压缩文件
     * @param srcFile 源文件路径
     * @param destFile 目标文件路径
     */
    public static void compressFile(File[] srcFile, String destFile) {
        OutputStream outputStream=null;
        ZipOutputStream zipOutputStream=null;
        try {
            outputStream=new FileOutputStream(new File(destFile));
            zipOutputStream=new ZipOutputStream(outputStream);
            zipOutputStream.setEncoding("GBK");

            for(File file:srcFile) {
                startZip(zipOutputStream,"",file);
            }

            //File file=new File(srcFile);

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if(zipOutputStream!=null) {
                    zipOutputStream.close();
                }
                if(outputStream!=null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    public static void compressFile(List<String> srcFile, String destFile) {
        OutputStream outputStream=null;
        ZipOutputStream zipOutputStream=null;
        try {
            outputStream=new FileOutputStream(new File(destFile));
            zipOutputStream = new ZipOutputStream(outputStream);
            zipOutputStream.setEncoding("gbk");

            for(String str:srcFile) {
                File file=new File(str);
                startZip(zipOutputStream,"",file);
            }
            //File file=new File(srcFile);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if(zipOutputStream!=null) {
                    zipOutputStream.close();
                }
                if(outputStream!=null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void startZip(ZipOutputStream zipOutputStream,String oppositePath,File file) {
        InputStream inputStream=null;
        BufferedInputStream bufferedInputStream=null;
        try {
            System.out.println("当前压缩目录或文件:"+file.getName());
            //目录
            if(file.isDirectory()) {
                //若是目录创建目录
                String newoppositePath1=oppositePath+file.getName()+"/";
                ZipEntry zipEntry1=new ZipEntry(newoppositePath1);
                zipOutputStream.putNextEntry(zipEntry1);
                zipOutputStream.closeEntry();
                File[] files=file.listFiles();
                for(File f:files) {
                    if(f.isDirectory()) {
                        //创建压缩文件的目录结构
//                      String newoppositePath2=newoppositePath1+f.getName()+"/";
//
//                      ZipEntry zipEntry2=new ZipEntry(newoppositePath2);
//                      zipOutputStream.putNextEntry(zipEntry2);
//                      zipOutputStream.closeEntry();
                        startZip(zipOutputStream,newoppositePath1,f);
                        //文件
                    }else {
                        zipFile(zipOutputStream,newoppositePath1,f);
                    }
                }

                //文件
            }else {
                zipFile(zipOutputStream,oppositePath,file);

            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if(bufferedInputStream!=null) {
                    bufferedInputStream.close();
                }
                if(inputStream!=null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }



    public static void zipFile(ZipOutputStream zipOutputStream,String oppositePath,File file) {
        //System.out.println("正在压缩文件:"+file.getName());
        InputStream inputStream=null;
        BufferedInputStream bufferedInputStream=null;

        try {
            zipOutputStream.putNextEntry(new ZipEntry(oppositePath+file.getName()));
            inputStream=new FileInputStream(file);
            bufferedInputStream=new BufferedInputStream(inputStream);
            byte[] buffer=new byte[bufferedInputStream.available()];
            Integer length=null;
            while((length=bufferedInputStream.read(buffer))!=-1) {
                zipOutputStream.write(buffer, 0, length);
            }
            zipOutputStream.closeEntry();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * @param zipPath
     * @param outPath 该参数最后要加File.separator,例c:\data\
     */
    public static void decomprecessFile(String zipPath,String outPath) {
        OutputStream outputStream=null;
        BufferedOutputStream bufferedOutputStream=null;
        InputStream inputStream=null;
        BufferedInputStream bufferedInputStream=null;
        CheckedInputStream checkedInputStream=null;
        try {
            ZipFile zipFile=new ZipFile(zipPath,"GBK");
            //获取压缩文件中的所有项
            for(Enumeration<ZipEntry> enumeration = zipFile.getEntries(); enumeration.hasMoreElements();) {
                ZipEntry zipEntry=(ZipEntry) enumeration.nextElement();
                System.out.println(zipEntry.getName());
                //目录,创建目录
                if(zipEntry.getName().endsWith("/")) {
                    File f=new File(outPath+zipEntry.getName());
                    f.mkdirs();
                    //文件,创建文件
                }else {
                    outputStream=new FileOutputStream(outPath+zipEntry.getName());
                    bufferedOutputStream=new BufferedOutputStream(outputStream);

                    inputStream=zipFile.getInputStream(zipEntry);
                    bufferedInputStream=new BufferedInputStream(inputStream);

                    checkedInputStream=new CheckedInputStream(bufferedInputStream,new CRC32());
                    byte[] buffer=new byte[bufferedInputStream.available()];
                    Integer length=null;
                    while((length=checkedInputStream.read(buffer))!=-1) {
                        bufferedOutputStream.write(buffer, 0, length);
                    }
                    bufferedOutputStream.flush();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if(bufferedOutputStream!=null) {
                    bufferedOutputStream.close();
                }
                if(outputStream!=null) {
                    outputStream.close();
                }
                if(checkedInputStream!=null) {
                    checkedInputStream.close();
                }
                if(bufferedInputStream!=null) {
                    bufferedInputStream.close();
                }
                if(inputStream!=null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

strtus.xml配置

<action name="export_tables_byIds" class="com.pageoffice.byb.yewu.PdfDownLoadAction" method="export_tables_byIds">
   <result name="success" type="stream">
      <param name="contentType">${contentType}</param>
      <param name="inputName">inputStream</param>
      <param name="contentDisposition">attachment;filename=${fileName}</param>
      <param name="bufferSize">4096</param>
   </result>
   <result name="error">/core/pageoffice/fx_write/error.jsp</result>
</action>

最重要就是excel转pdf的jar包

我提供两个下载地址;

之前下载地址1,不限速,不知道现在还能不能用了,如果不信就点第二个下载地址

下载地址1:http://raboninco.com/23880909/downloadsfree-spire-xls-javahtml

 

下载地址2:https://www.e-iceblue.cn/Downloads/Free-Spire-XLS-JAVA.html

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值