通过指定列头集合创建EXCEL模板(初始化EXCEL模板为文本格式)
/**
* 根据列头创建Excel模板
*
* @param headList
* @return
*/
public static XSSFWorkbook createWorkBook(List headList) {
XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = wb.createSheet("数据表");
//设置excel为文本格式
XSSFCellStyle cellStyle = wb.createCellStyle();
XSSFDataFormat dataFormat = wb.createDataFormat();
cellStyle.setDataFormat(dataFormat.getFormat("@"));
for(int column=0;column<=headList.size();column++){
sheet.setDefaultColumnStyle(column,cellStyle);
}
buildHeader(sheet, headList);
return wb;
}
/**
* 创建表头
*
* @param sheet
*/
private static void buildHeader(XSSFSheet sheet, List headList) {
XSSFRow headerRow = sheet.createRow(0);
int index = 0;
for (String header : headList) {
XSSFCell cell = headerRow.createCell(index, Cell.CELL_TYPE_STRING);
cell.setCellValue(header);
index++;
}
}
获取当前单元格内容
/**
* 获取当前单元格内容
*/
public static String getCellValue(Cell cell) {
String value = "";
if(cell!=null){
cell.setCellType(Cell.CELL_TYPE_STRING);
value = cell.getStringCellValue();
}
return value;
}
判断某一行的所有单个格是否有值
/**
* 判断某一行的所有单个格是否有值
*
* @param row 当前行
* @param cells 当前行总列数
* @return
*/
private static boolean isThereAValue(XSSFRow row, int cells) {
for (int i = 0; i < cells; i++) {
XSSFCell rowcell = row.getCell(i);
String cellValue = ExcelUtils.getCellValue(rowcell);
if (null != cellValue && !"".equals(cellValue)) {
return true;
}
}
return false;
}
获取EXCEL中不为空行的行数
/**
* 获取excel的不为空的行数
*
* @param sheet
* @param lastRows sheet对应最后一行的编号
* @return
*/
public static int getExcelRows(XSSFSheet sheet, int lastRows) {
boolean isThereAValue;
int rows = 0;
for (int i = 0; i <=lastRows; i++) {
XSSFRow row = sheet.getRow(i);
if (row == null) {
continue;
}
int cells = sheet.getRow(0).getLastCellNum();
isThereAValue = ExcelUtils.isThereAValue(row, cells);
if (!isThereAValue) {
continue;
}
rows++;
}
return rows;
}
获取第一栏标题栏数据
/**
* 获取第一行标题栏数据
*
* @param sheet
* @return map key:标题栏列下标(0开始) value 标题栏值
* @throws ExportException
*/
private static Map loadHeader(XSSFSheet sheet) {
Map header = new HashMap();
int HEADER = 0;
XSSFRow row = sheet.getRow(HEADER);
int columns = row.getLastCellNum();
for (int i = 0; i < columns; i++) {
log.info("加载标题栏:" + row.getCell(i).getStringCellValue());
String value = row.getCell(i).getStringCellValue();
if (null == value) {
throw new RuntimeException("标题栏不能为空!");
}
header.put(i, value);
}
return header;
}
解析EXCEL模板将Workbook中的值放入List
/**
* 将workbook中的值放入List
POI操作EXCEL常见问题
for (int rowIndex = 1; rowIndex <= lastRowNum; rowIndex++
)。