postman上傳excel,java后台讀取excel生成到指定位置進行備份,並且把excel中的數據添加到數據庫


最近要做個前端網頁上傳excel,數據直接添加到數據庫的功能。。在此寫個讀取excel的demo。

首先新建springboot的web項目 導包,讀取excel可以用poi也可以用jxl,這里本文用的是poi

poi的 pom依賴如下:

<dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.17</version>
        </dependency>

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.17</version>
        </dependency>

service層的實現類為:

@Service
public class ExcelServiceImpl  implements ExcelService {
    @Autowired
    private  CorpTaxService corpTaxService;

    @Override
    public void read(HttpServletRequest request, HttpServletResponse response, MultipartFile file) {
        String fileName = "";
        String filePath = "D://";
        if (file != null && !file.isEmpty()){
            fileName = file.getOriginalFilename();
        }else {
            throw new CECException(501, "上傳的文件為空,請重新選擇。");
        }
        BigDecimal tenThsoud = new BigDecimal(10000);
        ArrayList<CorpTax> list = new ArrayList<>();

        //excel文件路徑
       // String excelPath2 =  "F:\\工作簿2.xlsx";
        try {
            FileInputStream fis = null;
            if (file != null && !file.isEmpty()) {   //判斷文件是否存在

                String[] split = file.getOriginalFilename().split("\\.");  //.是特殊字符,需要轉義!!!!!
                Workbook wb;
                //根據文件后綴(xls/xlsx)進行判斷
                if ( "xls".equals(split[1])){
                    //fis = new FileInputStream(excel);   //文件流對象
                    wb = new HSSFWorkbook(file.getInputStream());
                }else if ("xlsx".equals(split[1])){
                    wb = new XSSFWorkbook(file.getInputStream());
                }else {
                    System.out.println("文件類型錯誤!");
                    throw new CECException(501, "文件類型錯誤");
                }

                //開始解析
                Sheet sheet = wb.getSheetAt(0);     //讀取sheet 0

                int firstRowIndex = sheet.getFirstRowNum()+1;   //第一行是列名,所以不讀
                int lastRowIndex = sheet.getLastRowNum();
                System.out.println("firstRowIndex: "+firstRowIndex);
                System.out.println("lastRowIndex: "+lastRowIndex);

                for(int rIndex = firstRowIndex; rIndex <= lastRowIndex; rIndex++) {   //遍歷行
                    System.out.println("rIndex: " + rIndex);
                    Row row = sheet.getRow(rIndex);
                    if (row != null) {
                        CorpTax corpTax = new CorpTax();
                        corpTax.setCorpName(row.getCell(0).getStringCellValue());
                        corpTax.setTaxData(new BigDecimal(row.getCell(1).getNumericCellValue()).divide(tenThsoud, 6, RoundingMode.HALF_UP));
                        corpTax.setFiscalRet(new BigDecimal(row.getCell(2).getNumericCellValue()).divide(tenThsoud, 6,RoundingMode.HALF_UP));
                        corpTax.setIndustry(row.getCell(3).toString());
                        corpTax.setCorpType(row.getCell(4).toString());
                        corpTax.setCorpBelong(row.getCell(5).toString());
                        corpTax.setCorpYear((int)row.getCell(6).getNumericCellValue());
                        corpTax.setCorpMonth((int)row.getCell(7).getNumericCellValue());
                        System.out.println(corpTax);
                        list.add(corpTax);
              // 往數據庫庫添加數據,這里就是一個王數據庫的添加操作
int insert = corpTaxService.insert(corpTax); System.out.println(insert); int firstCellIndex = row.getFirstCellNum(); int lastCellIndex = row.getLastCellNum(); for (int cIndex = firstCellIndex; cIndex < lastCellIndex; cIndex++) { //遍歷列 Cell cell = row.getCell(cIndex); if (cell != null) { System.out.println(cell.toString()); } } } } wb.close(); } else { System.out.println("找不到指定的文件"); } } catch (Exception e) { e.printStackTrace(); }       // 把excel生成到指定位置進行備份。 FileInputStream fileInputStream; try { fileInputStream = (FileInputStream) file.getInputStream(); BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream); FileOutputStream fileOutputStream = new FileOutputStream(filePath + fileName); BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream); byte[] bytes = new byte[1024]; while (bufferedInputStream.read(bytes) != -1){ bufferedOutputStream.write(bytes); } bufferedOutputStream.flush(); bufferedOutputStream.close(); bufferedInputStream.close(); } catch (IOException e) { e.printStackTrace(); } for (CorpTax corpTax : list){ System.out.println(corpTax); } } public List<CorpTax> test(){ BigDecimal tenThsoud = new BigDecimal(10000); ArrayList<CorpTax> list = new ArrayList<>(); //excel文件路徑 String excelPath2 = "F:\\工作簿2.xlsx"; try { FileInputStream fis = null; //String encoding = "GBK"; File excel = new File(excelPath2); if (excel.isFile() && excel.exists()) { //判斷文件是否存在 String[] split = excel.getName().split("\\."); //.是特殊字符,需要轉義!!!!! Workbook wb; //根據文件后綴(xls/xlsx)進行判斷 if ( "xls".equals(split[1])){ fis = new FileInputStream(excel); //文件流對象 wb = new HSSFWorkbook(fis); }else if ("xlsx".equals(split[1])){ wb = new XSSFWorkbook(excel); }else { System.out.println("文件類型錯誤!"); return null; } //開始解析 Sheet sheet = wb.getSheetAt(0); //讀取sheet 0 int firstRowIndex = sheet.getFirstRowNum()+1; //第一行是列名,所以不讀 int lastRowIndex = sheet.getLastRowNum(); System.out.println("firstRowIndex: "+firstRowIndex); System.out.println("lastRowIndex: "+lastRowIndex); for(int rIndex = firstRowIndex; rIndex <= lastRowIndex; rIndex++) { //遍歷行 System.out.println("rIndex: " + rIndex); Row row = sheet.getRow(rIndex); if (row != null) { CorpTax corpTax = new CorpTax(); corpTax.setCorpName(row.getCell(0).getStringCellValue()); corpTax.setTaxData(new BigDecimal(row.getCell(1).getNumericCellValue()).divide(tenThsoud, 6, RoundingMode.HALF_UP)); corpTax.setFiscalRet(new BigDecimal(row.getCell(2).getNumericCellValue()).divide(tenThsoud, 6,RoundingMode.HALF_UP)); corpTax.setIndustry(row.getCell(3).toString()); corpTax.setCorpType(row.getCell(4).toString()); corpTax.setCorpBelong(row.getCell(5).toString()); corpTax.setCorpYear((int)row.getCell(6).getNumericCellValue()); corpTax.setCorpMonth((int)row.getCell(7).getNumericCellValue()); System.out.println(corpTax); list.add(corpTax); // int insert = corpTaxService.insert(corpTax); int firstCellIndex = row.getFirstCellNum(); int lastCellIndex = row.getLastCellNum(); for (int cIndex = firstCellIndex; cIndex < lastCellIndex; cIndex++) { //遍歷列 Cell cell = row.getCell(cIndex); if (cell != null) { System.out.println(cell.toString()); } } } } wb.close(); // fis.close(); } else { System.out.println("找不到指定的文件"); } } catch (Exception e) { e.printStackTrace(); } return list; } }

上面這個實現類包含兩個方法,上面的那個方法是,可以把excel生成到D盤進行備份,並且讀取其中的數據,添加到數據庫的(這里讀取excel中的數據添加到數據庫,是我根據自己的數據庫格式,剪切了excel就只剩下了8列,而且每一列的格式都是手動處理的,並沒有使用工具類進行處理,網友想要用工具類進行處理,可以參考https://www.cnblogs.com/zhanghaoliang/p/6526089.html)。

controller層就是一個簡單的對service層的調用

@RequestMapping("excel")
@RestController
public class ExcelController {

    @Autowired
    private ExcelService excelService;


    @RequestMapping(value = "upload",method = RequestMethod.POST)
    public String upLoadExcel(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "file") MultipartFile file){
        excelService.read(request, response, file);
        return "ok";
    }



}

 

參考文章:https://www.cnblogs.com/zhanghaoliang/p/6526089.html

https://blog.csdn.net/gxx_csdn/article/details/79085713

https://www.cnblogs.com/cx-code/p/9111336.html

 

下面說一下,過程中的坑;

1 org.springframework.beans.BeanInstantiationException  這是因為

HttpServletRequest request, HttpServletResponse response  寫成了
HttpRequest request, HttpResponse response






免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM