POI导入工具类

ExcelUtil.java  是主要工具类
WDWUtil.java  是验证Excel是2003(HSSFWorkbook)还是2007(XSSFWorkbook);以及文件是否是Excel文件

使用方法,此处是SpringMVC接收上传的文件,
使用(org.springframework.web.multipart.MultipartFile)MultipartFile file来接收文件

使用方法如下所示:

String filename = file.getOriginalFilename();//得到上传的文件名称
InputStream is = file.getInputStream();// 转化为流的方式
List<Row> list = ExcelUtil.getExcelRead(filename, is, true);
if (list.size()==0) {
	return 2;//2 excel文件为空
}
for (Row row : list) {
	//得到每个元素的值 这里是两列
	Cell cell_0 = row.getCell(0);
	Cell cell_1 = row.getCell(1);
	//得到列的值,也就是你需要解析的字段的值
	String a100 = ExcelUtil.getValue(cell_0);
	String a298 = ExcelUtil.getValue(cell_1);
	//将读取出来的数值set给Special
	special.setA100(a100);
	special.setA298(a298);
	listMer.add(special);
	//存到表里
	specialService.save(special);
}

 

导入主要工具类ExcelUtil如下:

package com.ocean.utils;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
 /**
  * <p>desc:Excel 工具类 </p>
  * <p>类名:ExcelUtil </p>
  */
public class ExcelUtil {
    //读取文件的方法
    /**
     * 获取解析文件行数据
     * @param fileName : 文件地址
     * @param isTitle  : 是否过滤第一行解析
     * @return
     * @throws Exception
     */
    public static List<Row> getExcelRead(String fileName, InputStream is, boolean isTitle) throws Exception{
        try {
            //判断其兼容版本 调用了判断版本的方法
            Workbook workbook = getWorkbook(fileName,is);
            Sheet sheet = workbook.getSheetAt(0);
            int count = 0;
            List<Row> list = new ArrayList<Row>();
            for (Row row : sheet) {
                // 跳过第一行的目录
                if (count == 0 && isTitle) {
                    count++;
                    continue;
                }
                list.add(row);
            }
            return list;
        } catch (Exception e) {
            throw e;
        }
    }
 
//判断版本的方法
 
    public static Workbook getWorkbook(String fileName,InputStream is) throws Exception{
        Workbook workbook = null;
        try {
            /** 判断文件的类型,是2003还是2007 */
            boolean isExcel2003 = true;
            if (WDWUtil.isExcel2007(fileName)) {
                isExcel2003 = false;
            }
 
            if (isExcel2003) {
                workbook = new HSSFWorkbook(is);
            } else {
                workbook = new XSSFWorkbook(is);
            }
        } catch (Exception e) {
            throw e;
        }
        return workbook;
    }
 
    //得到cell值的方法:
    public static String getValue(Cell cell){
        if(cell.getCellType() == HSSFCell.CELL_TYPE_BOOLEAN){
            return String.valueOf(cell.getBooleanCellValue());
        }else if(cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC){
            double value = cell.getNumericCellValue();
            return new BigDecimal(value).toString();
        }else if (cell.getCellType() ==HSSFCell.CELL_TYPE_STRING){
            return String.valueOf(cell.getStringCellValue());
        }else{
            return String.valueOf(cell.getStringCellValue());
        }
    }
 
 
}

下边这个是工具类WDWUtil是判断 上传的是03还是07的Excel文件

package com.ocean.utils;

/**
 * <p>desc:工具类验证Excel文档 </p>
 * <p>类名:WDWUtil </p>
 */
public class WDWUtil {
    /**
     * @描述:是否是2003的excel,返回true是2003
     * @param filePath
     * @return
     */
    public static boolean isExcel2003(String filePath)  {
        return filePath.matches("^.+\\.(?i)(xls)$");
    }
 
    /**
     * @描述:是否是2007的excel,返回true是2007
     * @param filePath
     * @return
     */
    public static boolean isExcel2007(String filePath)  {
        return filePath.matches("^.+\\.(?i)(xlsx)$");
    }
 
    /**
     * 验证是否是EXCEL文件
     * @param filePath
     * @return
     */
    public static boolean validateExcel(String filePath){
        if (filePath == null || !(isExcel2003(filePath) || isExcel2007(filePath))){
            return false;
        }
        return true;
    }
}


CELL_TYPE_NUMERIC       数值型    
CELL_TYPE_STRING          字符串型    
CELL_TYPE_FORMULA       公式型   
CELL_TYPE_BLANK            空值    
CELL_TYPE_BOOLEAN      布尔型   
CELL_TYPE_ERROR           错误   
 

 

 

 

 

下面是使用Apache POI导入Excel的Java工具类示例: ```java import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class ExcelUtils { /** * 读取Excel文件,返回一个二维数组 * * @param filePath Excel文件路径 * @param sheetName 工作表名称 * @return 二维数组 * @throws IOException */ public static String[][] readExcel(String filePath, String sheetName) throws IOException { Workbook workbook = null; InputStream inputStream = new FileInputStream(filePath); if (filePath.endsWith(".xls")) { workbook = new HSSFWorkbook(inputStream); } else if (filePath.endsWith(".xlsx")) { workbook = new XSSFWorkbook(inputStream); } else { throw new RuntimeException("不支持的文件格式"); } Sheet sheet = workbook.getSheet(sheetName); int rowCount = sheet.getPhysicalNumberOfRows(); int columnCount = sheet.getRow(0).getPhysicalNumberOfCells(); String[][] data = new String[rowCount - 1][columnCount]; for (int i = 1; i < rowCount; i++) { Row row = sheet.getRow(i); for (int j = 0; j < columnCount; j++) { Cell cell = row.getCell(j); data[i - 1][j] = cell.toString(); } } workbook.close(); inputStream.close(); return data; } } ``` 使用示例: ```java String filePath = "path/to/excel/file.xlsx"; String sheetName = "Sheet1"; String[][] data = ExcelUtils.readExcel(filePath, sheetName); ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值