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

SpringBoot集成POI實現(xiàn)Excel導(dǎo)入導(dǎo)出的示例詳解

 更新時間:2022年07月22日 11:56:52   作者:pdai  
Apache?POI?是用Java編寫的免費開源的跨平臺的?Java?API,Apache?POI提供API給Java程序?qū)icrosoft?Office格式檔案讀和寫的功能。本文主要介紹通過SpringBoot集成POI工具實現(xiàn)Excel的導(dǎo)入和導(dǎo)出功能,需要的可以參考一下

知識準(zhǔn)備

需要了解POI工具,以及POI對Excel中的對象的封裝對應(yīng)關(guān)系。

什么是POI

Apache POI 是用Java編寫的免費開源的跨平臺的 Java API,Apache POI提供API給Java程序?qū)icrosoft Office格式檔案讀和寫的功能。POI為“Poor Obfuscation Implementation”的首字母縮寫,意為“簡潔版的模糊實現(xiàn)”。

Apache POI 是創(chuàng)建和維護(hù)操作各種符合Office Open XML(OOXML)標(biāo)準(zhǔn)和微軟的OLE 2復(fù)合文檔格式(OLE2)的Java API。用它可以使用Java讀取和創(chuàng)建,修改MS Excel文件.而且,還可以使用Java讀取和創(chuàng)建MS Word和MSPowerPoint文件。更多請參考官方文檔。

POI中基礎(chǔ)概念

生成xls和xlsx有什么區(qū)別?POI對Excel中的對象的封裝對應(yīng)關(guān)系?

生成xls和xlsx有什么區(qū)別呢?

XLSXLSX
只能打開xls格式,無法直接打開xlsx格式可以直接打開xls、xlsx格式
只有65536行、256列可以有1048576行、16384列
占用空間大占用空間小,運算速度也會快一點

POI對Excel中的對象的封裝對應(yīng)關(guān)系如下:

ExcelPOI XLSPOI XLSX(Excel 2007+)
Excel 文件HSSFWorkbook (xls)XSSFWorkbook(xlsx)
Excel 工作表HSSFSheetXSSFSheet
Excel 行HSSFRowXSSFRow
Excel 單元格HSSFCellXSSFCell
Excel 單元格樣式HSSFCellStyleHSSFCellStyle
Excel 顏色HSSFColorXSSFColor
Excel 字體HSSFFontXSSFFont

實現(xiàn)案例

這里展示SpringBoot集成POI導(dǎo)出用戶列表的和導(dǎo)入用戶列表的例子。

Pom依賴

引入poi的依賴包

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

導(dǎo)出Excel

UserController中導(dǎo)出的方法

