import java.io.InputStream; import java.util.Date; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.usermodel.XSSFRow; public class ReadExcel { @SuppressWarnings("deprecation") public static Object readExcel(InputStream is,Workbook workbook,Sheet sheet,int h,int l,String bb){ //行:h,列:l,判断标志:bb Cell cell; if(bb.equals("03")){ HSSFRow row=(HSSFRow) sheet.getRow(h); cell=row.getCell(l); }else{ XSSFRow row=(XSSFRow) sheet.getRow(h); cell=row.getCell(l); } if(cell==null||"".equals(cell)){ return null; }else{ switch (cell.getCellType()) { case Cell.CELL_TYPE_NUMERIC: return (Date) cell.getDateCellValue(); case Cell.CELL_TYPE_STRING: return cell.getStringCellValue(); case Cell.CELL_TYPE_BOOLEAN: return cell.getBooleanCellValue(); case Cell.CELL_TYPE_ERROR: return Cell.CELL_TYPE_ERROR; case Cell.CELL_TYPE_FORMULA: String value=String.valueOf(cell.getNumericCellValue()); if(value.equals("NaN")){ return cell.getStringCellValue(); }else{ return value; } case Cell.CELL_TYPE_BLANK: return null; default: return cell.getStringCellValue().toString(); } } }
import java.io.IOException;
import java.io.InputStream;
//调用方法(有些注解其实可以不要)
@SuppressWarnings("deprecation")
@RequestMapping(value = "insertExcel.do", method = RequestMethod.POST,produces="text/html;charset=utf-8")
@ResponseBody
@ResponseBody
public String insertExcelCQ(@RequestParam("fkxx")MultipartFile excel,……) throws UnsupportedEncodingException {
try {
……
InputStream is = excel.getInputStream();
//调用Service中的方法
riskmesService.insertExcel(is, ……);
……
return string;
} catch (Exception e) {
……
return string;
}
}
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
//Service中的方法
public void insertExcel(InputStream is,……){
Workbook workbook;
Sheet sheet;
String bb;
//根据版本分别定义参数
try {
try{
bb="07";
workbook=new XSSFWorkbook(is);
sheet=(XSSFSheet) workbook.getSheetAt(0);
}catch(Exception e){
bb="03";
workbook=new HSSFWorkbook(is);
sheet=(HSSFSheet) workbook.getSheetAt(0);
}
//循环遍历所有行(行数和列数都是从0开始的)
for(int i=2;i<sheet.getPhysicalNumberOfRows();i++){
……
String str1=ReadExcel.readExcel(is, workbook, sheet, i, 1, bb);//获取i行1列的数据
String str2=ReadExcel.readExcel(is, workbook, sheet, i, 2, bb);//获取i行2列的数据
……
}
}
需要的包