자바 엑셀 템 플 릿 조작 및 다운로드

10859 단어

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

/**
 * ZHF   EXCEL    
 *
 * 
 * org.apache.commons
 * commons-collections4
 * 4.2
 * 
 */
public class ExportExcelUtil {

    public static void main(String[] args) {
        ExportExcelUtil exportExcelUtil = new ExportExcelUtil();
        List> rowDataList = new ArrayList<>();
        Map map = new HashMap<>();
        map.put(0, "ff");
        map.put(1, "AA");
        map.put(2, "BB");
        map.put(3, "CC");
        map.put(4, "DD");
        map.put(5, "EE");
        Map map1 = new HashMap<>();
        map1.put(0, "  ");
        map1.put(1, "  1");
        map1.put(2, "  3");
        map1.put(3, "  4");
        map1.put(4, "  5");
        map1.put(5, "  6");
        rowDataList.add(map);
        rowDataList.add(map1);
        String path = "D:/file/   .xls";
        String realPath = "D:/file/  ";
        String newFileName = "   [data]" + System.currentTimeMillis() + ".xlsx";
        exportExcelUtil.exportExcel(10, 2, rowDataList, path, realPath, newFileName);
    }


    /**
     *   excel
     *
     * @param rowIndex            
     * @param rowCount         ,      
     * @param rowDataList      ,         
     * @param path              
     * @param realPath           
     * @param newFileName      
     */
    public void exportExcel(int rowIndex, int rowCount, List> rowDataList, String path, String realPath, String newFileName) {

        File newFile = createNewFile(path, realPath, newFileName);
        // File newFile = new File("d:/ss.xls");

        //        ,
        InputStream is = null;
        HSSFWorkbook workbook = null;
        HSSFSheet sheet = null;
        try {
            is = new FileInputStream(newFile);//  excel       
            workbook = new HSSFWorkbook(is);//    workbook,
            //      sheet
            sheet = workbook.getSheetAt(0);
        } catch (Exception e1) {
            e1.printStackTrace();
        }

        if (sheet != null) {
            try {
                //    
                FileOutputStream fos = new FileOutputStream(newFile);
                HSSFRow row = sheet.getRow(rowIndex);
                if (row == null) {
                    row = sheet.createRow(rowIndex);
                }
                HSSFCell cell = row.getCell(0);
                if (cell == null) {
                    cell = row.createCell(0);
                }
                for (int m = 0; m < rowCount; m++) {
                    row = sheet.createRow((int) m + rowIndex);
                    //        
                    for (int i = 0; i < rowDataList.get(m).size(); i++) {
                        Map dataMap = rowDataList.get(m);
                        String value = dataMap.get(i);
                        if (value.equals("null")) {
                            value = " ";
                        }
                        cell = row.createCell(i);
                        cell.setCellValue(value);
                    }

                }
                workbook.write(fos);
                fos.flush();
                fos.close();

                //   
//                InputStream fis = new BufferedInputStream(new FileInputStream(
//                        newFile));
//                HttpServletResponse response = ServletActionContext.getResponse();
//                byte[] buffer = new byte[fis.available()];
//                fis.read(buffer);
//                fis.close();
//                response.reset();
//                response.setContentType("text/html;charset=UTF-8");
//                OutputStream toClient = new BufferedOutputStream(
//                        response.getOutputStream());
//                response.setContentType("application/x-msdownload");
//                String newName = URLEncoder.encode(
//                        "  " + System.currentTimeMillis() + ".xlsx",
//                        "UTF-8");
//                response.addHeader("Content-Disposition",
//                        "attachment;filename=\"" + newName + "\"");
//                response.addHeader("Content-Length", "" + newFile.length());
//                toClient.write(buffer);
//                toClient.flush();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    if (null != is) {
                        is.close();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        //         
        // this.deleteFile(newFile);
    }

    /**
     *     
     *
     * @param s    
     * @param t        
     */

    public void fileChannelCopy(File s, File t) {
        try {
            InputStream in = null;
            OutputStream out = null;
            try {
                in = new BufferedInputStream(new FileInputStream(s), 1024);
                out = new BufferedOutputStream(new FileOutputStream(t), 1024);
                byte[] buffer = new byte[1024];
                int len;
                while ((len = in.read(buffer)) != -1) {
                    out.write(buffer, 0, len);
                }
            } finally {
                if (null != in) {
                    in.close();
                }
                if (null != out) {
                    out.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     *   excel  ,              
     *
     * @param path              
     * @param realPath           
     * @param newFileName      
     * @return
     */
    public File createNewFile(String path, String realPath, String newFileName) {
        //     ,       ************************************************************
        //       
//        String path = "D:/file/   .xls";


        File file = new File(path);
        //        
//        String realPath = "D:/file/  ";
        //      
//        String newFileName = "JL07-01       [data]" + System.currentTimeMillis() + ".xlsx";
        //         
        File dir = new File(realPath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        //      excel
        File newFile = new File(realPath, newFileName);
        try {
            newFile.createNewFile();
            //         
            fileChannelCopy(file, newFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return newFile;
    }

    /**
     *        
     *
     * @param files
     */
    private void deleteFile(File... files) {
        for (File file : files) {
            if (file.exists()) {
                file.delete();
            }
        }
    }


 
다운로드 종류:
 //   word
    @RequestMapping(value = "/downWord")
    @ResponseBody
    public boolean downExcel(HttpServletRequest request, HttpServletResponse response) {
        String path = request.getParameter("downUrl");
        String regex = "YQSBYLB(.*?).xls";
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(path);
        while (m.find()) {
            String filename = "YQSBYLB" + m.group(1) + ".xls";
            ExcelExportUtil excelExport2 = new ExcelExportUtil();
            return excelExport2.downLoadFile(path, response, request, filename, "xls");
        }
        return false;
    }

 

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

public class ExcelExportUtil {
 
    /**
     *    excel
     *
     * @param filePath
     * @param response
     * @param request
     * @param fileName
     * @param fileType
     * @return
     */
    public boolean downLoadFile(String filePath,
                                HttpServletResponse response, HttpServletRequest request,
                                String fileName, String fileType) {
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            response.setContentType("text/html;charset=utf-8");
            request.setCharacterEncoding("UTF-8");
            String downLoadPath = filePath;
            long fileLength = new File(downLoadPath).length();
            if ("pdf".equals(fileType)) {
                response.setContentType("application/pdf;charset=UTF-8");
            } else if ("xls".equals(fileType)) {
                response.setContentType("application/x-msdownload;");
            } else if ("doc".equals(fileType)) {
                response.setContentType("application/msword;charset=UTF-8");
            }
            response.setHeader("Content-disposition", "attachment; filename=" + new String(fileName.getBytes("utf-8"), "ISO8859-1"));
            response.setHeader("Content-Length", String.valueOf(fileLength));
            bis = new BufferedInputStream(new FileInputStream(downLoadPath));
            bos = new BufferedOutputStream(response.getOutputStream());
            byte[] buff = new byte[2048];
            int bytesRead;
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bis != null)
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            if (bos != null)
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }
        return true;

    }

}

좋은 웹페이지 즐겨찾기