最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

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

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

今天給大家?guī)淼氖且粋€(gè) SpringBoot導(dǎo)入導(dǎo)出數(shù)據(jù)

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

項(xiàng)目創(chuàng)建好后我們首先對 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ùn)行報(bào)錯(cuò)

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

mapper:用于存放dao層接口

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

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

controller:用于存放controller控制層

接下來我們開始編寫代碼

首先是實(shí)體類

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;
    //表頭數(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ù)開始。。。。。。");
        //查詢數(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ù)開始。。。。。。");
        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();
    }
}

工具類

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)出解析開始,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)建表頭名稱
            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寫入到輸出流中
            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)入解析開始,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++) {
                //過濾表頭行
                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;
    }
    //測試導(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ù)查詢
    //@ResponseBody
    @RequestMapping("/pojos_bing")
    public List<User> gotoIndex() {
        List<User> pojos = excelService.find();
        return pojos;
    }
}

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

寫了一個(gè)簡單前端用于測試

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í)瀏覽器會自動下載

當(dāng)我們點(diǎn)擊導(dǎo)入按鈕時(shí)會往數(shù)據(jù)庫中添加表格數(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)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • spring?NamedContextFactory在Fegin配置及使用詳解

    spring?NamedContextFactory在Fegin配置及使用詳解

    在我們?nèi)粘m?xiàng)目中,使用FeignClient實(shí)現(xiàn)各系統(tǒng)接口調(diào)用變得更加簡單,?在各個(gè)系統(tǒng)集成過程中,難免會遇到某些系統(tǒng)的Client需要特殊的配置、返回讀取等需求。Feign使用NamedContextFactory來為每個(gè)Client模塊構(gòu)造單獨(dú)的上下文(ApplicationContext)
    2023-11-11
  • SpringBoot請求參數(shù)接收方式

    SpringBoot請求參數(shù)接收方式

    這篇文章主要介紹了SpringBoot請求參數(shù)接收方式,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-02-02
  • 解讀synchronized鎖的釋放機(jī)制

    解讀synchronized鎖的釋放機(jī)制

    這篇文章主要介紹了synchronized鎖的釋放機(jī)制,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2025-04-04
  • Springboot jar運(yùn)行時(shí)如何將jar內(nèi)的文件拷貝到文件系統(tǒng)中

    Springboot jar運(yùn)行時(shí)如何將jar內(nèi)的文件拷貝到文件系統(tǒng)中

    因?yàn)閳?zhí)行需要,需要把jar內(nèi)templates文件夾下的的文件夾及文件加壓到宿主機(jī)器的某個(gè)路徑下,以便執(zhí)行對應(yīng)的腳本文件,這篇文章主要介紹了Springboot jar運(yùn)行時(shí)如何將jar內(nèi)的文件拷貝到文件系統(tǒng)中,需要的朋友可以參考下
    2024-06-06
  • springboot static關(guān)鍵字真能提高Bean的優(yōu)先級(厲害了)

    springboot static關(guān)鍵字真能提高Bean的優(yōu)先級(厲害了)

    這篇文章主要介紹了springboot static關(guān)鍵字真能提高Bean的優(yōu)先級(厲害了),需要的朋友可以參考下
    2020-07-07
  • Java基礎(chǔ)教程_判斷語句if else

    Java基礎(chǔ)教程_判斷語句if else

    下面小編就為大家?guī)硪黄狫ava基礎(chǔ)教程_判斷語句if else。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2016-06-06
  • Git和Maven的子模塊簡單實(shí)踐

    Git和Maven的子模塊簡單實(shí)踐

    今天小編就為大家分享一篇關(guān)于Git和Maven的子模塊簡單實(shí)踐,小編覺得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來看看吧
    2018-12-12
  • Spring MVC整合Shiro權(quán)限控制的方法

    Spring MVC整合Shiro權(quán)限控制的方法

    這篇文章主要介紹了Spring MVC整合Shiro權(quán)限控制,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2018-05-05
  • Java鎖機(jī)制Lock用法示例

    Java鎖機(jī)制Lock用法示例

    這篇文章主要介紹了Java鎖機(jī)制Lock用法,結(jié)合具體實(shí)例形式分析了Java鎖機(jī)制的相關(guān)上鎖、釋放鎖、隱式鎖、顯式鎖等概念與使用技巧,需要的朋友可以參考下
    2018-08-08
  • Spring Boot啟動過程(五)之Springboot內(nèi)嵌Tomcat對象的start教程詳解

    Spring Boot啟動過程(五)之Springboot內(nèi)嵌Tomcat對象的start教程詳解

    這篇文章主要介紹了Spring Boot啟動過程(五)之Springboot內(nèi)嵌Tomcat對象的start的相關(guān)資料,需要的朋友可以參考下
    2017-04-04

最新評論

永寿县| 临泉县| 外汇| 邢台市| 尤溪县| 柳州市| 长岛县| 金乡县| 大姚县| 甘谷县| 大余县| 临湘市| 长宁县| 建始县| 瑞昌市| 蒙山县| 镇巴县| 全州县| 高密市| 杨浦区| 武乡县| 凤翔县| 息烽县| 鱼台县| 岢岚县| 贵州省| 五莲县| 商南县| 临泉县| 盖州市| 蒲江县| 余江县| 包头市| 修武县| 浙江省| 民和| 聂荣县| 舟山市| 巍山| 无为县| 沅江市|