1. apache poi包里有4个主要的类:
Workbook----工作表,通过WorkbookFactory的create(FileInputStream fis)方法获取,
Sheet----------表格,Workbook实例的getSheetAt(int num)方法获取,
Row------------行,Sheet实例的getRow(int num)方法获取,
Cell-------------单元格,Row实例的getCell(int num)方法获取,
最后通过Cell实例根据数据类型调用对应的方法获取单元格的值。
2. 代码
package com.wangtiansoft.stla.common.utils;
//import com.upi.institution.common.utils.CommonUtils;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
public class ExcelUtil {
private static Logger logger = LoggerFactory.getLogger(ExcelUtil.class);
private static Workbook workbook;
private static Sheet sheet;
/**
* 初始化表格,判断文件格式是xls还是xlsx
* @param excelPath
*/
private static void initExcel(String excelPath){
if (StringUtils.isEmpty(excelPath)){
logger.info("文件路径不能为空");
workbook = null;
return;
}
try {
InputStream is = new FileInputStream(excelPath);
if (excelPath.endsWith(".xls")){
//.xls格式
workbook = new HSSFWorkbook(is);
}else if(excelPath.endsWit