如何使用Spring Data JPA和DTO设计模式从Excel导入数据

问题描述

我试图将数据从excel导入到db表中,当我用邮递员测试该应用程序时,它成功了,但是excel表上没有数据持久化到db表中。 Json响应还通过返回一个空数据对象来确认这一点。请协助。

以下是空但成功的json响应:

{
    "status": "OK","success": true,"errorCode": 0,"data": [],"message": "See Data object for Details!","timestamp": "2020-08-25T13:27:36.112+00:00"
}

这是我的导入代码

    @Transactional
    public List <AuditorStampDutyReport> importAuditorStampDutyReportDetails(multipartfile myfile) {

        List<AuditorStampDutyReport> uploadReport = new ArrayList<>();
        AuditorStampDutyReport excelReport = new AuditorStampDutyReport();

        int sheetNumber=1,rowNumber=2;
        try {
            Workbook workbook = new XSSFWorkbook(myfile.getInputStream());
            for (int i = 2; i < workbook.getNumberOfSheets(); i++) {
                sheetNumber = i;
                Sheet sheet = workbook.getSheetAt(i);
                for (Row row : sheet) {
                    rowNumber = row.getRowNum();
                    if (rowNumber < 2) {
                        String possibleTaxPayerId = ImportExcelHelper.getorDefault(row.getCell(1),"").trim().replaceAll(" +"," ");
                        Organization organization = null;
                        //for name of tax payer
                        if (possibleTaxPayerId != null) {
                            organization = organizationRepository.findFirstNameByNameLike(organization.getId(),possibleTaxPayerId);
                        }
                        excelReport.setorganization(organization);
                        excelReport.setTin_of_tax_payer_organization(ImportExcelHelper.getString(row.getCell(2)));
                        excelReport.setPeriod_covered(ImportExcelHelper.getorDefault(row.getCell(3),""));

                        continue;
                    }

                    if (rowNumber > 2 && rowNumber < 6){
                        excelReport.setDate_of_transaction(ImportExcelHelper.getDate(row.getCell(2)));
                        excelReport.setDuty_payer(ImportExcelHelper.getString(row.getCell(3)));
                        excelReport.setTin_of_duty_payer(ImportExcelHelper.getString(row.getCell(4)));

                        String possibleInstrumentId = ImportExcelHelper.getorDefault(row.getCell(5),"");
                        Instruments instruments = null;
                        if (possibleInstrumentId != null) {
                            instruments = instrumentsRepository.findByNameLike(instruments.getId(),possibleInstrumentId);
                        }
                        excelReport.setInstruments(instruments);

                        excelReport.setAssessment_number(ImportExcelHelper.getLong(row.getCell(6)));

                        DeedOfAssignment deedOfAssignment = null;
if(deedOfAssignment.getId()!=null && deedOfAssignment.getId()>0) {

    }

}
}

                        excelReport.setReceipt_number(ImportExcelHelper.getString(row.getCell(10)));
                        excelReport.setConsideration(ImportExcelHelper.getDouble(row.getCell(11)));
                        excelReport.setRate(ImportExcelHelper.getDouble(row.getCell(12)));
                        excelReport.setAmount_payable(ImportExcelHelper.getDouble(row.getCell(13)));
                        excelReport.setAmount_paid(ImportExcelHelper.getDouble(row.getCell(14)));
                        excelReport.setDate_of_payment(ImportExcelHelper.getDate(row.getCell(15)));
                        excelReport.setBalance(ImportExcelHelper.getDouble(row.getCell(16)));
                        excelReport.setPenalty(ImportExcelHelper.getDouble(row.getCell(17)));
                        excelReport.setoutstanding(ImportExcelHelper.getDouble(row.getCell(18)));
                        excelReport.setRemarks(ImportExcelHelper.getString(row.getCell(19)));

                        if (ImportExcelHelper.isCellEmpty(row.getCell(0))) {
                            continue;   //Empty END OF FILE
                        }

                        if(rowNumber==16){
                            excelReport.setAmount_recoverable(ImportExcelHelper.getDouble(row.getCell(18)));
                        }

                        logger.log(Level.INFO,"Row Number: {0}",rowNumber);
                        uploadReport.add(excelReport);

                    }
                }

            uploadReport = auditorStampDutyReportRepository.saveAll(uploadReport);
        }
        catch (IOException| IllegalArgumentException | NullPointerException ex) {
            logger.log(Level.SEVERE,null,ex);
            throw new IllegalArgumentException("Sheet: " + (sheetNumber + 1) + " - Row: " + (rowNumber) + " - Error: " + ex.getMessage());
        }
        return uploadReport;
    }



这是excel助手类:

import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.util.Date;
import lombok.Data;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.springframework.stereotype.Component;

/**
 *
 * @author Dell G7
 */
@Component
@Data
public class ImportExcelHelper {
    
    public static String getorDefault(Cell cell,String defaultValue) {
        return isCellEmpty(cell) ? defaultValue : getString(cell);
    }

    public static Double getDouble(Cell cell) {
        return cell.getCellType() == CellType.STRING ? Double.valueOf(cell.getStringCellValue()) : cell.getNumericCellValue();
    }

    public static Integer getInteger(Cell cell){
        return cell.getCellType() == CellType.STRING ?
                Integer.valueOf(cell.getStringCellValue()) : Integer.valueOf(cell.getNumericCellValue()+"");
    }

    public static Long getLong(Cell cell){
        return  cell.getCellType() == CellType.STRING ?
                Long.valueOf(cell.getStringCellValue()): Long.valueOf(cell.getNumericCellValue()+ "");
    }

    public static String getString(Cell cell) {
        return cell.getCellType() == CellType.NUMERIC ? String.valueOf(cell.getNumericCellValue()) : cell.getStringCellValue().trim();
    }
    
    public static boolean isCellEmpty(Cell cell) {
        if (cell == null || cell.getCellType() == CellType.BLANK) {
            return true;
        }
        return cell.getCellType() == CellType.STRING && cell.getStringCellValue().trim().isEmpty();
    }

    public static LocalDate getDate(Cell cell) {
        if (isCellEmpty(cell)) {
            return null;
        }
        try {
            Date date = cell.getDateCellValue();
            return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        } catch (Exception e) {
            return getDate(cell.getStringCellValue());
        }
    }

    public static LocalDate getDate(String date) {
        DateTimeFormatter formatter = new DateTimeFormatterBuilder()
                .appendOptional(DateTimeFormatter.ofPattern("d/MM/yyyy"))
                .appendOptional(DateTimeFormatter.ofPattern("d/M/yyyy"))
                .appendOptional(DateTimeFormatter.ofPattern("dd/M/yyyy"))
                .appendOptional(DateTimeFormatter.ofPattern("dd/MM/yyyy"))
                .toFormatter();
        return LocalDate.parse(date,formatter);
    }

}


这是我的控制器

    @Transactional
    @PostMapping(path = "/upload",consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResponseEntity<Object> uploadAuditorReport(@RequestPart("importFile") multipartfile fileImport){
        System.out.println("Entry Point With File Import : " + fileImport.getName());

    List <AuditorStampDutyReport> uploadExcelSheet = auditorStampDutyReportService.importAuditorStampDutyReportDetails(fileImport);
    return ResponseEntity.ok(new JsonResponse("See Data object for Details!",uploadExcelSheet));
}


欢迎任何帮助。谢谢

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)