Java POI 实现文件下载预览功能

这个工具类主要用于文件的复制、清理缓存、获取Excel模板文件及sheet名称等功能,使用了Apache POI库来处理Excel。提供获取当前时间、文件夹清理、按行列序号获取Excel单元格坐标等方法。
摘要由CSDN通过智能技术生成
/**
     * 下载附件
     * @param adtpaccid
     * @param request
     * @param response
     * @return
     */
    public String downLoadWriteAccService(String adtmainaccsid,HttpServletRequest request,HttpServletResponse response){

        String downDetail = null;
        String rPath; //附件相对路径
        String tPath; //附件绝对路径
        try
        {
            AqFile aqFile = aqFileDao.findById(adtmainaccsid);
            if(null != aqFile){
                rPath = aqFile.getPath();
                if(null != rPath && !"".equals(rPath)){
                    //获取绝对路径
                    tPath = request.getSession().getServletContext().getRealPath(rPath);
                    //判断文件是否存在于硬盘上
                    File f = new File(tPath);
                    if(f.exists()){
                        if(f.isFile()){
                            //下载
                            CellInfoUtil.downFileProcess(request, response, tPath, aqFile.getFileName());
                        }else{
                            downDetail = "数据库存储的附件信息有误,路径指向的是文件夹而非文件,无法下载!";
                        }
                    }else{
                        downDetail = "文件可能已经被删除,无法下载!";
                    }

                }else{
                    downDetail = "数据库存储的附件信息丢失,不存在文件路径,无法下载!";
                }
            }else{
                downDetail = "不存在的附件!";
            }
        }catch (java.io.IOException e) {
            logger.error("客户端接收下载的文件突然中断!");
        }catch (Exception e) {
            downDetail = "下载附件发生异常!";
            logger.error(":"+e.getMessage());
        }finally{

        }
        return downDetail;
    }

     /**
     * 在线预览
     *
     * @param request
     * @param response
     * @return
     */
    public boolean queryToPreview(HttpServletRequest request,
            HttpServletResponse response) throws IOException {

        logger.info("begin finding.......");
        boolean isSucc = false;
        PrintWriter pw;
        pw = response.getWriter();
        try {
            String urlReal = "";
            String str = "";
            System.out.println("进入方法!");
            String id = request.getParameter("id");
            List<AqFile> aqFile = this.getAqFileDao().findByHql(
                    "from AqFile where id='" + id + "'");
            request.setAttribute("aqFile", aqFile);
            for (AqFile aqfile : aqFile) {
                urlReal = aqfile.getPath();
                System.out.println(urlReal);
                String basepath = this.getClass().getClassLoader().getResource(
                "").toString();
                System.out.println("---------------" + basepath);
                String base = (String) basepath.subSequence(6, basepath
                        .lastIndexOf("/") - 15);
                System.out.println(base);
                File file = new File(base + urlReal);
                if (urlReal.endsWith(".doc")) {
                    System.out.println("1111111111123");
                    str = Test.doWord(file, base, request, response);
                    if (str != null) {
                        str = "wordHtm/" + str;
                        Map map = new HashMap();
                        map.put("url", str);
                        JSONArray json = new JSONArray();
                        json.put(map);
                        pw.print(json.toString());
                    }
                }else if (urlReal.endsWith(".pdf")) {
                    str = urlReal;
                    Map map = new HashMap();
                    map.put("url", str);
                    if(file.exists()){
                        JSONArray json = new JSONArray();
                        json.put(map);
                        pw.print(json.toString());                    
                    }else{
                        str="ToDo";
                    }
                } else if (urlReal.endsWith(".docx")) {
                    str = Test.doWord2007(file, base, request, response);
                    if (str != null) {
                        str = "wordHtm/" + str;
                        Map map = new HashMap();
                        map.put("url", str);
                        JSONArray json = new JSONArray();
                        json.put(map);
                        pw.print(json.toString());
                    }

                }  else if (urlReal.endsWith(".jpg")) {                    

                    str = urlReal;
                    Map map = new HashMap();
                    map.put("url", str);
                    if(file.exists()){
                        JSONArray json = new JSONArray();
                        json.put(map);
                        pw.print(json.toString());                    
                    }else{
                        str="ToDo";
                    }

                } else if (urlReal.endsWith(".png")) {            

                    str = urlReal;
                    Map map = new HashMap();
                    map.put("url", str);
                    if(file.exists()){
                        JSONArray json = new JSONArray();
                        json.put(map);
                        pw.print(json.toString());                    
                    }else{
                        str="ToDo";
                    }
                }else if (urlReal.endsWith(".gif")) {            

                    str = urlReal;
                    Map map = new HashMap();
                    map.put("url", str);
                    if(file.exists()){
                        JSONArray json = new JSONArray();
                        json.put(map);
                        pw.print(json.toString());                    
                    }else{
                        str="ToDo";
                    }            
                }else if (urlReal.endsWith(".rar")) {            

                    str = urlReal;
                    Map map = new HashMap();
                    map.put("url", str);
                    if(file.exists()){
                        JSONArray json = new JSONArray();
                        json.put(map);
                        pw.print(json.toString());                    
                    }else{
                        str="ToDo";
                    }        
                }else if (urlReal.endsWith(".zip")) {            

                    str = urlReal;
                    Map map = new HashMap();
                    map.put("url", str);
                    if(file.exists()){
                        JSONArray json = new JSONArray();
                        json.put(map);
                        pw.print(json.toString());                    
                    }else{
                        str="ToDo";
                    }        
                }else {
                    Map map = new HashMap();
                    str = "wordHtm/ToDo";
                    map.put("url", str);
                    JSONArray json = new JSONArray();
                    json.put(map);
                    pw.print(json.toString());    
                }

                // upfile/transferFile/b0e05d39e43540c4a2f971519efe11f4
                // pw.print(str);
                // WordToHtml.zhuanhuan(urlReal);
                // String url =
                // Word2Html.wordToHtml("D:/apache-tomcat-6.0.45/webapps/htmis/",
                // urlReal);
                // if(url!=null){
                // System.out.println(url);
                // String fileurl =
                // url.substring(url.lastIndexOf("\\")+1,url.lastIndexOf("."));
                // String realurl = "upfile/transferFile/"+fileurl;
                // System.out.println(fileurl);
                // System.out.println(realurl);
                // Map map =new HashMap();
                // map.put("url", realurl);
                // JSONArray json = new JSONArray();
                // json.add(map);
                // pw.print(json.toString());
                // }
            }
            // File sourceFile = new
            // File("D:/apache-tomcat-6.0.45/webapps/htmis/jsp/auditofficial/auditmainfile/20161204091718/b462d82d6dbb48b487f5c57d862cc1b0");
            // File pdfFile = new
            // File("D:/apache-tomcat-6.0.45/webapps/htmis/jsp/auditofficial/auditmainfile/20161204091718/b462d82d6dbb48b487f5c57d862cc1b0");
            // File swfFile = new
            // File("D:/apache-tomcat-6.0.45/webapps/htmis/jsp/auditofficial/auditmainfile/20161204091718/b462d82d6dbb48b487f5c57d862cc1b0");

            isSucc = true;
        } catch (RuntimeException re) {
            isSucc = false;
            pw.print("");
            logger.error("begin failed,error:" + re);
            throw re;
        }
        // catch (IOException r) {
        // isSucc=false;
        // logger.error("begin failed,error:"+r);
        //            
        // }

        return isSucc;

    }

///工具类

public class CellInfoUtil {
    static Logger logger = Logger.getLogger(CellInfoUtil.class);
    private static final char[] ABC_CHARArray = new char[26];//26个英文字母
    
    private static final char[] chinaCharArray = new char[10];//10个中文汉字
    
    private static String ptheExcelOutFileDirPath = null;//导出excel展现文件临时的根目录。注意每一个附件的目录结构为 根目录/excelviewfile。其文件统一制作删除功能
    
    private static String ptheOutFileTmpDirPath = null;//导出文件临时的根目录。注意每一个附件的目录结构为 根目录/reportFilesExpFileTmp
    
    private static String ptheImgFileTmpDirPath = null;//word统计时产生的临时图片的根目录。注意每一个附件的目录结构为 根目录/wordTempFile
    
    private static String strExcelPathApp = null;//excel模板文件根目录
    
    private static final int intClearMaxUnit = 1200;//excel清理缓存文件,最大时间间隔。精确到秒。
    
    private static final int intImgClearMaxUnit = 72000;//图片清理缓存文件,用于word统计,比excel时间要长一些,最大时间间隔。精确到秒。默认20小时,即72000
    private static final boolean isOutInputBorder = false;//在填报时,下载文件时,是否强行按照规定的格式显示每一个单元格的边框。如果为false,显示整行边框
    
