Excel相關操作 —— poi

ExcelUtil —— excel相關通用方法總結

1、上傳下載
2、樣式設置
3、單元格設置檢測

import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class ExcelUtil {
    private static final Logger LOG = LoggerFactory.getLogger(ExcelUtil.class);
    /**
     * 將Excel工作簿用response輸出流輸出(默認導出爲.xls格式)
     *
     * @param wb 輸出的工作薄
     * @param rp 前端響應response
     */
    public static void exportExcel(Workbook wb, HttpServletResponse rp) {
        String time = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        int random = (int) (Math.random() * 1000);
        //獲得隨機文件名
        String name = time + random;
        rp.reset();
        rp.setContentType("application/octet-stream;charset=GBK");
       	try {
            rp.setHeader("Content-Disposition", "attachment;filename=" + new String((name + ".xls").getBytes("ISO8859-1"), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        rp.setCharacterEncoding("UTF-8");
        try(OutputStream out = rp.getOutputStream()) {
           
            wb.write(out);

        } catch (Exception e) {
            LOG.error(e.getMessage());
        } 
    }
    

    /**
     * 設置通用樣式的單元格
     *
     * @param cellNo    單元格號
     * @param cellValue 單元格內容
     */
    public void setCell(Row row, int cellNo, Object cellValue) {

        Cell cell = row.getCell(cellNo);
        if (cell == null){
            cell = row.createCell(cellNo);
        }

        if (cellValue == null) {
            cell.setCellValue("");
        } else {
            String cellType = cellValue.getClass().getName();
            cellType = cellType.substring(cellType.lastIndexOf(".") + 1, cellType.length());
            if (cellType.equals("String")) {
                cell.setCellValue(cellValue.toString());
            } else if (cellType.equals("Double") || cellType.equals("BigDecimal")) {
                cell.setCellValue(Double.parseDouble(cellValue.toString()));
            } else if (cellType.equals("Integer")) {
                cell.setCellValue(Integer.parseInt(cellValue.toString()));
            } else if (cellType.equals("HSSFPicture")) {
                cell.setCellValue("");
            } else if (cellType.equals("Timestamp")) {
                DateFormat formater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                cell.setCellValue(formater.format(cellValue));
            } else if (cellType.equals("Date")) {
                DateFormat formater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                cell.setCellValue(formater.format(cellValue));
            } else {
                cell.setCellValue("未知類型");
            }
        }
    }

    /**
     * 給指定單元格加邊框,垂直水平居中,宋體8號,不加粗,自動換行
     *
     * @param cell 設置的單元格
     */
    public void setFrameCommon(Cell cell, Workbook wb, Font font) {
        CellStyle xc = wb.createCellStyle();
        xc.setBorderBottom(CellStyle.BORDER_THIN);
        xc.setBorderTop(CellStyle.BORDER_THIN);
        xc.setBorderLeft(CellStyle.BORDER_THIN);
        xc.setBorderRight(CellStyle.BORDER_THIN);
        xc.setAlignment(CellStyle.ALIGN_CENTER);
        xc.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
        xc.setWrapText(true);
        xc.setFont(font);
        cell.setCellStyle(xc);
    }

    /**
     * 通用文件上傳
     *
     * @param file 上傳的文件
     * @param path 上傳的地址
     * @return 上傳的文件本地路徑
     */
    @RequestMapping("importCstm")
    public String importCstm(@RequestParam("file") MultipartFile file, String path) {
        try {
            UploadFile uf = new UploadFile();
            uf.createFolder(path);
            String fileName = uf.uploadFile(file.getInputStream(), file.getOriginalFilename(), path);
            String fileUrl = path + "/" + fileName;
            return fileUrl;
        } catch (Exception e) {
            // 文件上傳異常
            e.printStackTrace();
            return null;
        }
    }

    

    /**
     * 根據相應路徑獲得工作簿
     *
     * @param url 文件路徑
     * @return 工作簿
     */
    public Workbook readExcel(String url) {
        Workbook wb = null;
        String type = url.substring(url.lastIndexOf(".") + 1,
                url.length());
        try (FileInputStream fis = new FileInputStream(url)){
            //判斷文件類型


            if (type.equals("xls")) {
                wb = new HSSFWorkbook(fis);
            } else if (type.equals("xlsx")) {
                wb = new XSSFWorkbook(fis);
            } else {
                wb = null;
            }
        } catch (Exception e) {
            wb = null;
        }
        return wb;
    }

    /**
     * 給指定單元格加邊框,垂直水平居中,宋體8號,加粗,自動換行
     */
    public void setFrameBoldweight(CellStyle cs) {
        cs.setBorderBottom(CellStyle.BORDER_THIN);
        cs.setBorderTop(CellStyle.BORDER_THIN);
        cs.setBorderLeft(CellStyle.BORDER_THIN);
        cs.setBorderRight(CellStyle.BORDER_THIN);
        cs.setAlignment(CellStyle.ALIGN_CENTER);
        cs.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
    }

    /**
     * 給指定單元格加邊框,垂直水平居中,宋體8號,加粗,自動換行
     * @param cell 設置的單元格
     */
    public void setFrameBoldweight(Cell cell, Workbook wb, Font font) {
        CellStyle xc = wb.createCellStyle();
        xc.setBorderBottom(CellStyle.BORDER_THIN);
        xc.setBorderTop(CellStyle.BORDER_THIN);
        xc.setBorderLeft(CellStyle.BORDER_THIN);
        xc.setBorderRight(CellStyle.BORDER_THIN);
        xc.setAlignment(CellStyle.ALIGN_CENTER);
        xc.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
        xc.setWrapText(true);
        font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        xc.setFont(font);
        cell.setCellStyle(xc);
    }


    /**
     * 給指定單元格加左邊框,垂直水平居中,宋體8號,不加粗,自動換行
     */
    public void setFrameCommonOnlyLeft(CellStyle cs) {
        cs.setBorderLeft(CellStyle.BORDER_THIN);
        cs.setBorderRight(CellStyle.BORDER_NONE);
        cs.setBorderBottom(CellStyle.BORDER_NONE);
        cs.setBorderTop(CellStyle.BORDER_NONE);
        cs.setAlignment(CellStyle.ALIGN_CENTER);
        cs.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
    }

    /**
     * 給指定單元格除上、右邊外加邊框,垂直水平居中,宋體8號,不加粗,自動換行
     */
    public void setFrameCommonNoRT(CellStyle cs) {
        cs.setBorderBottom(CellStyle.BORDER_THIN);
        cs.setBorderLeft(CellStyle.BORDER_THIN);
        cs.setBorderTop(CellStyle.BORDER_NONE);
        cs.setBorderRight(CellStyle.BORDER_NONE);
        cs.setAlignment(CellStyle.ALIGN_CENTER);
        cs.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
    }

    /**
     * 給指定單元格除上、左邊外加邊框,垂直水平居中,宋體8號,不加粗,自動換行
     */
    public void setFrameCommonNoLT(CellStyle cs) {
        cs.setBorderBottom(CellStyle.BORDER_THIN);
        cs.setBorderRight(CellStyle.BORDER_THIN);
        cs.setBorderLeft(CellStyle.BORDER_NONE);
        cs.setBorderTop(CellStyle.BORDER_NONE);
        cs.setAlignment(CellStyle.ALIGN_CENTER);
        cs.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
    }

    /**
     * 給指定單元格除右邊外加邊框,垂直水平居中,宋體8號,不加粗,自動換行
     */
    public void setFrameCommonNoRight(CellStyle cs) {
        cs.setBorderBottom(CellStyle.BORDER_THIN);
        cs.setBorderTop(CellStyle.BORDER_THIN);
        cs.setBorderLeft(CellStyle.BORDER_THIN);
        cs.setBorderRight(CellStyle.BORDER_NONE);
        cs.setAlignment(CellStyle.ALIGN_CENTER);
        cs.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
    }

    /**
     * 給指定單元格除左、右邊外加邊框,垂直水平居中,宋體8號,不加粗,自動換行
     */
    public void setFrameCommonNoLR(CellStyle cs) {
        cs.setBorderBottom(CellStyle.BORDER_THIN);
        cs.setBorderTop(CellStyle.BORDER_THIN);
        cs.setBorderLeft(CellStyle.BORDER_NONE);
        cs.setBorderRight(CellStyle.BORDER_NONE);
        cs.setAlignment(CellStyle.ALIGN_CENTER);
        cs.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
    }

    /**
     * 給指定單元格加右邊框,垂直水平居中,宋體8號,不加粗,自動換行
     */
    public void setFrameCommonOnlyRight(CellStyle cs) {
        cs.setBorderRight(CellStyle.BORDER_THIN);
        cs.setBorderLeft(CellStyle.BORDER_NONE);
        cs.setBorderBottom(CellStyle.BORDER_NONE);
        cs.setBorderTop(CellStyle.BORDER_NONE);
        cs.setAlignment(CellStyle.ALIGN_CENTER);
        cs.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
    }

    /**
     * 給指定單元格除左、右邊外加邊框,垂直水平居中,宋體8號,不加粗,自動換行
     * @param cell 設置的單元格
     */
    public void setFrameCommonNoLR(Cell cell, Workbook wb, Font font) {
        CellStyle xc = wb.createCellStyle();
        xc.setBorderBottom(CellStyle.BORDER_THIN);
        xc.setBorderTop(CellStyle.BORDER_THIN);
        xc.setAlignment(CellStyle.ALIGN_CENTER);
        xc.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
        xc.setWrapText(true);
        xc.setFont(font);
        cell.setCellStyle(xc);
    }
    
}

Excel設置圖片

 public Workbook demo( String[] imgs, HttpServletRequest request) {
		Workbook wb = null; 	
		Sheet sheet = null;

        BufferedImage bufferImg = null;
        // 項目目錄
        String classPath = request.getServletContext().getRealPath("");
        // 決裁書模板文件 webapp/
        File file = new File(classPath, "/templet/demo.xls");
		
        HSSFPatriarch patriarch = null;
        try (FileInputStream is = new FileInputStream(file)) {

            wb = new HSSFWorkbook(is);
            sheet = wb.getSheetAt(0);
            // 1、圖片繪製管理器
            patriarch = (HSSFPatriarch) sheet.createDrawingPatriarch();
            ByteArrayOutputStream[] byteArrayOut = new ByteArrayOutputStream[8];
            // 2、圖片位置個數
            HSSFClientAnchor[] anchor = new HSSFClientAnchor[8];
            // 將圖片寫入excel中指定位置
            for (int i = 0; i < imgs.length; i++) {
                if (!"".equals(imgs[i])) {
                    ByteArrayOutputStream byteArrayOut1 = new ByteArrayOutputStream();
                    // 3、讀取圖片
                    bufferImg = ImageIO.read(new File(classPath + imgs[i]));
                    ImageIO.write(bufferImg, "jpg", byteArrayOut1);
                    byteArrayOut[i] = byteArrayOut1;
                    // 4、設置位置
                    anchor[i] = new HSSFClientAnchor(80, 50, 960, 215, (short) i, 3, (short) i, 3);
                    // 5、填充圖片
                    patriarch.createPicture(anchor[i], wb.addPicture(byteArrayOut[i].toByteArray(), HSSFWorkbook.PICTURE_TYPE_PNG));
                    
                } else {
                    byteArrayOut[i] = null;
                    anchor[i] = null;
                }
            }
        

        } catch (Exception e) {
            LOG.warn(e.getMessage());
        }
        return wb;

    }

Excel合併單元格

 		CellRangeAddress cra = new CellRangeAddress(1, 2, 0, 0);
        sheet.addMergedRegion(cra);
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章