POI实现excel单元格画斜线

时间:2024-03-12 09:16:45

//工具类
public class PoiUtil {

public static final int PERCENT_WIDTH = 50;
public static final int PERCENT_HEIGHT = 20;
public static final float PXTOPT = 0.75f;


// draw cell line

/**
* @param sheet 页签
* @param i 行
* @param j 列
* @param width 单元格宽度
* @param height 单元格高度
*/
public static void drawLine(HSSFSheet sheet, int i, int j, int width, int height) {
int cellWidth = (int) (PERCENT_WIDTH * PXTOPT * width);
short cellHeight = (short) (PERCENT_HEIGHT * PXTOPT * height);
HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
HSSFClientAnchor a = new HSSFClientAnchor(0, 0, 1023, 255, (short) j, i, (short) (j), i);
HSSFShapeGroup group = patriarch.createGroup(a);
float verticalPointsPerPixel = a.getAnchorHeightInPoints(sheet);
EscherGraphics g = new EscherGraphics(group, sheet.getWorkbook(), Color.black,
verticalPointsPerPixel);
EscherGraphics2d g2d = new EscherGraphics2d(g);
int[] xys = {width, height};
for (int l = 0; l < xys.length; l += 2) {
int x = (int) ((PERCENT_WIDTH * 0.75 * xys[l] / cellWidth) * 1023);
int y = (int) ((PERCENT_HEIGHT * 0.75 * xys[l + 1] / cellHeight) * 255);
//g2d.drawLine(0, 0, x, y); 左上右下
g2d.drawLine(0, y, x, 0);
}
}

public static HSSFCellStyle getCellFormat(HSSFWorkbook wb) {
HSSFCellStyle cellStyle = wb.createCellStyle();
if (cellStyle.getBorderBottom() != HSSFCellStyle.BORDER_THIN) {
cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
}
if (cellStyle.getBorderLeft() != HSSFCellStyle.BORDER_THIN) {
cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
}
if (cellStyle.getBorderTop() != HSSFCellStyle.BORDER_THIN) {
cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
}
if (cellStyle.getBorderRight() != HSSFCellStyle.BORDER_THIN) {
cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
}
cellStyle.setBottomBorderColor(createPette(wb));
cellStyle.setLeftBorderColor(createPette(wb));
cellStyle.setRightBorderColor(createPette(wb));
cellStyle.setTopBorderColor(createPette(wb));
return cellStyle;
}

public static short createPette(HSSFWorkbook wb) {
short petteIndex = 0;
Color rgb = new Color(0x00, 0x00, 0x00);
HSSFPalette palette = wb.getCustomPalette();
palette.setColorAtIndex(petteIndex, (byte) rgb.getRed(), (byte) rgb.getGreen(), (byte) rgb
.getBlue());
return petteIndex;
}


//调用地:
//sheet0操作页签,i行号,j列号,cell0当前单元格(通过row0获得),row0当前行(通过sheet0获得)
PoiUtil.drawLine(sheet0, i, j, sheet0.getColumnWidth(cell0.getColumnIndex()), row0.getHeight());

效果: