POI操作Excel

POI:Excel中插入图片,解析Excel(poi-3.7-20101029.jar,poi-ooxml-3.7-20101029.jar)
   /**
     * 在Excle2003文档插入条形码
     * 
     * @param fileWordPath
     *            Excel文档绝对路径
     * @param newText
     *            需要插入的条形码图片的绝对路径
     */
    public static boolean insertImage2Excel03(String fileExcelPath,String fileImagePath) {
        FileOutputStream fileOut = null;
        BufferedOutputStream bos = null;
        BufferedImage bufferImg = null;
        ByteArrayOutputStream byteArrayOut = null;
        FileInputStream fis = null;
        HSSFWorkbook wb = null;
        try {
            bufferImg = ImageIO.read(new File(fileImagePath));
            fis = new FileInputStream(new File(fileExcelPath));
            wb = new HSSFWorkbook(fis);
            //遍历该excel下的所有页签
            for (int i = 0; i < wb.getNumberOfSheets(); i++) {
                byteArrayOut = new ByteArrayOutputStream();
                HSSFSheet sheet = wb.getSheetAt(i);
                ImageIO.write(bufferImg, "jpeg", byteArrayOut);//将图像写入outputStream
                sheet.shiftRows(0, sheet.getLastRowNum(), 1, false, false);//获得区域,在第一行上面插入一行
                HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
                //如果第一行不为空
                if (null != sheet.getRow(0)) 
                {
                    //设置第一行高度
                    sheet.getRow(0).setHeightInPoints((float) 65);
                    HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 0, 0,(short) 0, 0, (short)2, 1);//设置条码位置在(0列,0行,1列,1行)
                    HSSFPicture picture = patriarch.createPicture(anchor, wb.addPicture(byteArrayOut.toByteArray(),HSSFWorkbook.PICTURE_TYPE_JPEG));//把jpeg图片通过流写入该sheet1
                    picture.resize();//把图片设置成原始大小
                }
                byteArrayOut.flush();
                byteArrayOut.close();
                byteArrayOut = null;
            }
            fileOut = new FileOutputStream(fileExcelPath);
            bos = new BufferedOutputStream(fileOut);
            wb.write(bos);
            bos.flush();
            bos.close();
        } catch (IOException io) {
            io.printStackTrace();
            return false;
        } finally {
            if (null != byteArrayOut)//关闭byteArrayOut流
                try {
                    byteArrayOut.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            if (null != fis) //关闭fis流
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            if (null != fileOut)//关闭fileOut流
                try {
                    fileOut.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            if (null != bos)//关闭fileOut流
                try {
                    bos.close();
                    bos = null;
                } catch (IOException e) {
                    e.printStackTrace();
                }   
        }
        return true;
    }

/**
*解析Excel03
*/
    public List<List<Map<Integer, DynamicDataEvt>>> readExcel03(String filePath)
    {
        int startRow = 1;// 开始行
        List<List<Map<Integer, DynamicDataEvt>>> content = new ArrayList<List<Map<Integer, DynamicDataEvt>>>();
        HSSFWorkbook workbook = null;
        FileInputStream input = null;
        try
        {
            input = new FileInputStream(new File(filePath));
            workbook = new HSSFWorkbook(input);
        }
        catch (Exception e)
        {
            return null;
        }
        int colsum = 0;
        HSSFSheet sheet = null;
        HSSFRow dataRow = null;
        int sheetnum = workbook.getNumberOfSheets();// 获取页签数
        for (int z = 0; z < sheetnum; z++)// 循环页签
        {
            sheet = workbook.getSheetAt(z);
            if (sheet.getFirstRowNum() == sheet.getLastRowNum())// 如果起止行相等说明页签为空
            {
                continue;
            }
            if ((startRow - 1) >= sheet.getLastRowNum())
            {
                continue;
            }
            List<Map<Integer, DynamicDataEvt>> page = new ArrayList<Map<Integer, DynamicDataEvt>>();
            for (int x = (startRow - 1); x <= sheet.getLastRowNum(); x++)
            {
                dataRow = sheet.getRow(x);
                boolean flag = true;
                int lastcol = 0;
                if (dataRow == null)
                {
                    flag = false;
                    lastcol = colsum;
                }
                else
                {
                    colsum = colsum < dataRow.getLastCellNum() ? dataRow
                            .getLastCellNum() : colsum;
                    lastcol = dataRow.getLastCellNum();
                }
                Map<Integer, DynamicDataEvt> cell = new HashMap<Integer, DynamicDataEvt>();
                for (int y = 0; y < lastcol; y++)
                {
                    DynamicDataEvt dy = new DynamicDataEvt();
                    if (flag)
                    {
                        MergeCellTwoEvt mer = getHSSFCell(sheet, x, y);
                        dy.setValue(retrievalCell03(mer.getHcell()));// 单元格的值
                        dy.setRowNumber(x);// 单元格跨行数
                        dy.setColNumber(y);// 单元格跨列数
                        if (mer.isDelegateCall())
                        {
                            dy.setRowUniteId(mer.getMergedrowSum());
                            dy.setColUniteId(mer.getMergedcolSum());
                        }
                        else
                        {
                            if (mer.isMergedRowSign())
                            {
                                dy.setRowUniteId(-1);

                            }
                            if (mer.isMergedColSign())
                            {
                                dy.setColUniteId(-1);//
                            }
                        }
                    }
                    else
                    {
                        dy.setValue("NULL");
                        dy.setRowNumber(x);
                        dy.setColNumber(y);
                    }
                    dy.setSheetNumber(z);
                    cell.put(y, dy);
                }
                page.add(cell);
            }
            content.add(page);
        }
        return content;
    }

    /**
     * 03单元格解析
     *
     * @param sheet
     * @param x
     * @param y
     * @return
     */
    public MergeCellTwoEvt getHSSFCell(HSSFSheet sheet, int x, int y)
    {
        MergeCellTwoEvt merEvt = new MergeCellTwoEvt();
        for (int numMR = 0; numMR < sheet.getNumMergedRegions(); numMR++)
        {
            CellRangeAddress region = sheet.getMergedRegion(numMR);
            if (region.getFirstRow() <= x && region.getLastRow() >= x
                    && region.getFirstColumn() <= y
                    && region.getLastColumn() >= y)
            {

                if (region.getFirstRow() == x && region.getFirstColumn() == y)
                {
                    merEvt.setHcell(sheet.getRow(x).getCell(y));
                    merEvt.setDelegateCall(true);
                }
                else
                {

                    merEvt.setHcell(sheet.getRow(region.getFirstRow()).getCell(
                            region.getFirstColumn()));
                }

                int info = 0;
                if ((info = region.getLastRow() - region.getFirstRow()) > 0)
                {
                    merEvt.setMergedrowSum(info + 1);
                    merEvt.setMergedRowSign(true);
                }
                if ((info = region.getLastColumn() - region.getFirstColumn()) > 0)
                {
                    merEvt.setMergedcolSum(info + 1);
                    merEvt.setMergedColSign(true);
                }

                break;
            }
            else
            {
                merEvt.setHcell(sheet.getRow(x).getCell(y));
            }
        }

        if (merEvt.getHcell() == null)
        {
            merEvt.setHcell(sheet.getRow(x).getCell(y));
        }

        return merEvt;
    }
/**
*获取单元格的值
*/
    public String retrievalCell03(HSSFCell hcel)
    {
        String dataEvt = "";
        if (null == hcel)
        {
            dataEvt = "NULL";
        }
        // 字符串
        else if (hcel.getCellType() == HSSFCell.CELL_TYPE_STRING)
        {
            dataEvt = (hcel.toString());
        }
        // 公式
        else if (hcel.getCellType() == HSSFCell.CELL_TYPE_FORMULA)
        {
            dataEvt = (getConversionNumber(getCellValue03(hcel)));
        }
        else if (hcel.getCellType() == HSSFCell.CELL_TYPE_NUMERIC)
        {
            if (HSSFDateUtil.isCellDateFormatted(hcel))
            {
                Date date = hcel.getDateCellValue();
                SimpleDateFormat dateFormat = new SimpleDateFormat(
                        "yyyy年MM月dd日");
                dataEvt = (dateFormat.format(date));
            }
            else
            {
                dataEvt = (getConversionNumber(String.valueOf(hcel
                        .getNumericCellValue())));
            }
        }
        else if (hcel.getCellType() == HSSFCell.CELL_TYPE_BLANK)
        {

            dataEvt = "NULL";

        }
        else if (hcel.getCellType() == HSSFCell.CELL_TYPE_ERROR)
        {
            dataEvt = "ERROR";
        }

        return dataEvt;

    }
-------------
还有一个牛人整理的POI使用pdf。借鉴借鉴。

你可能感兴趣的:(java,poi,Excel)