最近遇到一个需求是需要向excel表格中追加数据,由于报表格式要求需要按列添加,因此需要获得excel表格最后一列值,然后列插入值:
- private static int findRealCloumns(XSSFSheet sheet, int... flag) {
- int realCloumn = 0;
- while (true) {
- // 遍历行数,获取每行的最后一列
- int total = 0;
- for(int j : flag){
- XSSFRow row = sheet.getRow(j);
- if(row != null && row.getCell(realCloumn) != null && row.getCell(realCloumn).getCellType() < 6){
- row.getCell(realCloumn).setCellType(XSSFCell.CELL_TYPE_STRING);
- }
- if (row == null||row.getCell(realCloumn) == null||row.getCell(realCloumn).getStringCellValue().matches("^\\s+$")
- ||row.getCell(realCloumn).getCellType()>2) {
- total++;
- }
- // 如果需要列都是空说明就该返回
- if (total == flag.length) {
- return realCloumn;
- }
- }
- realCloumn++;
- }
- }
获得excel最后一行
- public static int findRealRows(XSSFSheet sheet, int... flag) {
- int rowReal = 0;
- int rows = sheet.getPhysicalNumberOfRows();// 此处物理行数统计有错误,
- for (int i = 0; i < rows; i++) {
- XSSFRow row = sheet.getRow(i);
- int total = 0;
- for(int j : flag){
- // 将所有单元格设置为字符串格式
- if(row != null && row.getCell(j) != null && row.getCell(j).getCellType() < 6){
- row.getCell(j).setCellType(XSSFCell.CELL_TYPE_STRING);
- }
- if (row == null ||row.getCell(j) == null||row.getCell(j).getStringCellValue().matches("^\\s+$")||row.getCell(j).getCellType()>2) {
- total++;
- }
- }
- // 如果需要列都是空说明就该返回
- if (total == flag.length) {
- return rowReal;
- } else {
- rowReal++;
- }
- }
- return rowReal;
- }
总结 :
不论是excel最后一行还是最后一列,首先需要约定一行的前几个单元格内容不能为空或者一列的前几行单元格不能为空,否则判断该行或该列为最后一行或列。