通用的Java读取Excel文件(POI)


import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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;

public class CommonReadExcel {

	public void readExcel(String filePath) throws Exception {
		Map<String, String> map = new HashMap<String, String>();
		String value = "";
		HSSFWorkbook wookbook = new HSSFWorkbook(new FileInputStream(filePath));
		HSSFSheet sheet = wookbook.getSheetAt(0);
		int rows = sheet.getPhysicalNumberOfRows();// hang
		int max_cells = 0;// 列
		// 获取最长的列,在实践中发现如果列中间有空值的话,那么读到空值的地方就停止了。所以我们需要取得最长的列
		for (int i = 0; i < rows; i++) {
			HSSFRow row = sheet.getRow(i);
			if (row != null) {
				int cells = row.getPhysicalNumberOfCells();
				if (max_cells < cells) {
					max_cells = cells;
				}
			}
		}
		for (int i = 1; i < rows; i++) {
			HSSFRow row = sheet.getRow(i);
			if (row != null) {
				// 遍历列
				for (int j = 0; j < max_cells; j++) {
					HSSFCell cell = row.getCell(j);
					if (cell == null) {
						value += "NULL,";
					}else{
//判断单元格的类型
						switch(cell.getCellType()){
					case(HSSFCell.CELL_TYPE_NUMERIC):
						value = value + cell.getNumericCellValue() + ",";
						break;
					case(HSSFCell.CELL_TYPE_FORMULA)://公式
						try{
						value = value + cell.getNumericCellValue() + ",";//	cell.getCellFormula()
						}catch(Exception e ){
						value = value + cell.getRichStringCellValue() + ",";
						}
						break;
					case(HSSFCell.CELL_TYPE_STRING):
						value = value + cell.getStringCellValue() + ",";
						break;
					}
					}
						
				}
			}
		}	
		String[] k = value.split(",");
		for (String string : k) {
			System.out.println(string);
		}
	}
	public static void main(String[] args) throws Exception {
		CommonReadExcel cre = new CommonReadExcel();
		cre.readExcel("C:\\Users\\Administrator.WINDOWS-VK1LA9F\\Desktop\\04接卫宁.xls");
		
	}
	
	
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值