天天看點

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());
	}
}
           

繼續閱讀