Excel转图片,非截图,画图

废话不多说
```java
package com.ddmc.domain;

import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.xssf.usermodel.XSSFColor;

import java.awt.*;

public class Grid2 {
    private boolean show;
    /** 对应Excel中的row,也可以理解为cells[i][j]的i */
    private int row;
    /** 对应Excel中的col,也可以理解为cells[i][j]的j */
    private int col;
    private int x;
    private int y;
    private int width;
    private int height;
    private String text;
    private Font font;
    //= new Font("微软雅黑", Font.PLAIN, 12);
    private Color bgColor = null;
    private Color ftColor = null;


    public HorizontalAlignment getAlignment() {
        return alignment;
    }

    public void setAlignment(HorizontalAlignment alignment) {
        this.alignment = alignment;
    }

    private HorizontalAlignment alignment=null;



    public int getRow() {
        return row;
    }

    public void setRow(int row) {
        this.row = row;
    }

    public int getCol() {
        return col;
    }

    public void setCol(int col) {
        this.col = col;
    }

    public int getX() {
        return x;
    }

    public void setX(int x) {
        this.x = x;
    }

    public int getY() {
        return y;
    }

    public void setY(int y) {
        this.y = y;
    }

    public boolean isShow() {
        return show;
    }

    public void setShow(boolean show) {
        this.show = show;
    }

    public int getWidth() {
        return width;
    }

    public void setWidth(int width) {
        this.width = width;
    }

    public int getHeight() {
        return height;
    }

    public void setHeight(int height) {
        this.height = height;
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

    public Color getBgColor() {
        return bgColor;
    }

    /**
     * 将poi.ss.usermodel.Color 转换成 java.awt.Color
     * <a href="http://home.cnblogs.com/u/309701/" target="_blank">@param</a>
     * color
     */
    public void setBgColor(org.apache.poi.ss.usermodel.Color color) {
        this.bgColor = poiColor2awtColor(color);
    }

    public void setBgColor(Color color) {
        this.bgColor = color;
    }

    public Color getFtColor() {
        return ftColor;
    }

    public void setFtColor(org.apache.poi.ss.usermodel.Color color) {
        this.ftColor = poiColor2awtColor(color);
    }

    public Font getFont() {
        return font;
    }

    public void setFont(org.apache.poi.ss.usermodel.Font font) {
        if (font != null) {
            this.font = new Font(font.getFontName(), Font.BOLD, font.getFontHeight() / 20 + 2);
        }
    }

    private Color poiColor2awtColor(org.apache.poi.ss.usermodel.Color color) {
        Color awtColor = null;
        // .xlsx
        if (color instanceof XSSFColor) {
            XSSFColor xc = (XSSFColor) color;
            String rgbHex = xc.getARGBHex();
            if (rgbHex != null) {
                awtColor = new Color(Integer.parseInt(rgbHex.substring(2), 16));
            }
        } // .xls
        else if (color instanceof HSSFColor) {
            HSSFColor hc = (HSSFColor) color;
            short[] s = hc.getTriplet();
            if (s != null) {
                awtColor = new Color(s[0], s[1], s[2]);
            }
        }
        return awtColor;
    }
}





```java
package com.ddmc.domain;

import org.apache.poi.ss.usermodel.Cell;

import java.awt.*;

public class UserCell {
    private Cell cell;
    private int row;
    private int col;
    private boolean show;
    private String text="";
    private Color   color=null;

    public Cell getCell() {
        return cell;
    }
    public void setCell(Cell cell) {
        this.cell = cell;
    }
    public int getRow() {
        return row;
    }
    public void setRow(int row) {
        this.row = row;
    }
    public int getCol() {
        return col;
    }
    public void setCol(int col) {
        this.col = col;
    }
    public boolean isShow() {
        return show;
    }
    public void setShow(boolean show) {
        this.show = show;
    }
    public String getText() {
        return text;
    }
    public void setText(String text) {
        this.text = text;
    }

    public Color getColor() {
        return color;
    }
    public void setColor(Color color) {
        this.color = color;
    }
}

package com.ddmc.domain;

import lombok.Data;

@Data
public class Point {
    private int row;
    private int col;
    private String value;

}

package com.ddmc.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ddmc.domain.Point;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.*;

import java.io.*;
import java.util.*;

public class ExcelUtils {

    private static final Logger logger = Logger.getLogger(ExcelUtils.class);

