POI处理excel表格中的空数据

1:我在上面有一篇中有使用if判断的方式去处理POI读取到的null的cell,这里介绍一种用try...catch的方法去处理读取到的null的cell的情况,上一篇的链接:https://blog.csdn.net/hujyhfwfh2/article/details/81062120 有兴趣的可以结合一起看... 上一篇有高速大家如何去自动获取excel的行列 这里就不写了 我直接手动传入excel的行数 列数。

package reportFormCompare.Utils;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

/**
 * user给一个excel路径 改程序将读取excel 封装成集合  PS:user需要给出该excel的行列
 */
public class ReadExcelToList {
	
	private String filePath;
	
	public ReadExcelToList(String filePath){
		
		this.filePath = filePath;
	}

	public ArrayList<List> ReadExcel(int rowTotalCount , int columnCount) {

		// int column = 5;//column表示excel的列数

		ArrayList<List> list = new ArrayList<List>();

		try {
			// 建需要读取的excel文件写入stream
			HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(filePath));
			// 指向sheet下标为0的sheet 即第一个sheet 也可以按在sheet的名称来寻找
			HSSFSheet sheet = workbook.getSheetAt(0);
			// 获取sheet1中的总行数
//			int rowTotalCount = sheet.getLastRowNum();
			// 获取总列数
//			int columnCount = sheet.getRow(0).getPhysicalNumberOfCells();

			// System.out.println("行数为:"+rowTotalCount+"列数为:"+columnCount);

			for (int i = 0; i <= rowTotalCount; i++) {
				// 获取第i列的row对象
				HSSFRow row = sheet.getRow(i);

				ArrayList<String> listRow = new ArrayList<String>();

				for (int j = 0; j < columnCount; j++) {
					// 使用try。。。catch的方法对null的cell进行list的组装
					try{
						
						String cell = row.getCell(j).toString();
						listRow.add(cell);
						
					}catch(Exception e){
						listRow.add("");
					}	
					// 在第i列 依次获取第i列的第j个位置上的值 %15s表示前后间隔15个字节输出
				}

				list.add(listRow);

				 System.out.println(list.toString());
			}

		} catch (FileNotFoundException e) {

			e.printStackTrace();
		} catch (IOException e) {

			e.printStackTrace();
		}

		return list;
	}
	
	public static void main(String[] args) {
		
		ReadExcelToList excelToList = new ReadExcelToList("D://345.xls");
		ArrayList<List> arrayList = excelToList.ReadExcel(10, 20);
		System.out.println(arrayList.toString());
	}
}

猜你喜欢

转载自blog.csdn.net/hujyhfwfh2/article/details/81324270