gpt4 book ai didi

Java Apache POI 空白单元格

转载 作者:行者123 更新时间:2023-11-30 02:44:40 26 4
gpt4 key购买 nike

我是 Apache POI 新手,但对 Java 并不陌生。我一直在尝试将数据从一个 Excel 文件转换为另一个文件,将任何分隔符数据更改为新单元格。尽管大多数新数据都是正确的,但有一些异常(exception)情况不遵循空白单元格的规则。这是输入文件https://ufile.io/bce15这是输出文件 https://ufile.io/55020

在下图中,记录 4 和记录 5 不按规则进行,我不明白为什么!!

enter image description here

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;


public class testWrite {
public static void main( String [] args ) {
int rowNums = 1;
try {

FileInputStream file = new FileInputStream(new File("ExceptionDataDummy.xlsx"));;
XSSFWorkbook wb = new XSSFWorkbook(file);
XSSFSheet sheet = wb.getSheetAt(0);
String filename = "ExceptionDataResult.xlsx" ;
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet1 = workbook.createSheet("FirstSheet");
Iterator<Row> rows = sheet.rowIterator();
int col = 0;
while( rows.hasNext() ) {
XSSFRow row = (XSSFRow) rows.next();
XSSFRow row1 = sheet1.createRow((short)rowNums);
System.out.println("\n");
Iterator<Cell> cells = row.cellIterator();
while( cells.hasNext() ) {

XSSFCell cell = (XSSFCell) cells.next();
if(XSSFCell.CELL_TYPE_NUMERIC==cell.getCellType()) {
row1.createCell(col).setCellValue(cell.getNumericCellValue());
col++;
}
else
if(XSSFCell.CELL_TYPE_STRING==cell.getCellType()){
String contents = cell.getStringCellValue();
String[] items = contents.split(",");
for (String item : items) {
row1.createCell(col).setCellValue(item);
col++;
}
}
else
if(XSSFCell.CELL_TYPE_BOOLEAN==cell.getCellType()) {
row1.createCell(col).setCellValue(cell.getBooleanCellValue());
col++;
}
else
if((cell.equals("")) || (XSSFCell.CELL_TYPE_BLANK==cell.getCellType()) || (cell == null)) {

cell.setCellType(Cell.CELL_TYPE_BLANK);
col++;
}
else {
System.out.print("Unknown cell type");
}
}
rowNums++;
col=0;
}
FileOutputStream fileOut = new FileOutputStream(filename);
workbook.write(fileOut);
fileOut.close();
System.out.println("Your excel file has been generated!");
wb.close();
workbook.close();
} catch ( IOException ex ) {
ex.printStackTrace();
}
}
}

最佳答案

在您的代码中,您正在使用 cellIterator

Iterator<Cell> cells = row.cellIterator();

cellIterator 不包含空单元格。

您必须从第一个单元格开始循环到最后一个单元格,然后检查单元格是否为 null,而不是使用 cellIterator。

您可以引用下面的示例代码 -

for (int colNum = 0; colNum < row.getLastCellNum(); colNum++) {

Cell cell = row.getCell(colNum, Row.CREATE_NULL_AS_BLANK);
String cellValue = null;

// do whatever you want to do with the cell or its value

}

关于Java Apache POI 空白单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40555849/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com