package com.xxx.util;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
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.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.BorderStyle;
public class ExcelUtil {
public static HSSFCellStyle createCellStyle(HSSFWorkbook wb) {
HSSFCellStyle cellStyle = wb.createCellStyle();
cellStyle.setBorderBottom(BorderStyle.THIN); // 底部边框
cellStyle.setBottomBorderColor(HSSFColor.BLACK.index);// 底部边框颜色
// cellStyle.setBorderLeft(BorderStyle.MEDIUM_DASH_DOT_DOT); // 左边框
// cellStyle.setLeftBorderColor(HSSFColor.BLACK.index);// 左边框颜色
cellStyle.setBorderRight(BorderStyle.THIN);
cellStyle.setRightBorderColor(HSSFColor.BLACK.index);// 左边框颜色
// cellStyle.setBorderTop(BorderStyle.MEDIUM_DASH_DOT_DOT);
// cellStyle.setTopBorderColor(HSSFColor.BLACK.index);// 左边框颜色
return cellStyle;
}
/**
* @param sheet
* @param row
* 如果当前行是空行,则创建当前行
* @param i
* @return
*/
public static HSSFRow getNotNullRow(HSSFSheet sheet, int i) {
HSSFRow row = sheet.getRow(i);
if (row == null) {
row = sheet.createRow(i);
}
return row;
}
/**
* @param sheet
* @param row
* 如果当格子是空的,则创建当前格子
* @param i
* @return
*/
public static HSSFCell getNotNullCell(HSSFRow row, int i) {
HSSFCell cell = row.getCell(i);
if (cell == null) {
cell = row.createCell(i);
}
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
return cell;
}
/**
* @param sheet
* @param row
* 如果当格子是空的,则创建当前格子
* @param i
* @return
*/
public static HSSFCell getNotNullCell(HSSFWorkbook wb, HSSFRow row, int i) {
HSSFCell cell = row.getCell(i);
if (cell == null) {
cell = row.createCell(i);
HSSFCellStyle cellStyle = createCellStyle(wb);
cell.setCellStyle(cellStyle);
}
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
return cell;
}
/**
* 获取单元格的值 -不管格子的数据是何类型,自动返回相应的值
*
* @param cell
* @return
*/
public static String getCellValue(HSSFCell cell) {
if (cell == null)
return "";
if (cell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
return cell.getStringCellValue();
} else if (cell.getCellType() == HSSFCell.CELL_TYPE_BOOLEAN) {
return String.valueOf(cell.getBooleanCellValue());
} else if (cell.getCellType() == HSSFCell.CELL_TYPE_FORMULA) {
return cell.getCellFormula();
} else if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
return String.valueOf(cell.getNumericCellValue());
}
return "";
}
/**
* 设置整个sheet每个单元格宽度自适应
*
* @param sheet
* @throws Exception
*/
public static void setAutoWith(HSSFSheet sheet) throws Exception {
int maxColumn = sheet.getPhysicalNumberOfRows();
// 列宽自适应,只对英文和数字有效
for (int i = 0; i <= maxColumn; i++) {
sheet.autoSizeColumn(i);
}
}
}