内射老阿姨1区2区3区4区_久久精品人人做人人爽电影蜜月_久久国产精品亚洲77777_99精品又大又爽又粗少妇毛片

Java如何利用POI實(shí)現(xiàn)導(dǎo)入導(dǎo)出Excel表格

這篇文章主要介紹“Java如何利用POI實(shí)現(xiàn)導(dǎo)入導(dǎo)出Excel表格”的相關(guān)知識(shí),小編通過實(shí)際案例向大家展示操作過程,操作方法簡(jiǎn)單快捷,實(shí)用性強(qiáng),希望這篇“Java如何利用POI實(shí)現(xiàn)導(dǎo)入導(dǎo)出Excel表格”文章能幫助大家解決問題。

安居ssl適用于網(wǎng)站、小程序/APP、API接口等需要進(jìn)行數(shù)據(jù)傳輸應(yīng)用場(chǎng)景,ssl證書未來市場(chǎng)廣闊!成為創(chuàng)新互聯(lián)建站的ssl證書銷售渠道,可以享受市場(chǎng)價(jià)格4-6折優(yōu)惠!如果有意向歡迎電話聯(lián)系或者加微信:18980820575(備注:SSL證書合作)期待與您的合作!

一、Java利用POI實(shí)現(xiàn)導(dǎo)入導(dǎo)出Excel表格demo

1.引入依賴

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

2.導(dǎo)入demo

2.1 controller層

/**
     * Excel導(dǎo)入 
     */
    @PostMapping("/import")
    public Result userImport2(@RequestParam("file") MultipartFile file) throws Exception{
        Result result=userService.userImportExcel(file);
        return result;
    }

2.2 service實(shí)現(xiàn)類層

public Result userImportExcel(MultipartFile file){
    try {
        InputStream inputStream = file.getInputStream();
        XSSFWorkbook sheets = new XSSFWorkbook(inputStream);
        //獲取表單sheet 第一個(gè)
        XSSFSheet sheetAt = sheets.getSheetAt(0);
        //獲取第一行
        int firstRowNum = sheetAt.getFirstRowNum();
        //最后一行
        int lastRowNum = sheetAt.getLastRowNum();
        //存入數(shù)據(jù)集合
        List<User> users=new ArrayList<>();
        //遍歷數(shù)據(jù)
        for(int i=firstRowNum+1;i<lastRowNum+1;i++){
            XSSFRow row = sheetAt.getRow(i);
            if(row!=null){
               /* //獲取第一行的第一列
                int firstCellNum = row.getFirstCellNum();
                //獲取第一行的最后列
                short lastCellNum = row.getLastCellNum();
                for (int j=firstCellNum;j<lastCellNum+1;j++){
                    //放入集合中需要可以用這種方法
                    String cellValue = getValue(row.getCell(firstCellNum));
                }*/
                //這里我就直接賦值
                User user = new User();
                user.setUname(row.getCell(0).getStringCellValue());
                user.setUpassword(row.getCell(1).getStringCellValue());
                user.setUsex(row.getCell(2).getStringCellValue());
                user.setRole(row.getCell(3).getStringCellValue());
                user.setUlove((int) row.getCell(4).getNumericCellValue());
                user.setUphoto(row.getCell(5).getStringCellValue());
                user.setUaddress(row.getCell(6).getStringCellValue());
                users.add(user);
            }
        }
        //保存數(shù)據(jù)
        saveBatch(users);
        return Result.success();
    }catch (Exception e){
        e.printStackTrace();
        log.info("error:{}",e);
    }

    return Result.error("300","導(dǎo)入失敗");
}

/**
 * 判斷值的類型
 */
public String getValue(HSSFCell cell) {

    if(cell==null){
        return "";
    }
    String cellValue= "";
    try {
        DecimalFormat df=new DecimalFormat("0.00");
        if(cell.getCellType()== CellType.NUMERIC){
            //日期時(shí)間轉(zhuǎn)換
            if(HSSFDateUtil.isCellDateFormatted(cell)){
                cellValue=DateFormatUtils.format(cell.getDateCellValue(),"yyyy-MM-dd");
            }else{
                NumberFormat instance = NumberFormat.getInstance();
                cellValue=instance.format(cell.getNumericCellValue()).replace(",","");
            }

        }else if(cell.getCellType() == CellType.STRING){
            //字符串
            cellValue=cell.getStringCellValue();
        }else if(cell.getCellType() == CellType.BOOLEAN){
            //Boolean
            cellValue= String.valueOf(cell.getBooleanCellValue());
        }else if(cell.getCellType() == CellType.ERROR){
            //錯(cuò)誤
        }else if(cell.getCellType() == CellType.FORMULA){
            //轉(zhuǎn)換公式 保留兩位
            cellValue=df.format(cell.getNumericCellValue());
        }else{
            cellValue=null;
        }

    } catch (Exception e) {
        e.printStackTrace();
        cellValue="-1";
    }

    return cellValue;
}

3.導(dǎo)出demo

3.1 controller層

/**
 * 導(dǎo)出 
 * @param response
 * @return
 * @throws Exception
 */
@GetMapping("/export")
public Result userExport2(HttpServletResponse response) throws Exception{
    Result result=userService.userExportExcel(response);
    return result;
}

3.2 service實(shí)現(xiàn)類

public Result userExportExcel(HttpServletResponse response) {
    try {
        //創(chuàng)建excel
        XSSFWorkbook sheets = new XSSFWorkbook();
        //創(chuàng)建行
        XSSFSheet sheet = sheets.createSheet("用戶信息");
        //格式設(shè)置
        XSSFCellStyle cellStyle = sheets.createCellStyle();
        //橫向居中
        cellStyle.setAlignment(HorizontalAlignment.CENTER);
        //創(chuàng)建單元格第一列
        XSSFRow row = sheet.createRow(0);
        //表頭
        this.titleExcel(row,cellStyle);
        //查詢?nèi)康挠脩魯?shù)據(jù)  mybatis-plus
        List<User> list = list();
        //遍歷設(shè)置值
        for(int i=0;i<list.size();i++){
            XSSFRow rows = sheet.createRow(i+1);
            User user=list.get(i);
            //表格里賦值
            this.titleExcelValue(user,rows,cellStyle);
        }
        //設(shè)置瀏覽器響應(yīng)格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String filName= URLEncoder.encode("用戶信息","UTF-8");
        response.setHeader("Content-Disposition","attachment;filename="+filName+".xls");

        ServletOutputStream outputStream=response.getOutputStream();
        sheets.write(outputStream);
        outputStream.close();
        sheets.close();
        return Result.success();

    }catch (Exception e){
        e.printStackTrace();
        log.info("error:{}",e);
    }

    return Result.error("300","導(dǎo)出失敗");
}

/**
*表格里賦值
**/
public void titleExcelValue(User user, XSSFRow row,XSSFCellStyle cellStyle) {
    XSSFCell cellId = row.createCell(0);
    cellId.setCellValue(user.getUid());
    cellId.setCellStyle(cellStyle);

    XSSFCell cellUserName = row.createCell(1);
    cellUserName.setCellValue(user.getUname());
    cellUserName.setCellStyle(cellStyle);

    XSSFCell cellPassword = row.createCell(2);
    cellPassword.setCellValue(user.getUpassword());
    cellPassword.setCellStyle(cellStyle);

    XSSFCell cellSex = row.createCell(3);
    cellSex.setCellValue(user.getUsex());
    cellSex.setCellStyle(cellStyle);

    XSSFCell cellRole = row.createCell(4);
    cellRole.setCellValue(user.getRole());
    cellRole.setCellStyle(cellStyle);

    XSSFCell cellLoveValue = row.createCell(5);
    cellLoveValue.setCellValue(user.getRole());
    cellLoveValue.setCellStyle(cellStyle);

    XSSFCell cellPhone = row.createCell(6);
    cellPhone.setCellValue(user.getUphoto());
    cellPhone.setCellStyle(cellStyle);

    XSSFCell cellAddress = row.createCell(7);
    cellAddress.setCellValue(user.getUaddress());
    cellAddress.setCellStyle(cellStyle);


}
/**
    表頭
**/
public void titleExcel(XSSFRow row,XSSFCellStyle cellStyle){

    XSSFCell cellId = row.createCell(0);
    cellId.setCellValue("用戶ID");
    cellId.setCellStyle(cellStyle);

    XSSFCell cellUserName = row.createCell(1);
    cellUserName.setCellValue("用戶名");
    cellUserName.setCellStyle(cellStyle);

    XSSFCell cellPassword = row.createCell(2);
    cellPassword.setCellValue("密碼");
    cellPassword.setCellStyle(cellStyle);

    XSSFCell cellSex = row.createCell(3);
    cellSex.setCellValue("性別");
    cellSex.setCellStyle(cellStyle);

    XSSFCell cellRole = row.createCell(4);
    cellRole.setCellValue("角色");
    cellRole.setCellStyle(cellStyle);

    XSSFCell cellLoveValue = row.createCell(5);
    cellLoveValue.setCellValue("愛心值");
    cellLoveValue.setCellStyle(cellStyle);

    XSSFCell cellPhone = row.createCell(6);
    cellPhone.setCellValue("電話號(hào)碼");
    cellPhone.setCellStyle(cellStyle);

    XSSFCell cellAddress = row.createCell(7);
    cellAddress.setCellValue("地址");
    cellAddress.setCellStyle(cellStyle);

}
二、Hutool工具類封裝方法導(dǎo)出導(dǎo)入Excel

