java poi excel合并单元格,如何从Java中使用Apache POI的Excel合并单元格看?

I have a Excel file in .xlsx format. I have stored data by merging cells to form various columns. I am reading the Excel file via a Java web application and saving its data to a database (MySQL). But when I read from merged cells I get null values along with what are stored in the columns as well as the headers. I am using Apache POI. My code is:

public static void excelToDBLogIN() {

FileInputStream file = null;

Boolean flag = true;

ArrayList rows = new ArrayList();

try {

// here uploadFolder contains the path to the Login 3.xlsx file

file = new FileInputStream(new File(uploadFolder + "Login 3.xlsx"));

//Create Workbook instance holding reference to .xlsx file

XSSFWorkbook workbook = new XSSFWorkbook(file);

//Get first/desired sheet from the workbook

XSSFSheet sheet = workbook.getSheetAt(0);

//Iterate through each rows one by one

Iterator rowIterator = sheet.iterator();

while (rowIterator.hasNext()) {

Row row = rowIterator.next();

//For each row, iterate through all the columns

Iterator cellIterator = row.cellIterator();

String tuple = "";

while (cellIterator.hasNext()) {

Cell cell = cellIterator.next();

//Check the cell type and format accordingly

switch (cell.getCellType()) {

case Cell.CELL_TYPE_NUMERIC:

//int value = new BigDecimal(cell.getNumericCellValue()).setScale(0, RoundingMode.HALF_UP).intValue();

//tuple = tuple + String.valueOf(value) + "+";

DataFormatter objDefaultFormat = new DataFormatter();

String str = objDefaultFormat.formatCellValue(cell);

tuple = tuple + str + "+";

break;

case Cell.CELL_TYPE_STRING:

tuple = tuple + cell.getStringCellValue() + "+";

break;

case Cell.CELL_TYPE_BLANK:

tuple = tuple + "" + "+";

break;

}

}

rows.add(tuple);

flag = true;

}

}

} catch (Exception e) {

e.printStackTrace();

} finally {

if (file != null) {

try {

file.close();

file = null;

} catch (Exception e) {

System.out.println("File closing operation failed");

e.printStackTrace();

}

}

}

}

}

I searched for answers in the web but did not find anything relevant.

解决方案

Following code of snippet might help.

while (rowIterator.hasNext()) {

Row row = rowIterator.next();

//For each row, iterate through all the columns

Iterator cellIterator = row.cellIterator();

outer:

while (cellIterator.hasNext()) {

Cell cell = cellIterator.next();

//will iterate over the Merged cells

for (int i = 0; i < sheet.getNumMergedRegions(); i++) {

CellRangeAddress region = sheet.getMergedRegion(i); //Region of merged cells

int colIndex = region.getFirstColumn(); //number of columns merged

int rowNum = region.getFirstRow(); //number of rows merged

//check first cell of the region

if (rowNum == cell.getRowIndex() && colIndex == cell.getColumnIndex()) {

System.out.println(sheet.getRow(rowNum).getCell(colIndex).getStringCellValue());

continue outer;

}

}

//the data in merge cells is always present on the first cell. All other cells(in merged region) are considered blank

if (cell.getCellType() == Cell.CELL_TYPE_BLANK || cell == null) {

continue;

}

System.out.println(cell.getStringCellValue());

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java POI是一个用于操作Microsoft Office格式文件的开源库,在处理Excel文件时可以使用它来实现单元格的合并和数据读取。下面是一个使用Java POI合并单元格并读取数据的示例: 1. 导入Java POI的相关库: ```java import org.apache.poi.ss.usermodel.*; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import java.io.FileInputStream; import java.io.IOException; ``` 2. 定义一个方法来读取Excel文件: ```java public static void readExcel(String filePath) { try { FileInputStream fileInputStream = new FileInputStream(filePath); Workbook workbook = new XSSFWorkbook(fileInputStream); Sheet sheet = workbook.getSheetAt(0); // 循环遍历每一行 for (Row row : sheet) { // 循环遍历每一列 for (Cell cell : row) { // 判断单元格的合并状态 if (cell.getCellType() == CellType.STRING && cell.getCellStyle().getAlignment() == HorizontalAlignment.CENTER) { // 获取合并区域的开始行、结束行、开始列、结束列 int firstRow = sheet.getMergedRegion(cell.getColumnIndex(), cell.getRowIndex()).getFirstRow(); int lastRow = sheet.getMergedRegion(cell.getColumnIndex(), cell.getRowIndex()).getLastRow(); int firstColumn = sheet.getMergedRegion(cell.getColumnIndex(), cell.getRowIndex()).getFirstColumn(); int lastColumn = sheet.getMergedRegion(cell.getColumnIndex(), cell.getRowIndex()).getLastColumn(); // 获取合并区域的数据 String mergedData = sheet.getRow(firstRow).getCell(firstColumn).getStringCellValue(); // 打印合并区域的数据 System.out.println(mergedData); } } } workbook.close(); fileInputStream.close(); } catch (IOException e) { e.printStackTrace(); } } ``` 3. 调用readExcel方法来读取Excel文件: ```java public static void main(String[] args) { readExcel("excelFile.xlsx"); } ``` 以上就是使用Java POI合并单元格并读取数据的一个简单示例。通过判断单元格的合并状态,可以获取到合并区域的数据。根据具体的需求可以进一步处理合并区域的数据。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值