首頁 > 軟體

SpringBoot匯入匯出資料實現方法詳解

2022-12-03 14:01:21

今天給大家帶來的是一個 SpringBoot匯入匯出資料

首先我們先建立專案 注意:建立SpringBoot專案時一定要聯網不然會報錯

專案建立好後我們首先對 application.yml 進行編譯

server:
  port: 8081
# mysql
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/dvd?characterEncoding=utf-8&&severTimezone=utc
    username: root
    password: root
  thymeleaf:
    mode: HTML5
    cache: false
    suffix: .html
    prefix: classpath:/
mybatis:
  mapperLocations: classpath:mapper/**/*.xml
  configuration:
    map-underscore-to-camel-case: true
pagehelper:
  helper-dialect: mysql
  offset-as-page-num: true
  params: count=countSql
  reasonable: true
  row-bounds-with-count: true
  support-methods-arguments: true

注意:在 :後一定要空格,這是他的語法,不空格就會執行報錯

接下來我們進行對專案的構建 建立好如下幾個包 可根據自己實際需要建立其他的工具包之類的

mapper:用於存放dao層介面

pojo:用於存放實體類

service:用於存放service層介面,以及service層實現類

controller:用於存放controller控制層

接下來我們開始編寫程式碼

首先是實體類

package com.bdqn.springbootexcel.pojo;
import lombok.Data;
import java.io.Serializable;
import java.util.List;
@Data
public class ExcelData implements Serializable{
    //檔名稱
    private String fileName;
    //表頭資料
    private String[] head;
    //資料
    private List<String[]> data;
}

然後是service層

package com.bdqn.springbootexcel.service;
import com.bdqn.springbootexcel.pojo.User;
import org.apache.ibatis.annotations.Select;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
public interface ExcelService {
    Boolean exportExcel(HttpServletResponse response, String fileName, Integer pageNum, Integer pageSize);
    Boolean importExcel(String fileName);
    List<User> find();
}
package com.bdqn.springbootexcel.service;
import com.bdqn.springbootexcel.mapper.UserMapper;
import com.bdqn.springbootexcel.pojo.ExcelData;
import com.bdqn.springbootexcel.pojo.User;
import com.bdqn.springbootexcel.util.ExcelUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
@Slf4j
@Service
public class ExcelServiceImpl implements ExcelService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public Boolean exportExcel(HttpServletResponse response, String fileName, Integer pageNum, Integer pageSize) {
        log.info("匯出資料開始。。。。。。");
        //查詢資料並賦值給ExcelData
        List<User> userList = userMapper.find();
        List<String[]> list = new ArrayList<String[]>();
        for (User user : userList) {
            String[] arrs = new String[userList.size()];
            arrs[0] = String.valueOf(user.getId());
            arrs[1] = String.valueOf(user.getName());
            arrs[2] = String.valueOf(user.getAge());
            arrs[3] = String.valueOf(user.getSex());
            list.add(arrs);
        }
        //表頭賦值
        String[] head = {"序列", "名字", "年齡", "性別"};
        ExcelData data = new ExcelData();
        data.setHead(head);
        data.setData(list);
        data.setFileName(fileName);
        //實現匯出
        try {
            ExcelUtil.exportExcel(response, data);
            log.info("匯出資料結束。。。。。。");
            return true;
        } catch (Exception e) {
            log.info("匯出資料失敗。。。。。。");
            return false;
        }
    }
    @Override
    public Boolean importExcel(String fileName) {
        log.info("匯入資料開始。。。。。。");
        try {
            List<Object[]> list = ExcelUtil.importExcel(fileName);
            System.out.println(list.toString());
            for (int i = 0; i < list.size(); i++) {
                User user = new User();
                user.setName((String) list.get(i)[0]);
                user.setAge((String) list.get(i)[1]);
                user.setSex((String) list.get(i)[2]);
                userMapper.add(user);
            }
            log.info("匯入資料結束。。。。。。");
            return true;
        } catch (Exception e) {
            log.info("匯入資料失敗。。。。。。");
            e.printStackTrace();
        }
        return false;
    }
    @Override
    public List<User> find() {
        return userMapper.find();
    }
}

工具類