    /**
     * 获取指定的文件XSSFWorkbook对象
     */
    public static XSSFWorkbook getXSSFWorkBook(String filePath) {
        InputStream input = null;
        XSSFWorkbook workbook = null;
        try {
            input = new FileInputStream(filePath);
            workbook = new XSSFWorkbook(input);
        } catch (IOException e) {
            logger.error("【excel文件读取失败!】 [filePath]:" + filePath, e);
        } finally {
            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return workbook;
    }
    public static HSSFWorkbook getHSSFWorkBook(String filePath) {
        InputStream input = null;
        HSSFWorkbook workbook = null;
        try {
            input = new FileInputStream(filePath);
            workbook = new HSSFWorkbook(input);
        } catch (IOException e) {
            logger.error("【excel文件读取失败!】 [filePath]:" + filePath, e);
        } finally {
            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return workbook;
    }

    /*
    获取sheet对象
    */
    public static XSSFSheet getXSSFSheet(XSSFWorkbook workbook, int sheetIndex) {
        XSSFSheet sheet = null;
        if (workbook != null) {
            sheet = workbook.getSheetAt(sheetIndex);
        }
        return sheet;
    }
    public static HSSFSheet getHSSFSheet(HSSFWorkbook workbook, int sheetIndex) {
        HSSFSheet sheet = null;
        if (workbook != null) {
            sheet = workbook.getSheetAt(sheetIndex);
        }
        return sheet;
    }

    /*
    求结束的最大坐标:最大x和最大y
     */
    public static int[] getEndPoint(XSSFSheet sheet) {
        int[] toIndex = new int[2];
        if (sheet != null) {
            int lastRowNum = sheet.getLastRowNum();
            toIndex[0] = lastRowNum ;// 加一 多截一行
            int[] arr = new int[lastRowNum + 1];
            for (int i = 0; i <= lastRowNum; i++) {
                XSSFRow row = sheet.getRow(i);
                if (row != null) {
                    short lastCellNum = row.getLastCellNum();
                    arr[i] = lastCellNum;
                }
            }
            bubb(arr);
            toIndex[1] = arr[arr.length - 1]-1 ;
        }
        return toIndex;
    }
    public static int[] getEndPoint2(HSSFSheet sheet) {
        int[] toIndex = new int[2];
        if (sheet != null) {
            int lastRowNum = sheet.getLastRowNum();
            toIndex[0] = lastRowNum + 1;
            int[] arr = new int[lastRowNum + 1];
            for (int i = 0; i <= lastRowNum; i++) {
                HSSFRow row = sheet.getRow(i);
                if (row != null) {
                    short lastCellNum = row.getLastCellNum();
                    arr[i] = lastCellNum;
                }
            }
            bubb(arr);
            toIndex[1] = arr[arr.length - 1] - 1;
        }
        return toIndex;
    }
   /*
   自动获取传入excel模板的起始位置
   */
    public static int[] getModel(XSSFSheet sheet) {
        int[] toIndex = new int[2];
        if (sheet != null) {
            int firstRowNum = sheet.getFirstRowNum();
            toIndex[0] = firstRowNum;
            int lastRowNum = sheet.getLastRowNum();
            toIndex[1] = lastRowNum+1;
        }
        return toIndex;
    }


    /*
    带有精度
     */
    public static void  setExcelValue(XSSFWorkbook xssWorkbook, XSSFCell cell, String value, int color, int size,int groundColor) {
        XSSFCellStyle cellStyle = xssWorkbook.createCellStyle();
        Font font = xssWorkbook.createFont();
        font.setFontName("微软雅黑");
        if (color != 0) {
            font.setColor((short) color);
        }
        if (size != 0) {
            font.setFontHeightInPoints((short) size);//设置字体大小
        }
        cellStyle.setFont(font);
        if (groundColor != 0) {
            cellStyle.setFillForegroundColor((short) groundColor);// 设置背景色
            cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        }
        cellStyle.setAlignment(HorizontalAlignment.CENTER);
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        cellStyle.setBorderBottom(BorderStyle.THIN); //下边框
        cellStyle.setBorderLeft(BorderStyle.THIN);//左边框
        cellStyle.setBorderTop(BorderStyle.THIN);//上边框
        cellStyle.setBorderRight(BorderStyle.THIN);//右边框
        if (value != null&&value !="") {
            if (isNumeric(value) == true) {
                if (value.contains(".")) {
                    double v = Double.parseDouble(String.valueOf(value));
                    cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("0.00"));
                    if (v > 9999999) {
                        cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat(("0.00E+00")));
                    }
                    cell.setCellValue(v);
                    cell.setCellStyle(cellStyle);
                } else {
                    double v = Double.parseDouble(String.valueOf(value));
                    cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("0"));
                    if (v > 9999999) {
                        cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat(("0.00E+00")));
                    }
                    cell.setCellValue(v);
                    cell.setCellStyle(cellStyle);
                }

//            } else if (value.substring(value.length() - 1, value.length()).equals("%")) {
            } else if (value.contains("%")) {
                String substring = value.substring(0, value.length() - 1);
                boolean numeric = isNumeric(substring);
                if (numeric == true) {
                    double v = Double.parseDouble(substring) / 100;
                    cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("0.00%"));
                    cell.setCellValue(v);
                    cell.setCellStyle(cellStyle);
                } else {
                    cell.setCellValue(value);
                    cell.setCellStyle(cellStyle);
                }
            } else {
                cell.setCellValue(value);
                cell.setCellStyle(cellStyle);
            }
        }
    }
    /*
    冒泡排序:最大的值为:arr[arr.length-1]-1
     */
    public static void bubb(int[] arr) {
        for (int i = 0; i < arr.length - 1; i++) {
            for (int j = 0; j < arr.length - 1 - i; j++) {
                if (arr[j] > arr[j + 1]) {
                    arr[j] = arr[j] ^ arr[j + 1];
                    arr[j + 1] = arr[j] ^ arr[j + 1];
                    arr[j] = arr[j] ^ arr[j + 1];
                }
            }
        }
    }
    public final static boolean isNumeric(String str){
        if (str != null && !"".equals(str.trim())){
            if (str.substring(0,1).equals("-")||str.substring(0,1).equals("+")){
                str=str.substring(1,str.length());
            }
            return str.replace(".","").matches("^[0-9]*$");
        }
        else{
            return false;
        }
    }
    /*
    合并单元格
     */
    public void addMergedRegion(XSSFSheet sheet, int rowIndex, int rowEnd, int firstCol, int lastCol){
        if (rowIndex <= rowEnd&&firstCol<=lastCol){
            sheet.addMergedRegion(new CellRangeAddress(rowIndex, rowEnd, firstCol, lastCol));
        }
    }

    public String getStringValue(XSSFSheet sheet, int row, int cell){
        String value="";
        XSSFRow rowValue = sheet.getRow(row);
        XSSFCell cellVale = rowValue.getCell(cell);
        if (cellVale !=null){
            value=cellVale.toString();
        }
        return value;
    }

    /*
     自动合并单元格
     先获取合并单元格的坐标
     再进行合并单元格
     */
    public void  getMergedRegion(XSSFSheet sheet,List<Point> points){
        Set<String> set=new HashSet();
        Iterator<Point> iterator = points.iterator();
        while (iterator.hasNext()){
            set.add(iterator.next().getValue());
        }
        List<List<Point>>  bigList=new LinkedList<>();
        Object[] arr =  set.toArray();

        for (int i = 0; i <= arr.length - 1; i++) {
            String valueSet = arr[i].toString();// 5
            List<Point> sencrdPoints = new LinkedList();
            for (int j = 0; j <= points.size() - 1; j++) {//5
                String valueMap = points.get(j).getValue();
                if (valueMap.equals(valueSet)) {
                    sencrdPoints.add(points.get(j));
                }
            }
            bigList.add(sencrdPoints);
        }
        Iterator<List<Point>> iterator1 = bigList.iterator();
        while (iterator1.hasNext()){
            List<Point> next = iterator1.next();
            if(next.size()>=2){
                int fistRow = next.get(0).getRow();
                int fistCol = next.get(0).getCol();
                int lastRow = next.get(next.size()-1).getRow();
                int lastCol = next.get(next.size()-1).getCol();
                addMergedRegion(sheet,fistRow,lastRow,fistCol,lastCol);
            }
        }
    }


    public void writeExcel(XSSFWorkbook xssWorkbook, String outPutPath){
        File xlsFile = new File(outPutPath);
        FileOutputStream xlsStream = null;
        try {
            xlsStream = new FileOutputStream(xlsFile);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        try {
            xssWorkbook.write(xlsStream);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /*
    获取split value
    后期改为Json value,不需要split
     */
    public String getSplitValue(Object value,int row,int col,List<Point> points){
        String s="";
        if (value!=null){
            if (value.toString().contains("_MERGE")){
                String splitValue = value.toString().split("_MERGE")[0];
                Point point=new Point();
                point.setCol(col);
                point.setRow(row);
                point.setValue(splitValue);
                points.add(point);
                s=splitValue;
            }else {
                s=value.toString();
            }
        }
        return s;
    }

    public String getJsonValue(Object value,int row,int col,List<Point> points){
        String s="";
        if (value!=null){
            String string = value.toString();
            JSONObject jsonObject = JSON.parseObject(string);
            Object value1 = jsonObject.get("value");
            if (value1!=null){
                s = value1.toString();
            }
            if (jsonObject.get("mege").equals(true)) {
                Point point = new Point();
                point.setCol(col);
                point.setRow(row);
                point.setValue(s);
                points.add(point);
            }
        }
        return s;
    }


    public Integer getJsonSize(Object value,int row,int col,List<Point> points){
        String s="0";
        if (value!=null){
            String string = value.toString();
            JSONObject jsonObject = JSON.parseObject(string);
            Object value1 = jsonObject.get("size");
            if (value1!=null){
                s = value1.toString();
            }
        }
        return Integer.parseInt(s);
    }

    public Integer getJsonColor(Object value,int row,int col,List<Point> points){
        String s="0";
        if (value!=null){
            String string = value.toString();
            JSONObject jsonObject = JSON.parseObject(string);
            Object value1 = jsonObject.get("color");
            if (value1!=null){
                s = value1.toString();
            }
        }
        return Integer.parseInt(s);
    }

    public Integer getJsonGroundColor(Object value,int row,int col,List<Point> points){
        String s="0";
        if (value!=null){
            String string = value.toString();
            JSONObject jsonObject = JSON.parseObject(string);
            Object value1 = jsonObject.get("gtoundColor");
            if (value1!=null){
                s = value1.toString();
            }
        }
        return Integer.parseInt(s);
    }

}
package com.ddmc.service;

import com.ddmc.domain.Grid2;
import com.ddmc.domain.UserCell;
import com.ddmc.utils.ExcelUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

public class Excel2PngMainString2 {

    private static final Logger logger = Logger.getLogger(Excel2PngMainString2.class);
    public static void main(String[] args) {
        ExcelUtils excelUtils=new ExcelUtils();

//        if(args[0].contains(".xlsx")){
//            XSSFWorkbook xssfWorkBook =excelUtils.getXSSFWorkBook(args[0]);
//            XSSFSheet xssfSheet = excelUtils.getXSSFSheet(xssfWorkBook,0);
//            int[] fromIndex=new int[2];
//            fromIndex[0]=0;
//            fromIndex[1]=0;
//            int[] toIndex = excelUtils.getEndPoint(xssfSheet);
//            doDraw(xssfSheet,fromIndex,toIndex,args[1]);
//        }else if(args[0].contains(".xls")) {
//            HSSFWorkbook hssfWorkBook =excelUtils.getHSSFWorkBook(args[0]);
//            HSSFSheet hssfSheet = excelUtils.getHSSFSheet(hssfWorkBook,0);
//            int[] fromIndex=new int[2];
//            fromIndex[0]=0;
//            fromIndex[1]=0;
//            int[] toIndex = excelUtils.getEndPoint2(hssfSheet);
//            doDraw2(hssfSheet,fromIndex,toIndex,args[1],hssfWorkBook);
//        }else {
//            System.out.println("输入的excel文件不是.xls和.xlsx类型");
//        }
        XSSFWorkbook xssfWorkBook =excelUtils.getXSSFWorkBook("e:/xy3.xlsx");
        XSSFSheet xssfSheet = excelUtils.getXSSFSheet(xssfWorkBook,0);
        int[] fromIndex=new int[2];
        fromIndex[0]=0;
        fromIndex[1]=0;
        int[] toIndex = excelUtils.getEndPoint(xssfSheet);
        doDraw(xssfSheet,fromIndex,toIndex,"e:/111111111111.png");
        }


    public static void doDraw(XSSFSheet sheet,int[] fromIndex, int[] toIndex,String imagePath){
        //图片宽度
        int imageWidth = 0;
        //图片高度
        int imageHeight = 0;

        //根据指定区域,动态获得输出总行列数
        int totalRow = toIndex[0] - fromIndex[0] + 1;
        int totalCol = toIndex[1] - fromIndex[1] + 1;

        //起始行列号
        int startRowNum = fromIndex[0];
        int startColNum = fromIndex[1];

        //创建单元格数组,用于遍历单元格
        UserCell[][] cells = new UserCell[totalRow + 1][totalCol + 1];
        // 存放行绘图边界
        int[] rowPixPos = new int[totalRow + 1];
        rowPixPos[0] = 0;
        // 存放列绘图边界
        int[] colPixPos = new int[totalCol + 1];
        colPixPos[0] = 0;
        //开始遍历单元格
        for (int i =0 ; i < totalRow; i++) {
            int rowNum = startRowNum + i;
            for (int j = 0; j < totalCol; j++) {
                int colNum = startColNum + j;
                XSSFCell cell = null;
                try {
                    cell = sheet.getRow(rowNum).getCell(colNum);
                }catch (NullPointerException e){
                    cell = sheet.createRow(rowNum).createCell(colNum);
                }
                cells[i][j] = new UserCell();
                cells[i][j].setCell(cell);
                cells[i][j].setRow(rowNum);
                cells[i][j].setCol(colNum);
                boolean ifShow = !(sheet.isColumnHidden(colNum) || sheet.getRow(rowNum).getZeroHeight());
                cells[i][j].setShow(ifShow);
                // 计算所求区域宽度
                // 如果该单元格是隐藏的,则置宽度为0
                float widthPix = !ifShow ? 0 : (sheet.getColumnWidthInPixels(colNum));
                if (i == 0) {
                    imageWidth += widthPix;
                }
                colPixPos[j + 1] = (int) (widthPix * 1.15 + colPixPos[j]);
            }
            // 计算所求区域高度
            // 行序列在指定区域中间
            boolean ifShow = (i >= 0);
            // 行序列不能隐藏
            ifShow = ifShow && !sheet.getRow(rowNum).getZeroHeight();
            // 如果该单元格是隐藏的,则置高度为0
            float heightPoint = !ifShow ? 0 : (sheet.getRow(rowNum).getHeightInPoints());
            imageHeight += heightPoint;
            rowPixPos[i + 1] = (int) (heightPoint * 96 / 72) + rowPixPos[i];
        }
        imageHeight = imageHeight * 96 / 72;
        imageWidth = imageWidth * 115 / 100;

        //获取栅格化单元格对象集合
        List<Grid2> grids =
                getGrids(totalRow, totalCol, rowPixPos, colPixPos, cells, sheet.getMergedRegions());
        //生成图片,并保存
        generateImageByGraphics2D(imageWidth,imageHeight,imagePath,grids);
    }


    /**
     *  通过java2d生成图片,并保存
     * @param imageWidth
     * @param imageHeight
     * @param imagePath
     * @param grids
     */
    private static void generateImageByGraphics2D(int imageWidth,int imageHeight,String imagePath,List<Grid2> grids){
        BufferedImage image = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d = image.createGraphics();

        g2d.setColor(Color.white);

        g2d.fillRect(0, 0, imageWidth, imageHeight);
        // 平滑字体
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_NORMALIZE);
        g2d.setRenderingHint(RenderingHints.KEY_TEXT_LCD_CONTRAST, 140);
        g2d.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
        g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        // 绘制表格
        for (Grid2 g : grids) {

            if (!g.isShow()) {
                continue;
            }

            // 绘制背景色
            g2d.setColor(g.getBgColor() == null ? Color.white : g.getBgColor());
            g2d.fillRect(g.getX(), g.getY(), g.getWidth(), g.getHeight());

            // 绘制边框
            g2d.setColor(Color.black);
            g2d.setStroke(new BasicStroke(1));
            g2d.drawRect(g.getX(), g.getY(), g.getWidth(), g.getHeight());

            // 绘制文字,居中显示
            Color ftColor = g.getFtColor();
            g2d.setColor(ftColor);

            Font font = g.getFont();
            if (font !=null){
                if (!font.getFamily().contains("微软雅黑")||!font.getFamily().contains("宋体") ){
                    font = new Font("微软雅黑", Font.PLAIN, font.getSize());
                }
            }
            if (font == null ) {
                continue;
            }
            FontMetrics fm = g2d.getFontMetrics(font);
            // 获取将要绘制的文字宽度
            String str = g.getText() == null ? " " : g.getText();
            int strWidth = fm.stringWidth(str);
            g2d.setFont(font);
            if (g.getAlignment().toString().equals("JUSTIFY")||g.getAlignment().toString().equals("LEFT")){
                if (str.contains("\n")){
                    String[] split = str.split("\n");
                    int size = font.getSize();
                    int yy = g.getY() ;
                    for(int i=0;i<=split.length-1;i++){
                        g2d.drawString(split[i],
                                0,yy+size*(i+1));
                    }

                }else {
                    g2d.drawString(str,
                            0, g.getY() + (g.getHeight() - font.getSize()) / 2 + font.getSize());
                }

            }else {
                if (str.contains("\n")){
                    String[] split = str.split("\n");
                    int size = font.getSize();
                    int yy = g.getY() ;
                    for(int i=0;i<=split.length-1;i++){
                        g2d.drawString(split[i],
                                g.getX() + (g.getWidth() - strWidth) / 2,
                                yy+size*(i+1));
                    }

                }else {
                    g2d.drawString(str,
                            g.getX() + (g.getWidth() - strWidth) / 2,
                            g.getY() + (g.getHeight() - font.getSize()) / 2 + font.getSize());
                }


            }

        }
        //表格最后一行有可能不显示,手动画上一行
        g2d.drawLine(0, imageHeight - 1, imageWidth - 4, imageHeight - 1);

        g2d.dispose();
        try {
            imagePath = StringUtils.isNotBlank(imagePath) ? imagePath:"default.png";
            ImageIO.write(image, "png", new File(imagePath));
            logger.info("生成PNG: [" + imagePath + "] Success!");
        } catch (IOException e) {
            logger.error("【图片写出失败!】 "+imagePath,e);
        }
    }


    /**
     * 判断Excel中的单元格是否为合并单元格
     *
     * @param row
     * @param col
     * @param rangeAddress
     * @return 如果不是合并单元格返回{-1,-1},如果是合并单元格并且是一个单元格返回{lastRow,lastCol},
     *         如果是合并单元格并且不是第一个格子返回{0,0}
     */
    private static int[] isInMerged(int row, int col, List<CellRangeAddress> rangeAddress) {
        int[] isInMergedStatus = { -1, -1 };
        for (CellRangeAddress cra : rangeAddress) {
            if (row == cra.getFirstRow() && col == cra.getFirstColumn()) {
                isInMergedStatus[0] = cra.getLastRow();
                isInMergedStatus[1] = cra.getLastColumn();
                return isInMergedStatus;
            }
            if (row >= cra.getFirstRow() && row <= cra.getLastRow()) {
                if (col >= cra.getFirstColumn() && col <= cra.getLastColumn()) {
                    isInMergedStatus[0] = 0;
                    isInMergedStatus[1] = 0;
                    return isInMergedStatus;
                }
            }
        }
        return isInMergedStatus;
    }

    private static List<Grid2> getGrids(int totalRow, int totalCol, int[] rowPixPos, int[] colPixPos, UserCell[][] cells, List<CellRangeAddress> rangeAddress) {
        List<Grid2> grids = new ArrayList<Grid2>();
        for (int i = 0; i < totalRow; i++) {
            for (int j = 0; j < totalCol; j++) {
                Grid2 grid = new Grid2();
                // 设置坐标和宽高
                grid.setX(colPixPos[j]);
                grid.setY(rowPixPos[i]);
                grid.setWidth(colPixPos[j + 1] - colPixPos[j]);

                grid.setHeight(rowPixPos[i + 1] - rowPixPos[i]);
                grid.setRow(cells[i][j].getRow());
                grid.setCol(cells[i][j].getCol());
                grid.setShow(cells[i][j].isShow());

                // 判断是否为合并单元格
                int[] isInMergedStatus = isInMerged(grid.getRow(), grid.getCol(), rangeAddress);
                if (isInMergedStatus[0] == 0 && isInMergedStatus[1] == 0) {
                    // 此单元格是合并单元格,并且不是第一个单元格,需要跳过本次循环,不进行绘制
                    continue;
                } else if (isInMergedStatus[0] != -1 && isInMergedStatus[1] != -1) {
                    // 此单元格是合并单元格,并且属于第一个单元格,则需要调整网格大小
                    int lastRowPos = isInMergedStatus[0] > totalRow - 1 ? totalRow - 1 : isInMergedStatus[0];
                    int lastColPos = isInMergedStatus[1] > totalCol - 1 ? totalCol - 1 : isInMergedStatus[1];
                    grid.setWidth(colPixPos[lastColPos + 1] - colPixPos[j]);
                    grid.setHeight(rowPixPos[lastRowPos + 1] - rowPixPos[i]);

                }
                // 单元格背景颜色
                XSSFCell cell = (XSSFCell) cells[i][j].getCell();
                if (cell != null) {
                    XSSFCellStyle cs = cell.getCellStyle();
                    grid.setBgColor(cs.getFillForegroundColorColor());

                    HorizontalAlignment alignment = cell.getCellStyle().getAlignment();
                    grid.setAlignment(alignment);


                    // 设置字体
                    org.apache.poi.ss.usermodel.Font font = cs.getFont();

                    grid.setFont(font);
                    // 设置前景色
                    grid.setFtColor(cs.getFont().getXSSFColor());
                    // 设置文本
                    String strCell;
                    CellType cellType = cell.getCellTypeEnum();
                    switch (cellType) {
                        case STRING:
                            strCell = cell.getStringCellValue();
                            break;
                        case NUMERIC:
                            double numericCellValue = cell.getNumericCellValue();
                            Double v = (double) Math.round(numericCellValue * 100) / 100;
                            strCell = String.valueOf(v.toString()+"");
                            if (strCell.contains("E")){
                                strCell=new BigDecimal(strCell).toString();
                            }
                            break;
                        case BLANK:
                            strCell = "";
                            break;
                        case FORMULA:
                            try {
                                strCell = String.valueOf(cell.getNumericCellValue()+"");
                            } catch (IllegalStateException e) {
                                strCell = String.valueOf(cell.getRichStringCellValue()+"");
                            }
                            break;
                        default:
                            strCell = "";
                            break;
                    }
                    if (cs.getDataFormatString().contains("%")) {
                        try {
                            double numericCellValue = cell.getNumericCellValue();
                            double v = (double) Math.round(numericCellValue * 10000) / 100;
                            strCell = new DecimalFormat( "0.00").format(v) + "%";
                        } catch (NumberFormatException e) {
                        }
                    }
                        grid.setText(strCell.matches("\\w*\\.0") ? strCell.substring(0, strCell.length() - 2) : strCell);

                }
                grids.add(grid);
            }
        }
        return grids;
    }


    public static void doDraw2(HSSFSheet sheet,int[] fromIndex, int[] toIndex,String imagePath,HSSFWorkbook wb){
        //图片宽度
        int imageWidth = 0;
        //图片高度
        int imageHeight = 0;

        //根据指定区域,动态获得输出总行列数
        int totalRow = toIndex[0] - fromIndex[0] + 1;
        int totalCol = toIndex[1] - fromIndex[1] + 1;

        //起始行列号
        int startRowNum = fromIndex[0];
        int startColNum = fromIndex[1];

        //创建单元格数组,用于遍历单元格
        UserCell[][] cells = new UserCell[totalRow + 1][totalCol + 1];
        // 存放行绘图边界
        int[] rowPixPos = new int[totalRow + 1];
        rowPixPos[0] = 0;
        // 存放列绘图边界
        int[] colPixPos = new int[totalCol + 1];
        colPixPos[0] = 0;
        //开始遍历单元格
        for (int i =0 ; i < totalRow; i++) {
            int rowNum = startRowNum + i;
            for (int j = 0; j < totalCol; j++) {
                int colNum = startColNum + j;
                HSSFCell cell = null;
                try {
                    cell = sheet.getRow(rowNum).getCell(colNum);
                }catch (NullPointerException e){
                    cell = sheet.createRow(rowNum).createCell(colNum);
                }
                cells[i][j] = new UserCell();
                cells[i][j].setCell(cell);
                cells[i][j].setRow(rowNum);
                cells[i][j].setCol(colNum);
                boolean ifShow = !(sheet.isColumnHidden(colNum) || sheet.getRow(rowNum).getZeroHeight());
                cells[i][j].setShow(ifShow);
                // 计算所求区域宽度
                // 如果该单元格是隐藏的,则置宽度为0
                float widthPix = !ifShow ? 0 : (sheet.getColumnWidthInPixels(colNum));
                if (i == 0) {
                    imageWidth += widthPix;
                }
                colPixPos[j + 1] = (int) (widthPix * 1.15 + colPixPos[j]);
            }
            // 计算所求区域高度
            // 行序列在指定区域中间
            boolean ifShow = (i >= 0);
            // 行序列不能隐藏
            ifShow = ifShow && !sheet.getRow(rowNum).getZeroHeight();
            // 如果该单元格是隐藏的,则置高度为0
            float heightPoint = !ifShow ? 0 : (sheet.getRow(rowNum).getHeightInPoints());
            imageHeight += heightPoint;
            rowPixPos[i + 1] = (int) (heightPoint * 96 / 72) + rowPixPos[i];
        }
        imageHeight = imageHeight * 96 / 72;
        imageWidth = imageWidth * 115 / 100;

        //获取栅格化单元格对象集合
        List<Grid2> grids = getGrids2(totalRow, totalCol, rowPixPos, colPixPos, cells, sheet.getMergedRegions(),wb);
        //生成图片,并保存
        generateImageByGraphics2D(imageWidth,imageHeight,imagePath,grids);
    }

    private static List<Grid2> getGrids2(int totalRow, int totalCol, int[] rowPixPos, int[] colPixPos, UserCell[][] cells, List<CellRangeAddress> rangeAddress,HSSFWorkbook wb) {
        List<Grid2> grids = new ArrayList<Grid2>();
        for (int i = 0; i < totalRow; i++) {
            for (int j = 0; j < totalCol; j++) {
                Grid2 grid = new Grid2();
                // 设置坐标和宽高
                grid.setX(colPixPos[j]);
                grid.setY(rowPixPos[i]);
                grid.setWidth(colPixPos[j + 1] - colPixPos[j]);

                grid.setHeight(rowPixPos[i + 1] - rowPixPos[i]);
                grid.setRow(cells[i][j].getRow());
                grid.setCol(cells[i][j].getCol());
                grid.setShow(cells[i][j].isShow());

                // 判断是否为合并单元格
                int[] isInMergedStatus = isInMerged(grid.getRow(), grid.getCol(), rangeAddress);
                if (isInMergedStatus[0] == 0 && isInMergedStatus[1] == 0) {
                    // 此单元格是合并单元格,并且不是第一个单元格,需要跳过本次循环,不进行绘制
                    continue;
                } else if (isInMergedStatus[0] != -1 && isInMergedStatus[1] != -1) {
                    // 此单元格是合并单元格,并且属于第一个单元格,则需要调整网格大小
                    int lastRowPos = isInMergedStatus[0] > totalRow - 1 ? totalRow - 1 : isInMergedStatus[0];
                    int lastColPos = isInMergedStatus[1] > totalCol - 1 ? totalCol - 1 : isInMergedStatus[1];
                    grid.setWidth(colPixPos[lastColPos + 1] - colPixPos[j]);
                    grid.setHeight(rowPixPos[lastRowPos + 1] - rowPixPos[i]);

                }
                // 单元格背景颜色
                HSSFCell cell = (HSSFCell) cells[i][j].getCell();
                if (cell != null) {
                    HSSFCellStyle cs = cell.getCellStyle();

                    HorizontalAlignment alignment = cell.getCellStyle().getAlignment();
                    grid.setAlignment(alignment);
                    org.apache.poi.ss.usermodel.Font font = cs.getFont(wb);
//                    System.out.println(font.getColor());
                    if (font !=null){
//                        System.out.println(font.getFontName());
                        if (!font.getFontName().contains("宋体")|| !font.getFontName().contains("微软雅黑")){
                            font.setFontName("微软雅黑");
                            if (font.getColor()<=10){
                                font.setColor((short) 10);
                            }else if (font.getColor()<=60 && font.getColor()>=50){
                                font.setColor((short) 57);
                            }
                        }
                    }
                    // 设置字体
//                    org.apache.poi.ss.usermodel.Font font = cs.getFont(wb);
                    grid.setFont(font);

                    // 设置前景色
                    grid.setFtColor(cs.getFont(wb).getHSSFColor(wb));
                    // 设置文本
                    String strCell;
                    CellType cellType = cell.getCellTypeEnum();
                    switch (cellType) {
                        case STRING:
                            strCell = cell.getStringCellValue();
                            break;
                        case NUMERIC:
//                            strCell = String.valueOf(cell.getNumericCellValue());
                            double numericCellValue = cell.getNumericCellValue();
//                            System.out.println(numericCellValue);
                            Double v = (double) Math.round(numericCellValue * 100) / 100;
//                            strCell = new BigDecimal(v).toString();
                            strCell = String.valueOf(v.toString()+"");
                            if (strCell.contains("E")){
                                strCell=new BigDecimal(strCell).toString();
                            }
//                            System.out.println(strCell);
                            break;
                        case BLANK:
                            strCell = "";
                            break;
                        case FORMULA:
                            try {
                                strCell = String.valueOf(cell.getNumericCellValue());
                            } catch (IllegalStateException e) {
                                strCell = String.valueOf(cell.getRichStringCellValue());
                            }
                            break;
                        default:
                            strCell = "";
                            break;
                    }
                    if (cs.getDataFormatString().contains("%")) {
                        try {
                            double numericCellValue = cell.getNumericCellValue();
                            double v = (double) Math.round(numericCellValue * 10000) / 100;
                            strCell = new DecimalFormat( "0").format(v ) + "%";
                        } catch (NumberFormatException e) {
                        }
                    }
                    grid.setText(strCell.matches("\\w*\\.0") ? strCell.substring(0, strCell.length() - 2) : strCell);
//                    System.out.println(grid.getText());
                }
                grids.add(grid);

            }
        }
        return grids;
    }

}


<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.ddmc</groupId>
    <artifactId>Excel2Png</artifactId>
    <version>1.0-SNAPSHOT</version>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
        <skipTests>true</skipTests>
    </properties>

    <repositories>
        <repository>
            <id>cloudera</id>
            <url>https://repository.cloudera.com/artifactory/cloudera-repos</url>
        </repository>
    </repositories>

    <dependencies>



        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>4.1.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>4.1.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml-schemas</artifactId>
            <version>4.1.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-scratchpad</artifactId>
            <version>4.1.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.9</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.10</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.46</version>
        </dependency>

        <dependency>
            <groupId>org.apache.hadoop</groupId>
            <artifactId>hadoop-common</artifactId>
            <version>2.6.0</version>
        </dependency>

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
            <version>2.6.2</version>
        </dependency>

        <dependency>
            <groupId>commons-httpclient</groupId>
            <artifactId>commons-httpclient</artifactId>
            <version>3.1</version>
        </dependency>

        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.1</version>
        </dependency>


        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.4</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>2.10.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.10.0</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.10</version>
        </dependency>


    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>${java.version}</source>
                    <target>${java.version}</target>
                    <encoding>${project.build.sourceEncoding}</encoding>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-assembly-plugin</artifactId>
                <configuration>
                    <descriptorRefs>
                        <descriptorRef>jar-with-dependencies</descriptorRef>
                    </descriptorRefs>
                    <archive>
                        <manifest>
                            <mainClass>com.ddmc.service.Excel2PngMain</mainClass>
                        </manifest>
                        <manifest>
                            <mainClass>com.ddmc.service.Excel2PngMainString</mainClass>
                        </manifest>
                        <manifest>
                            <mainClass>com.ddmc.service.Excel2PngMainString2</mainClass>
                        </manifest>
                        <manifest>
                            <mainClass>com.ddmc.service.SendMessageMain</mainClass>
                        </manifest>
                    </archive>
                </configuration>
                <executions>
                    <execution>
                        <id>make-assembly</id>
                        <phase>package</phase>
                        <goals>
                            <goal>single</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值