@ApiOperation("Download Excel")
@GetMapping("/excel/download")
public void download(HttpServletResponse response) {
    try {
        SXSSFWorkbook workbook = userService.generateExcelWorkbook();
        response.reset();
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-disposition",
                "attachment;filename=user_excel_" + System.currentTimeMillis() + ".xlsx");
        OutputStream os = response.getOutputStream();
        workbook.write(os);
        workbook.dispose();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

UserServiceImple中導(dǎo)出Excel的主方法

private static final int POSITION_ROW = 1;
private static final int POSITION_COL = 1;

/**
  * @return SXSSFWorkbook
  */
@Override
public SXSSFWorkbook generateExcelWorkbook() {
    SXSSFWorkbook workbook = new SXSSFWorkbook();
    Sheet sheet = workbook.createSheet();

    int rows = POSITION_ROW;
    int cols = POSITION_COL;

    // 表頭
    Row head = sheet.createRow(rows++);
    String[] columns = new String[]{"ID", "Name", "Email", "Phone", "Description"};
    int[] colWidths = new int[]{2000, 3000, 5000, 5000, 8000};
    CellStyle headStyle = getHeadCellStyle(workbook);
    for (int i = 0; i < columns.length; ++i) {
        sheet.setColumnWidth(cols, colWidths[i]);
        addCellWithStyle(head, cols++, headStyle).setCellValue(columns[i]);
    }

    // 表內(nèi)容
    CellStyle bodyStyle = getBodyCellStyle(workbook);
    for (User user : getUserList()) {
        cols = POSITION_COL;
        Row row = sheet.createRow(rows++);
        addCellWithStyle(row, cols++, bodyStyle).setCellValue(user.getId());
        addCellWithStyle(row, cols++, bodyStyle).setCellValue(user.getUserName());
        addCellWithStyle(row, cols++, bodyStyle).setCellValue(user.getEmail());
        addCellWithStyle(row, cols++, bodyStyle).setCellValue(String.valueOf(user.getPhoneNumber()));
        addCellWithStyle(row, cols++, bodyStyle).setCellValue(user.getDescription());
    }
    return workbook;
}

private Cell addCellWithStyle(Row row, int colPosition, CellStyle cellStyle) {
    Cell cell = row.createCell(colPosition);
    cell.setCellStyle(cellStyle);
    return cell;
}

private List<User> getUserList() {
    return Collections.singletonList(User.builder()
            .id(1L).userName("pdai").email("pdai@pdai.tech").phoneNumber(121231231231L)
            .description("hello world")
            .build());
}

private CellStyle getHeadCellStyle(Workbook workbook) {
    CellStyle style = getBaseCellStyle(workbook);

    // fill
    style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
    style.setFillPattern(FillPatternType.SOLID_FOREGROUND);

    return style;
}

private CellStyle getBodyCellStyle(Workbook workbook) {
    return getBaseCellStyle(workbook);
}

private CellStyle getBaseCellStyle(Workbook workbook) {
    CellStyle style = workbook.createCellStyle();

    // font
    Font font = workbook.createFont();
    font.setBold(true);
    style.setFont(font);

    // align
    style.setAlignment(HorizontalAlignment.CENTER);
    style.setVerticalAlignment(VerticalAlignment.TOP);

    // border
    style.setBorderBottom(BorderStyle.THIN);
    style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
    style.setBorderLeft(BorderStyle.THIN);
    style.setLeftBorderColor(IndexedColors.BLACK.getIndex());
    style.setBorderRight(BorderStyle.THIN);
    style.setRightBorderColor(IndexedColors.BLACK.getIndex());
    style.setBorderTop(BorderStyle.THIN);
    style.setTopBorderColor(IndexedColors.BLACK.getIndex());

    return style;
}

導(dǎo)出后的excel如下

導(dǎo)入Excel

我們將上面導(dǎo)出的excel文件導(dǎo)入。

UserController中導(dǎo)入的方法

@ApiOperation("Upload Excel")
@PostMapping("/excel/upload")
public ResponseResult<String> upload(@RequestParam(value = "file", required = true) MultipartFile file) {
    try {
        userService.upload(file.getInputStream());
    } catch (Exception e) {
        e.printStackTrace();
        return ResponseResult.fail(e.getMessage());
    }
    return ResponseResult.success();
}

UserServiceImple中導(dǎo)入Excel的主方法

@Override
public void upload(InputStream inputStream) throws IOException {
    XSSFWorkbook book = new XSSFWorkbook(inputStream);
    XSSFSheet sheet = book.getSheetAt(0);
    // add some validation here

    // parse data
    int cols;
    for (int i = POSITION_ROW; i < sheet.getLastRowNum(); i++) {
        XSSFRow row = sheet.getRow(i + 1); // 表頭不算
        cols = POSITION_COL;
        User user = User.builder()
                .id(getCellLongValue(row.getCell(cols++)))
                .userName(getCellStringValue(row.getCell(cols++)))
                .email(getCellStringValue(row.getCell(cols++)))
                .phoneNumber(Long.parseLong(getCellStringValue(row.getCell(cols++))))
                .description(getCellStringValue(row.getCell(cols++)))
                .build();
        log.info(user.toString());
    }

    book.close();
}

private String getCellStringValue(XSSFCell cell) {
    try {
        if (null!=cell) {
            return String.valueOf(cell.getStringCellValue());
        }
    } catch (Exception e) {
        return String.valueOf(getCellIntValue(cell));
    }
    return "";
}

private long getCellLongValue(XSSFCell cell) {
    try {
        if (null!=cell) {
            return Long.parseLong("" + (long) cell.getNumericCellValue());
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return 0L;
}

private int getCellIntValue(XSSFCell cell) {
    try {
        if (null!=cell) {
            return Integer.parseInt("" + (int) cell.getNumericCellValue());
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return 0;
}

通過PostMan進(jìn)行接口測試

執(zhí)行接口后,后臺的日志如下

2022-06-10 21:36:01.720  INFO 15100 --- [nio-8080-exec-2] t.p.s.f.e.p.s.impl.UserServiceImpl       : User(id=1, userName=pdai, email=pdai@pdai.tech, phoneNumber=121231231231, description=hello world)

示例源碼

https://github.com/realpdai/tech-pdai-spring-demos

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

相關(guān)文章

  • Java SpringBoot模板引擎之 Thymeleaf入門詳解

    Java SpringBoot模板引擎之 Thymeleaf入門詳解

    jsp有著強(qiáng)大的功能,能查出一些數(shù)據(jù)轉(zhuǎn)發(fā)到JSP頁面以后,我們可以用jsp輕松實現(xiàn)數(shù)據(jù)的顯示及交互等,包括能寫Java代碼。但是,SpringBoot首先是以jar的方式,不是war;其次我們的tomcat是嵌入式的,所以現(xiàn)在默認(rèn)不支持jsp
    2021-10-10
  • java判斷是否空最簡單的方法

    java判斷是否空最簡單的方法

    在本篇文章里小編給大家整理的一篇關(guān)于java判斷是否空最簡單的方法,有興趣的讀者們可以參考下。
    2019-12-12
  • Java中如何實現(xiàn)不可變Map詳解

    Java中如何實現(xiàn)不可變Map詳解

    這篇文章主要給大家介紹了關(guān)于Java中如何實現(xiàn)不可變Map的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作工具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2018-12-12
  • springboot動態(tài)注入配置與docker設(shè)置環(huán)境變量的方法

    springboot動態(tài)注入配置與docker設(shè)置環(huán)境變量的方法

    這篇文章主要介紹了springboot動態(tài)注入配置與docker設(shè)置環(huán)境變量的方法,本文通過實例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2023-04-04
  • java使用es查詢的示例代碼

    java使用es查詢的示例代碼

    本篇文章主要介紹了java使用es查詢的示例代碼,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2018-01-01
  • Java????????HashMap遍歷方法匯總

    Java????????HashMap遍歷方法匯總

    這篇文章主要介紹了Java????????HashMap遍歷方法匯總,HashMap?的遍歷方法有很多種,不同的?JDK?版本有不同的寫法,下文關(guān)于其遍歷方法總結(jié)需要的小伙伴可以參考一下
    2022-05-05
  • 淺談對象數(shù)組或list排序及Collections排序原理

    淺談對象數(shù)組或list排序及Collections排序原理

    下面小編就為大家?guī)硪黄獪\談對象數(shù)組或list排序及Collections排序原理。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2016-09-09
  • Automapper實現(xiàn)自動映射的實例代碼

    Automapper實現(xiàn)自動映射的實例代碼

    這篇文章主要介紹了Automapper實現(xiàn)自動映射的實例代碼,需要的朋友可以參考下
    2017-09-09
  • spring mvc實現(xiàn)登錄賬號單瀏覽器登錄

    spring mvc實現(xiàn)登錄賬號單瀏覽器登錄

    這篇文章主要為大家詳細(xì)介紹了spring mvc實現(xiàn)登錄賬號單瀏覽器登錄,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2017-04-04
  • Java pom.xml parent引用報錯問題解決方案

    Java pom.xml parent引用報錯問題解決方案

    這篇文章主要介紹了Java pom.xml parent引用報錯問題解決方案,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2020-08-08

最新評論

左云县| 隆昌县| 宜君县| 社旗县| 青河县| 屏山县| 兴宁市| 太湖县| 富源县| 泸州市| 仁怀市| 星座| 包头市| 镇安县| 宜春市| 昌平区| 禹州市| 温泉县| 卓尼县| 甘孜| 神木县| 托里县| 漾濞| 通州市| 宁德市| 襄樊市| 库尔勒市| 宁津县| 喜德县| 定兴县| 通州区| 临漳县| 沙坪坝区| 嘉兴市| 新余市| 含山县| 新河县| 两当县| 临洮县| 广昌县| 静乐县|