package com.bdqn.springbootexcel.util;
import com.bdqn.springbootexcel.pojo.ExcelData;
import com.bdqn.springbootexcel.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import static org.apache.poi.ss.usermodel.CellType.*;
@Slf4j
public class ExcelUtil {
    public static void exportExcel(HttpServletResponse response, ExcelData data) {
        log.info("匯出解析開始,fileName:{}",data.getFileName());
        try {
            //範例化HSSFWorkbook
            HSSFWorkbook workbook = new HSSFWorkbook();
            //建立一個Excel表單,引數為sheet的名字
            HSSFSheet sheet = workbook.createSheet("sheet");
            //設定表頭
            setTitle(workbook, sheet, data.getHead());
            //設定單元格並賦值
            setData(sheet, data.getData());
            //設定瀏覽器下載
            setBrowser(response, workbook, data.getFileName());
            log.info("匯出解析成功!");
        } catch (Exception e) {
            log.info("匯出解析失敗!");
            e.printStackTrace();
        }
    }
    private static void setTitle(HSSFWorkbook workbook, HSSFSheet sheet, String[] str) {
        try {
            HSSFRow row = sheet.createRow(0);
            //設定列寬,setColumnWidth的第二個引數要乘以256,這個引數的單位是1/256個字元寬度
            for (int i = 0; i <= str.length; i++) {
                sheet.setColumnWidth(i, 15 * 256);
            }
            //設定為居中加粗,格式化時間格式
            HSSFCellStyle style = workbook.createCellStyle();
            HSSFFont font = workbook.createFont();
            font.setBold(true);
            style.setFont(font);
            style.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy h:mm"));
            //建立表頭名稱
            HSSFCell cell;
            for (int j = 0; j < str.length; j++) {
                cell = row.createCell(j);
                cell.setCellValue(str[j]);
                cell.setCellStyle(style);
            }
        } catch (Exception e) {
            log.info("匯出時設定表頭失敗!");
            e.printStackTrace();
        }
    }
    private static void setData(HSSFSheet sheet, List<String[]> data) {
        try{
            int rowNum = 1;
            for (int i = 0; i < data.size(); i++) {
                HSSFRow row = sheet.createRow(rowNum);
                for (int j = 0; j < data.get(i).length; j++) {
                    row.createCell(j).setCellValue(data.get(i)[j]);
                }
                rowNum++;
            }
            log.info("表格賦值成功!");
        }catch (Exception e){
            log.info("表格賦值失敗!");
            e.printStackTrace();
        }
    }
    private static void setBrowser(HttpServletResponse response, HSSFWorkbook workbook, String fileName) {
        try {
            //清空response
            response.reset();
            //設定response的Header
            response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
            OutputStream os = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/vnd.ms-excel;charset=gb2312");
            //將excel寫入到輸出流中
            workbook.write(os);
            os.flush();
            os.close();
            log.info("設定瀏覽器下載成功!");
        } catch (Exception e) {
            log.info("設定瀏覽器下載失敗!");
            e.printStackTrace();
        }
    }
    public static List<Object[]> importExcel(String fileName) {
        log.info("匯入解析開始,fileName:{}",fileName);
        try {
            List<Object[]> list = new ArrayList<>();
            InputStream inputStream = new FileInputStream(fileName);
            Workbook workbook = WorkbookFactory.create(inputStream);
            Sheet sheet = workbook.getSheetAt(0);
            //獲取sheet的行數
            int rows = sheet.getPhysicalNumberOfRows();
            for (int i = 0; i < rows; i++) {
                //過濾表頭行
                if (i == 0) {
                    continue;
                }
                //獲取當前行的資料
                Row row = sheet.getRow(i);
                Object[] objects = new Object[row.getPhysicalNumberOfCells()];
                int index = 0;
                for (Cell cell : row) {
                    if (cell.getCellType().equals(NUMERIC)) {
                        objects[index] = (int) cell.getNumericCellValue();
                    }
                    if (cell.getCellType().equals(STRING)) {
                        objects[index] = cell.getStringCellValue();
                    }
                    if (cell.getCellType().equals(BOOLEAN)) {
                        objects[index] = cell.getBooleanCellValue();
                    }
                    if (cell.getCellType().equals(ERROR)) {
                        objects[index] = cell.getErrorCellValue();
                    }
                    index++;
                }
                list.add(objects);
            }
            log.info("匯入檔案解析成功!");
            return list;
        }catch (Exception e){
            log.info("匯入檔案解析失敗!");
            e.printStackTrace();
        }
        return null;
    }
    //測試匯入
    public static void main(String[] args) {
        try {
            String fileName = "G:/test.xlsx";
            List<Object[]> list = importExcel(fileName);
            for (int i = 0; i < list.size(); i++) {
                User user = new User();
                user.setName((String) list.get(i)[0]);
                user.setAge((String) list.get(i)[1]);
                user.setSex((String) list.get(i)[2]);
                System.out.println(user.toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

最後是controller層

package com.bdqn.springbootexcel.controller;
import com.bdqn.springbootexcel.pojo.User;
import com.bdqn.springbootexcel.service.ExcelService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
@Slf4j
@RestController
public class ExcelController {
    @Autowired
    private ExcelService excelService;
    @GetMapping("/export")
    public String exportExcel(HttpServletResponse response, String fileName, Integer pageNum, Integer pageSize) {
        fileName = "test.xlsx";
        if (fileName == null || "".equals(fileName)) {
            return "檔名不能為空!";
        } else {
            if (fileName.endsWith("xls") || fileName.endsWith("xlsx")) {
                Boolean isOk = excelService.exportExcel(response, fileName, 1, 10);
                if (isOk) {
                    return "匯出成功!";
                } else {
                    return "匯出失敗!";
                }
            }
            return "檔案格式有誤!";
        }
    }
    @GetMapping("/import")
    public String importExcel(String fileName) {
        fileName = "G:/test.xlsx";
        if (fileName == null && "".equals(fileName)) {
            return "檔名不能為空!";
        } else {
            if (fileName.endsWith("xls") || fileName.endsWith("xlsx")) {
                Boolean isOk = excelService.importExcel(fileName);
                if (isOk) {
                    return "匯入成功!";
                } else {
                    return "匯入失敗!";
                }
            }
            return "檔案格式錯誤!";
        }
    }
    //餅狀圖的資料查詢
    //@ResponseBody
    @RequestMapping("/pojos_bing")
    public List<User> gotoIndex() {
        List<User> pojos = excelService.find();
        return pojos;
    }
}

到現在為止我們的後端程式碼就已經完全搞定了,前端頁面如下

寫了一個簡單前端用於測試

index.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <div align="center">
        <a th:href="@{'/export'}" rel="external nofollow" >匯出</a>
        <a th:href="@{'/import'}" rel="external nofollow" >匯入</a>
    </div>
</body>
</html>

當我們點選匯出按鈕時瀏覽器會自動下載

當我們點選匯入按鈕時會往資料庫中新增表格資料

到此這篇關於SpringBoot匯入匯出資料實現方法詳解的文章就介紹到這了,更多相關SpringBoot匯入匯出資料內容請搜尋it145.com以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援it145.com!


IT145.com E-mail:sddin#qq.com