1.导入 Maven
<dependency> <groupId>org.jeecg</groupId> <artifactId>easypoi-base</artifactId> <version>2.3.1</version>
</dependency>
2.Controller代码
@RequestMapping(value = "importPsd")
public String importPsd(MultipartFile file,HttpServletRequest request, HttpServletResponse response, Model model ,RedirectAttributes redirectAttributes) throws Exception {
syPsyhPsdService.importPsd(file);
return "导入成功跳转的页面";
}
3.Service代码
/**
* 批量导入(批量添加)
*/
private static final String XLS = "xls";
private static final String XLSK = "xlsx"; //定义全局的常量值
@Transactional(readOnly = false)
public void importPsd(MultipartFile file) throws Exception {
List<SyPsyhPsd> list = new ArrayList<SyPsyhPsd>();
Map<String, Object> rsultMap = new HashMap<String, Object>();
AutoCode auto =new AutoCode();
Workbook workbook = null;
String fileName = file.getOriginalFilename();
if(fileName.endsWith("xls")) {
//2003
try {
workbook = new HSSFWorkbook(file.getInputStream());
} catch (Exception e) {
e.printStackTrace( );
}
}else if(fileName.endsWith("xlsx")) {
try {
//2007
workbook = new XSSFWorkbook(file.getInputStream());
} catch (Exception e) {
e.printStackTrace( );
}
}else {
try {
throw new Exception("文件不是Excel文件");
} catch (Exception e) {
e.printStackTrace();
}
}
Sheet sheet = workbook.getSheet("export");
int rows = sheet.getLastRowNum();//指定行数。一共多少+
if(rows==0) {
try {
throw new Exception("请填写行数");
} catch (Exception e) {
e.printStackTrace();
}
}
for (int i = 2; i < rows+1; i++) {
//读取左上端单元格
Row row = sheet.getRow(i);
//行不为空
if(row != null) {
//创建实体类
SyPsyhPsd syPsyhPsd = new SyPsyhPsd();
//读取第一个内容
String rq = getCellValue(row.getCell(0));
syPsyhPsd.setRq(rq);
//读取第二个内容
/*String khpk = getCellValue(row.getCell(1));
syPsyhPsd.setKhpk(khpk);;*/
//读取第三个内容
String zzsj = getCellValue(row.getCell(1));
syPsyhPsd.setZzsj(zzsj);
//读取第四个内容
String zwsj = getCellValue(row.getCell(2));
syPsyhPsd.setZwsj(zwsj);
//读取第五个内容
String hwsx = getCellValue(row.getCell(3));
syPsyhPsd.setHwsx(hwsx);
//判断实体是否为空
if (syPsyhPsd!=null) {
//如果不为空,调用增加方法
super.save(syPsyhPsd);
}
}
}
}
/**
*获取Cell内容
*
*/
private String getCellValue(Cell cell) {
String value = "";
if(cell != null) {
//以下是判断数据的类型
switch (cell.getCellType()) {
case HSSFCell.CELL_TYPE_NUMERIC://数字
value = cell.getNumericCellValue() + "";
if(HSSFDateUtil.isCellDateFormatted(cell)) {
Date date = cell.getDateCellValue();
if(date != null) {
value = new SimpleDateFormat("yyyy-MM-dd").format(date);
}else {
value = "";
}
}else {
value = new DecimalFormat("0").format(cell.getNumericCellValue());
}
break;
case HSSFCell.CELL_TYPE_STRING: //字符串
value = cell.getStringCellValue();
break;
case HSSFCell.CELL_TYPE_BOOLEAN: //boolean
value = cell.getBooleanCellValue() + "";
break;
case HSSFCell.CELL_TYPE_FORMULA: //公式
value = cell.getCellFormula() + "";
break;
case HSSFCell.CELL_TYPE_BLANK: //空值
value = "";
break;
case HSSFCell.CELL_TYPE_ERROR: //故障
value = "非法字符";
break;
default:
value = "未知类型";
break;
}
}
return value.trim();
}