    public static String getPtheOutFileTmpDirPath() {
        if(null == ptheOutFileTmpDirPath || ptheOutFileTmpDirPath.trim().equals("")){
            String strPath = CellInfoUtil.class.getResource("/").getPath().replace("/", "\\");
            ptheOutFileTmpDirPath = strPath.substring(0,strPath.indexOf("WEB-INF"))+"\\reportFilesExpFileTmp\\";
        }
        return ptheOutFileTmpDirPath;
    }
    /**
     * 文件拷贝
     * @param srcFilePath
     * @param targerFilePath
     * @throws Exception
     */
    public static void copyFileProcess(String srcFilePath,String targerFilePath) throws Exception{
        CommonXfile cxf = new CommonXfile(1);
        //进行文件拷贝
        try{
            cxf.copyFile(srcFilePath, targerFilePath);
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 拷贝attachFile下的所有文件到指定的文件夹
     * @param attachFile
     * @param dirpath
     * @return
     * @throws Exception
     */
    public static boolean copyFilesToDirpath(File attachFile,String dirpath) throws Exception{
        if(null != attachFile.listFiles() && attachFile.listFiles().length>0){
            //表示还需要拷贝
            for(File tempFile:attachFile.listFiles()){
                if(null != tempFile.listFiles() && tempFile.listFiles().length>0){
                    if(!CellInfoUtil.copyFilesToDirpath(tempFile, dirpath+"\\"+tempFile.getName())){
                        return false;
                    }
                }else{
                    //表示是文件
                    CellInfoUtil.copyFileProcess(tempFile.getPath(), dirpath+"\\"+tempFile.getName());
                }
            }
            return true;
        }else{
            CellInfoUtil.copyFileProcess(attachFile.getPath(), dirpath+"\\"+attachFile.getName());
            return true;
        }
    }

    /**
     * 根据主表记录获取系统中保存的模板文件
     * @param strFilepath
     * @return
     * 成功:HSSFWorkbook
     * 失败:null
     */
    public static HSSFWorkbook getHSSFWorkbookByJcJjfMxModelCellMain(String strFilepath){
        HSSFWorkbook workbook = null;
        try{
            File wbfile = new File(getStrExcelPathApp()+strFilepath.trim());
            if(wbfile.exists()){
                //表示文件存在
                FileInputStream fis = new FileInputStream(wbfile);
                workbook = new HSSFWorkbook(new POIFSFileSystem(fis));
                fis.close();
            }else{
                logger.error("没有找到文件:"+getStrExcelPathApp()+strFilepath.trim()+"!");
                workbook = null;
            }
        }catch(Exception e){
            logger.error("根据根据路径:"+strFilepath+" 获取对应的文件时出错,原因:"+e);
            workbook = null;
        }
        return workbook;
    }
    /**
     * 获取excel模板文件根目录
     * @return
     */
    public static String getStrExcelPathApp(){
        if(null == strExcelPathApp || strExcelPathApp.trim().equals("")){
            String strPath = ExlCreatService.class.getResource("/").getPath().replace("/", "\\");
            strExcelPathApp = strPath.substring(0,strPath.indexOf("WEB-INF"))+"\\excelmodelfile\\";
        }
        return strExcelPathApp;
    }
    /**
     * 根据excel文件获取包含的sheet名称
     * @param excelFile
     * @return
     * 成功:List<String>
     * 失败:null
     */
    public static List<String> getSheetNameListByExcelFile(File excelFile){
        List<String> sheetNameList = null;
        try{
            sheetNameList = new ArrayList<String>();
            if(null != excelFile){
                FileInputStream fis = new FileInputStream(excelFile);
                HSSFWorkbook workbook = new HSSFWorkbook(new POIFSFileSystem(fis));
                fis.close();
                int sheetCon = workbook.getNumberOfSheets();//获取sheet个数
                if(sheetCon > 0){
                    for(int i=0;i<sheetCon;i++){
                        sheetNameList.add(workbook.getSheetAt(i).getSheetName());
                    }
                }
            }else{
                return sheetNameList;
            }
        }catch(Exception e){
            logger.error("根据文件"+excelFile.getName()+"获取对应的sheet名称的时候出错,原因:"+e);
            if(null != sheetNameList && sheetNameList.size() >0){
                sheetNameList.clear();
            }
            sheetNameList = null;
        }
        return sheetNameList;
    }
    
    /**
     * 获取文件夹所用的当前时间
     * @return
     */
    public static String getNowFileDateTime(){
        Calendar c = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String nowDateTime = sdf.format(c.getTime());
        return nowDateTime;
    }
    
    /**
     * 清理无用的缓存文件
     * @return
     */
    public static void clearTepFile(){
        try{
            File pdirFile = new File(getPtheOutFileTmpDirPath());
            if(pdirFile.exists()){
                File[] dirFileArray = pdirFile.listFiles();
                Calendar c = Calendar.getInstance();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
                String nowDate = sdf.format(c.getTime()).substring(0,8);
                String nowDateTime = sdf.format(c.getTime());
                if(null != dirFileArray && dirFileArray.length>0){
                    File[] dirSubFileArray = null;
                    for(File tempFile:dirFileArray){
                        if(!tempFile.isDirectory()){
                            tempFile.delete();
                            continue;
                        }
                        if((Long.valueOf(tempFile.getName())+1)<Long.valueOf(nowDate)){
                            //如果与当前间隔超过一天的话,肯定不会再使用。直接删除
                            deleteFileAll(tempFile);
                        }else{
                            //需要比较处理的时间和当前时间的间隔是否小于最小时间,如果小于的话,不处理;否则删除
                            dirSubFileArray = tempFile.listFiles();
                            if(null != dirSubFileArray && dirSubFileArray.length>0){
                                for(File tempSubFile:dirSubFileArray){
                                    //System.out.println(tempFile.getName()+tempSubFile.getName().substring(0,6));
                                    if((Long.valueOf(tempFile.getName()+tempSubFile.getName().substring(0,6))+intClearMaxUnit)<=Long.valueOf(nowDateTime)){
                                        //表示当前时间比缓存文件生成时间晚与最小时间,可以删除
                                        deleteFileAll(tempSubFile);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }catch(Exception e){
            logger.error("清除缓存的时候发生错误,原因:"+e);
        }
    }
    
    private static char[] getABC_CHARArray(){
        if('Z' != ABC_CHARArray[25]){
            for(int i=0;i <26;i++){
                ABC_CHARArray[i] = (char)('A'+i);
            }
        }
        return ABC_CHARArray;
    }
    
    /**
     * 根据行列序号获取单元格在excel中的显示坐标
     * @param colIndex 列序号,需要大于等于0
     * @param rowIndex 行序号,需要大于等于0
     * @return
     */
    public static String getExcelCellXY(int colIndex,int rowIndex){
        if(colIndex > 25){
            //return getABC_CHARArray()[(colIndex/25)-1]+getABC_CHARArray()[(colIndex%25)-1]+""+(rowIndex+1);
            return getABC_CHARArray()[(colIndex/25)-1]+""+getABC_CHARArray()[(colIndex%25)-1]+""+(rowIndex+1);
        }else{
            return getABC_CHARArray()[colIndex]+""+(rowIndex+1);
        }
    }

    /**
     * 下载文件处理
     * @param request
     * @param response
     * @param processFilePath
     * @param fileName
     */
    public static void downFileProcess(HttpServletRequest request,HttpServletResponse response,String processFilePath,String fileName) throws Exception{
        CommonXfile cxf = new CommonXfile(1);
        //进行下载
        try{
            cxf.downloadFile(processFilePath,fileName,request,response);
        }catch(Exception e){
            e.printStackTrace();
        }
    }
    /**
     * 下载文件处理
     * @param request
     * @param response
     * @param processFilePath
     */
    public static void downFileProcess(HttpServletRequest request,HttpServletResponse response,String processFilePath) throws Exception{
        CommonXfile cxf = new CommonXfile(1);
        //进行下载
        try{
            cxf.downloadFile(processFilePath,request,response);
        }catch(Exception e){
            
        }
    }
    /**
     * 获取处理周期值的起始日期
     * @param p_rptday
     * @param modelcyc DMSHY/日、月、季、半年、年
     * @return
     */
    publ

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值