欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

SpringBoot導(dǎo)入導(dǎo)出數(shù)據(jù)實(shí)現(xiàn)方法詳解

 更新時(shí)間:2022年12月02日 12:04:18   作者:披著星光的鯨魚(yú)  
這篇文章主要介紹了SpringBoot導(dǎo)入導(dǎo)出數(shù)據(jù)實(shí)現(xiàn)方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)吧

今天給大家?guī)?lái)的是一個(gè) SpringBoot導(dǎo)入導(dǎo)出數(shù)據(jù)

首先我們先創(chuàng)建項(xiàng)目 注意:創(chuàng)建SpringBoot項(xiàng)目時(shí)一定要聯(lián)網(wǎng)不然會(huì)報(bào)錯(cuò)

項(xiàng)目創(chuàng)建好后我們首先對(duì) application.yml 進(jìn)行編譯

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

注意:在 :后一定要空格,這是他的語(yǔ)法,不空格就會(huì)運(yùn)行報(bào)錯(cuò)

接下來(lái)我們進(jìn)行對(duì)項(xiàng)目的構(gòu)建 創(chuàng)建好如下幾個(gè)包 可根據(jù)自己實(shí)際需要?jiǎng)?chuàng)建其他的工具包之類(lèi)的

mapper:用于存放dao層接口

pojo:用于存放實(shí)體類(lèi)

service:用于存放service層接口,以及service層實(shí)現(xiàn)類(lèi)

controller:用于存放controller控制層

接下來(lái)我們開(kāi)始編寫(xiě)代碼

首先是實(shí)體類(lèi)

package com.bdqn.springbootexcel.pojo;
import lombok.Data;
import java.io.Serializable;
import java.util.List;
@Data
public class ExcelData implements Serializable{
    //文件名稱(chēng)
    private String fileName;
    //表頭數(shù)據(jù)
    private String[] head;
    //數(shù)據(jù)
    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("導(dǎo)出數(shù)據(jù)開(kāi)始。。。。。。");
        //查詢(xún)數(shù)據(jù)并賦值給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);
        //實(shí)現(xiàn)導(dǎo)出
        try {
            ExcelUtil.exportExcel(response, data);
            log.info("導(dǎo)出數(shù)據(jù)結(jié)束。。。。。。");
            return true;
        } catch (Exception e) {
            log.info("導(dǎo)出數(shù)據(jù)失敗。。。。。。");
            return false;
        }
    }
    @Override
    public Boolean importExcel(String fileName) {
        log.info("導(dǎo)入數(shù)據(jù)開(kāi)始。。。。。。");
        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("導(dǎo)入數(shù)據(jù)結(jié)束。。。。。。");
            return true;
        } catch (Exception e) {
            log.info("導(dǎo)入數(shù)據(jù)失敗。。。。。。");
            e.printStackTrace();
        }
        return false;
    }
    @Override
    public List<User> find() {
        return userMapper.find();
    }
}

工具類(lèi)

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("導(dǎo)出解析開(kāi)始,fileName:{}",data.getFileName());
        try {
            //實(shí)例化HSSFWorkbook
            HSSFWorkbook workbook = new HSSFWorkbook();
            //創(chuàng)建一個(gè)Excel表單,參數(shù)為sheet的名字
            HSSFSheet sheet = workbook.createSheet("sheet");
            //設(shè)置表頭
            setTitle(workbook, sheet, data.getHead());
            //設(shè)置單元格并賦值
            setData(sheet, data.getData());
            //設(shè)置瀏覽器下載
            setBrowser(response, workbook, data.getFileName());
            log.info("導(dǎo)出解析成功!");
        } catch (Exception e) {
            log.info("導(dǎo)出解析失敗!");
            e.printStackTrace();
        }
    }
    private static void setTitle(HSSFWorkbook workbook, HSSFSheet sheet, String[] str) {
        try {
            HSSFRow row = sheet.createRow(0);
            //設(shè)置列寬,setColumnWidth的第二個(gè)參數(shù)要乘以256,這個(gè)參數(shù)的單位是1/256個(gè)字符寬度
            for (int i = 0; i <= str.length; i++) {
                sheet.setColumnWidth(i, 15 * 256);
            }
            //設(shè)置為居中加粗,格式化時(shí)間格式
            HSSFCellStyle style = workbook.createCellStyle();
            HSSFFont font = workbook.createFont();
            font.setBold(true);
            style.setFont(font);
            style.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy h:mm"));
            //創(chuàng)建表頭名稱(chēng)
            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("導(dǎo)出時(shí)設(shè)置表頭失??!");
            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();
            //設(shè)置response的Header
            response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
            OutputStream os = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/vnd.ms-excel;charset=gb2312");
            //將excel寫(xiě)入到輸出流中
            workbook.write(os);
            os.flush();
            os.close();
            log.info("設(shè)置瀏覽器下載成功!");
        } catch (Exception e) {
            log.info("設(shè)置瀏覽器下載失?。?);
            e.printStackTrace();
        }
    }
    public static List<Object[]> importExcel(String fileName) {
        log.info("導(dǎo)入解析開(kāi)始,fileName:{}",fileName);
        try {
            List<Object[]> list = new ArrayList<>();
            InputStream inputStream = new FileInputStream(fileName);
            Workbook workbook = WorkbookFactory.create(inputStream);
            Sheet sheet = workbook.getSheetAt(0);
            //獲取sheet的行數(shù)
            int rows = sheet.getPhysicalNumberOfRows();
            for (int i = 0; i < rows; i++) {
                //過(guò)濾表頭行
                if (i == 0) {
                    continue;
                }
                //獲取當(dāng)前行的數(shù)據(jù)
                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("導(dǎo)入文件解析成功!");
            return list;
        }catch (Exception e){
            log.info("導(dǎo)入文件解析失??!");
            e.printStackTrace();
        }
        return null;
    }
    //測(cè)試導(dǎo)入
    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 "導(dǎo)出成功!";
                } else {
                    return "導(dǎo)出失?。?;
                }
            }
            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 "導(dǎo)入成功!";
                } else {
                    return "導(dǎo)入失敗!";
                }
            }
            return "文件格式錯(cuò)誤!";
        }
    }
    //餅狀圖的數(shù)據(jù)查詢(xún)
    //@ResponseBody
    @RequestMapping("/pojos_bing")
    public List<User> gotoIndex() {
        List<User> pojos = excelService.find();
        return pojos;
    }
}

到現(xiàn)在為止我們的后端代碼就已經(jīng)完全搞定了,前端頁(yè)面如下

寫(xiě)了一個(gè)簡(jiǎn)單前端用于測(cè)試

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" >導(dǎo)出</a>
        <a th:href="@{'/import'}" rel="external nofollow" >導(dǎo)入</a>
    </div>
</body>
</html>

當(dāng)我們點(diǎn)擊導(dǎo)出按鈕時(shí)瀏覽器會(huì)自動(dòng)下載

當(dāng)我們點(diǎn)擊導(dǎo)入按鈕時(shí)會(huì)往數(shù)據(jù)庫(kù)中添加表格數(shù)據(jù)

到此這篇關(guān)于SpringBoot導(dǎo)入導(dǎo)出數(shù)據(jù)實(shí)現(xiàn)方法詳解的文章就介紹到這了,更多相關(guān)SpringBoot導(dǎo)入導(dǎo)出數(shù)據(jù)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • SpringBoot+mail 輕松實(shí)現(xiàn)各類(lèi)郵件自動(dòng)推送

    SpringBoot+mail 輕松實(shí)現(xiàn)各類(lèi)郵件自動(dòng)推送

    在實(shí)際的項(xiàng)目開(kāi)發(fā)過(guò)程中,經(jīng)常需要用到郵件通知功能,例如,通過(guò)郵箱注冊(cè),郵箱找回密碼,郵箱推送報(bào)表等等,實(shí)際的應(yīng)用場(chǎng)景非常的多,今天通過(guò)這篇文章,我們一起來(lái)學(xué)習(xí)如何在 Spring Boot 中快速實(shí)現(xiàn)一個(gè)自動(dòng)發(fā)送郵件的功能
    2024-07-07
  • idea雙擊圖標(biāo)打不開(kāi),無(wú)反應(yīng)的解決

    idea雙擊圖標(biāo)打不開(kāi),無(wú)反應(yīng)的解決

    這篇文章主要介紹了idea雙擊圖標(biāo)打不開(kāi),無(wú)反應(yīng)的解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-09-09
  • mybatis查詢(xún)數(shù)據(jù)賦值到model里面為空的解決

    mybatis查詢(xún)數(shù)據(jù)賦值到model里面為空的解決

    這篇文章主要介紹了mybatis查詢(xún)數(shù)據(jù)賦值到model里面為空的解決,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-01-01
  • Java如何讀取配置文件并賦值靜態(tài)變量

    Java如何讀取配置文件并賦值靜態(tài)變量

    這篇文章主要介紹了Java如何讀取配置文件并賦值靜態(tài)變量,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-10-10
  • SpringBoot的自動(dòng)配置原理解析

    SpringBoot的自動(dòng)配置原理解析

    這篇文章主要介紹了SpringBoot的自動(dòng)配置原理解析,SpringBoot的自動(dòng)配置要從它的啟動(dòng)類(lèi)@SpringBootApplication說(shuō)起,點(diǎn)進(jìn)注解,@Target設(shè)置當(dāng)前注解可以標(biāo)記在哪,(ElementType.type)表示標(biāo)注在類(lèi)上面,需要的朋友可以參考下
    2023-08-08
  • Java web中 war exploded 的解決方案

    Java web中 war exploded 的解決方案

    這篇文章主要介紹了Java web中 war exploded 的解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-06-06
  • 基于Java代碼配置MyBatis Generator

    基于Java代碼配置MyBatis Generator

    這篇文章主要介紹了基于Java代碼配置MyBatis Generator,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-06-06
  • Spring Data JPA 建立表的聯(lián)合主鍵

    Spring Data JPA 建立表的聯(lián)合主鍵

    這篇文章主要介紹了Spring Data JPA 建立表的聯(lián)合主鍵。本文詳細(xì)的介紹了2種方式,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧
    2019-04-04
  • java實(shí)現(xiàn)從方法返回多個(gè)值功能示例

    java實(shí)現(xiàn)從方法返回多個(gè)值功能示例

    這篇文章主要介紹了java實(shí)現(xiàn)從方法返回多個(gè)值功能,結(jié)合實(shí)例形式分析了集合類(lèi)、封裝對(duì)象、引用傳遞三種實(shí)現(xiàn)方法,需要的朋友可以參考下
    2017-10-10
  • Java實(shí)現(xiàn)把窗體隱藏到系統(tǒng)托盤(pán)方法

    Java實(shí)現(xiàn)把窗體隱藏到系統(tǒng)托盤(pán)方法

    這篇文章主要介紹了Java實(shí)現(xiàn)把窗體隱藏到系統(tǒng)托盤(pán)方法,本文直接給出核心功能代碼,需要的朋友可以參考下
    2015-05-05

最新評(píng)論