废话不多说
```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
* @param
* 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);
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;
}
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;
}
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;
}
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.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);
}
}
}
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();
List<Point> sencrdPoints = new LinkedList();
for (int j = 0; j <= points.size() - 1; j++) {
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();
}
}
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();
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);
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();
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);
}
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);
}
}
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);
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();
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);
if (font !=null){
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);
}
}
}
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:
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").format(v ) + "%";
} catch (NumberFormatException e) {
}
}
grid.setText(strCell.matches("\\w*\\.0") ? strCell.substring(0, strCell.length() - 2) : strCell);
}
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>