2018年6月27日
由于工作原因需要写一个 获取Excel数据 然后存入数据库的功能。
1.获取前台文件
2.处理Excel数据
3.存入数据库中
Controller
例:
importBatchData(CommonDomain conn, String proId, @RequestParam("txt_file") MultipartFile file)
其中@RequestParam("txt_file"),txt_file 前台设置文档的name 后台别名获取。
service
文件扩展名
String extension=file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
【org.apache.poi.ss.usermodel.Workbook】
Workbook wb=ExcelUtils.getWorkBook(file.getInputStream(), extension);
/**
* 获取Excel文件操作句柄
* @param stream 代操作的流
* @param extenSion 文件扩展名
* @return excel操作句柄
*/
public static Workbook getWorkBook(InputStream stream,String extenSion) {
Workbook workBook = null;
try {
if ("xls".equals(extenSion)) {
workBook = new HSSFWorkbook(stream,false);
} else if ("xlsx".equals(extenSion)) {
workBook = new XSSFWorkbook(stream);
} else {
throw new RuntimeException("不支持的文件类型:" + extenSion);
}
}catch(Exception e) {
throw new RuntimeException("发生错误:" + e.getMessage());
}
return workBook;
}
获取sheet数量
int sheetNums=wb.getNumberOfSheets();
Sheet fisrtSheet=wb.getSheetAt(0);
String batchNo=ExcelUtils.getCellValue(18, 2, fisrtSheet);
/**
* 获取单元格内容
* @param xInd 横坐标
* @param yInd 竖坐标
* @param sheet 待操作的excel
* @return cell的数据
*/
@SuppressWarnings("deprecation")
public static String getCellValue(int xInd,int yInd,Sheet sheet) {
Row row=sheet.getRow(xInd);
if(row==null)
return StringUtils.EMPTY;
Cell cell=row.getCell(yInd);
if (cell == null) {
return StringUtils.EMPTY;// StringUtils.EMPTY;
}
switch (cell.getCellTypeEnum()) {
case NUMERIC:
boolean isDate = HSSFDateUtil.isCellDateFormatted(cell);
if (isDate) {
return DateUtil.dateToStr(cell.getDateCellValue());
} else {
double value=cell.getNumericCellValue();
int intValue=(int)value;
if(value > intValue) {
BigDecimal bg= new BigDecimal(cell.getNumericCellValue());
bg=bg.setScale(2, RoundingMode.CEILING);
return String.valueOf(bg.doubleValue());
}else {
return String.valueOf(intValue);
}
}
case STRING:
return cell.getStringCellValue();
case BOOLEAN:
return String.valueOf(cell.getBooleanCellValue());
case BLANK:
return StringUtils.EMPTY;// StringUtils.EMPTY;
case FORMULA:
HSSFFormulaEvaluator eval=new HSSFFormulaEvaluator((HSSFWorkbook) sheet.getWorkbook());
return eval.evaluate(cell).getNumberValue()+"";
default:
return StringUtils.EMPTY;// StringUtils.EMPTY;
}
}
修改添加cell数据
public static void setCellValue(int rowInd,int colInd,Object value,Sheet sheet) {
Row row=sheet.getRow(rowInd);
if(row==null)
row=sheet.createRow(rowInd);
Cell cell=row.getCell(colInd,Row.CREATE_NULL_AS_BLANK);
if(cell==null)
cell=row.createCell(colInd);
if(null == value)
{
value = "";
}
cell.setCellValue(value.toString());
}
finally {
FileUtils.closeResource(wb);
}
public static void closeResource(Closeable resource) {
if(resource!=null)
try {
resource.close();
} catch (IOException e) {
e.printStackTrace();
}
}