1.引入依賴

把poi封裝到工具類方法里面

<!-- hutool  -->
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.7.20</version>
        </dependency>

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

2.導(dǎo)入demo

/**
     * Excel導(dǎo)入 
*/
@PostMapping("/import")
public Result userImport(@RequestParam("file") MultipartFile file) throws Exception{
        System.out.println(file.toString());
        //InputStream inputStream = multipartFile.getInputStream();
        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        //讀取表的內(nèi)容
        List<List<Object>> list = reader.read(1);
        List<User> users = new ArrayList<>();
        for(List<Object> row : list){
            User user = new User();
            user.setUname(row.get(0).toString());
            user.setUpassword(row.get(1).toString());
            user.setUsex(row.get(2).toString());
            user.setRole(row.get(3).toString());
            user.setUlove(Integer.valueOf(row.get(4).toString()));
            user.setUphoto(row.get(5).toString());
            user.setUaddress(row.get(6).toString());
            users.add(user);
        }
        //批量插入用戶信息 mybatis-plus
        userService.saveBatch(users);
        return Result.success();
    }

3.導(dǎo)出demo

 /**
     * Excel導(dǎo)出 方法一
     */
    @GetMapping("/export")
    public Result userExport(HttpServletResponse response) throws Exception{
        //查詢?nèi)康挠脩魯?shù)據(jù)
        List<User> list = userService.list();
        //在內(nèi)存里做操作,保存到瀏覽器
        ExcelWriter writer = ExcelUtil.getWriter(true);
        //自定義標(biāo)題別名
        writer.addHeaderAlias("uname","用戶名");
        writer.addHeaderAlias("upassword","密碼");
        writer.addHeaderAlias("usex","性別");
        writer.addHeaderAlias("role","角色");
        writer.addHeaderAlias("ulove","愛心值");
        writer.addHeaderAlias("uphoto","電話號(hào)碼");
        writer.addHeaderAlias("uaddress","地址");
        //一次性寫出list內(nèi)的對(duì)象的Excel,使用默認(rèn)樣式,強(qiáng)制輸出標(biāo)題
        writer.write(list,true);
        //設(shè)置瀏覽器響應(yīng)格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String filName= URLEncoder.encode("用戶信息","UTF-8");
        response.setHeader("Content-Disposition","attachment;filename="+filName+".xls");

        ServletOutputStream outputStream=response.getOutputStream();
        writer.flush(outputStream,true);
        outputStream.close();
        writer.close();
        return Result.success();
    }

關(guān)于“Java如何利用POI實(shí)現(xiàn)導(dǎo)入導(dǎo)出Excel表格”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識(shí),可以關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,小編每天都會(huì)為大家更新不同的知識(shí)點(diǎn)。

本文名稱:Java如何利用POI實(shí)現(xiàn)導(dǎo)入導(dǎo)出Excel表格
網(wǎng)站網(wǎng)址:http://www.rwnh.cn/article16/pgcgdg.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供服務(wù)器托管、網(wǎng)站建設(shè)、企業(yè)網(wǎng)站制作、ChatGPTApp開發(fā)、網(wǎng)站制作

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)

成都網(wǎng)站建設(shè)公司
若羌县| 深泽县| 科尔| 永兴县| 故城县| 增城市| 仪征市| 罗江县| 贡觉县| 塘沽区| 呈贡县| 迁安市| 扶沟县| 新民市| 广元市| 广灵县| 宁波市| 措美县| 庄浪县| 内江市| 拉孜县| 左云县| 交口县| 宁武县| 伊宁县| 临桂县| 交口县| 大丰市| 荣昌县| 慈溪市| 北安市| 沙河市| 旅游| 建瓯市| 枣阳市| 江川县| 蓬溪县| 秦安县| 六盘水市| 霍林郭勒市| 平果县|