POI解析Excel

POI解析Excel

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;


* 获取Execl的表头
* @param is
* @return
* @throws IOException
*/
public static List<String> ExcelHead(InputStream is) throws IOException{
List<String> head = new ArrayList<>();

POIFSFileSystem fs = new POIFSFileSystem(is);
HSSFWorkbook wb = new HSSFWorkbook(fs);

HSSFSheet sheet = wb.getSheetAt(0);
HSSFRow row = sheet.getRow(0);

int colNum = row.getPhysicalNumberOfCells();

for (int i = 0; i < colNum; i++) {
HSSFCell cell = row.getCell(i);
head.add(cell.getStringCellValue());
}
return head;
}

/**
* 判断单元格内容的类型
* @param cell
* @return
*/
public String getCellValue(HSSFCell cell){
String result = null;
int cellType = cell.getCellType();

if (cellType == HSSFCell.CELL_TYPE_NUMERIC) {
if (HSSFDateUtil.isCellDateFormatted(cell)) {
Date date = cell.getDateCellValue();
SimpleDateFormat formater = new SimpleDateFormat("yyyy-MM-dd");
result = formater.format(date);
} else {
result = new Double(cell.getNumericCellValue()).toString();
}
} else if (cellType == HSSFCell.CELL_TYPE_STRING) {
if (cell.getStringCellValue().trim().equals("")) {
result = null;
} else {
result = cell.getStringCellValue();
}
} else if (cellType == HSSFCell.CELL_TYPE_BOOLEAN) {
if (cell.getBooleanCellValue()) {
result = "true";
} else {
result = "false";
}
} else if (cellType == HSSFCell.CELL_TYPE_ERROR) {
result = null;
} else {
result = null;
}

return result;
}

/**
* 获取内容
* @param is
* @return
* @throws IOException
*/
public Map<Integer, String> ExcelBody(InputStream is) throws IOException {
        Map<Integer, String> content = new HashMap<>();
        String str = " ";

        POIFSFileSystem fs = new POIFSFileSystem(is);
HSSFWorkbook wb = new HSSFWorkbook(fs);

HSSFSheet sheet = wb.getSheetAt(0);
HSSFRow row = sheet.getRow(0);

        int rowNum = sheet.getLastRowNum();
        int colNum = row.getPhysicalNumberOfCells();

        for (int i = 1; i <= rowNum; i++) {
            row = sheet.getRow(i);
            for (int j = 0; j < colNum; j++) {
            str += getCellValue(row.getCell(j));
}
            content.put(i, str);
            str = " ";
        }
        return content;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值