Excelファイルをアップロードしてデータベースに読み込み
備考:上編に続いてクリックしてリンクを開く
1、コントロール層の方法:
2、サービス実装層方法:
注意:springプロファイル:アプリケーションContext.xml追加構成
1、コントロール層の方法:
@RequestMapping(value = "uploadFile")
public void uploadFile(Model model, MultipartFile file) throws Exception {
bluetoothService.uploadFileToDatabase(file);
model.addAttribute(new Protocol());
}
2、サービス実装層方法:
public void uploadFileToDatabase(MultipartFile file) {
// TODO Auto-generated method stub
if (file == null) {
throw new BusinessException(ResponseCode.FAIL.code, " !");
}
String fileName = file.getOriginalFilename();
if (!(fileName.endsWith(".xls") || fileName.endsWith(".xlsx"))) {
logger.error(" {} , Excel !", fileName);
throw new BusinessException(ResponseCode.FAIL.code, " , Excel !");
}
XSSFWorkbook workBook = null;
try {
InputStream input = file.getInputStream();
workBook = new XSSFWorkbook(input);
} catch (Exception e) {
e.printStackTrace();
logger.error("===>> " + fileName + " :" + e.getMessage(), e);
throw new BusinessException(ResponseCode.FAIL.code, " :" + e.getMessage());
}
XSSFSheet sheet = workBook.getSheetAt(0);
if (sheet != null) {
int rows = sheet.getPhysicalNumberOfRows();
for (int i = 1; i < rows; i++) {
XSSFRow row = sheet.getRow(i);
for (int j = 0; j < row.getPhysicalNumberOfCells(); j++) {
XSSFCell cell = row.getCell(j);
String cellStr = "";
if (cell != null) {
cellStr = cell.toString();
}
System.out.print("【" + cellStr + "】 ");
}
System.out.println();
}
}
}
注意:springプロファイル:アプリケーションContext.xml追加構成