poi_04_整合项目

实体类

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Stu {
    private Integer stuId;
    private String stuName;
    private Integer stuSex;
    private Date stuBir;
}

1:导出

点击按钮,将数据导出为excel文件。
通常在列表页面,添加下载按钮;

 <a href="${path}/poi/exportPoi.do">导出</a>
@Controller
@RequestMapping("poi")
public class PoiController {

    @Autowired
    private PoiService poiService;

    @ResponseBody
    @RequestMapping("exportPoi")
    public void exportPoi(HttpServletResponse response){

        //告诉浏览器 响应的内容,
        response.setContentType("application/x-execl");
        ServletOutputStream outputStream = null;

        //将接受到的文件,作为一个附件 弹出来 给别人下载  需要设置它的header
        //setHeader("设置响应头","默认的文件名") new String 防止乱码
        try {
            response.setHeader("Content-Disposition", "attachment;filename=" + new String("学生名单.xlsx".getBytes(), "ISO-8859-1"));
            outputStream = response.getOutputStream();

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //创建输出流
        poiService.exportPoi(outputStream);
    }

}

service接口

 void exportPoi(ServletOutputStream outputStream);

service实现类

 @Override
    public void exportPoi(ServletOutputStream outputStream) {
        List<Stu> list = poiMapper.list();

        XSSFWorkbook wb = new XSSFWorkbook();


        //创建样式
        XSSFCellStyle cellStyle = wb.createCellStyle();


        XSSFSheet sheet = wb.createSheet("学生信息");

        //表头
        XSSFRow row1 = sheet.createRow(0);//创建行
        row1.createCell(0).setCellValue("编号");//创建单元格,
        row1.createCell(1).setCellValue("姓名");//创建单元格,
        row1.createCell(2).setCellValue("性别");//创建单元格,
        row1.createCell(3).setCellValue("生日");//创建单元格,

        for (int i = 0; i < list.size(); i++) {
            XSSFRow row = sheet.createRow(i+1);
            row.createCell(0).setCellValue(list.get(i).getStuId());//创建单元格,
            row.createCell(1).setCellValue(list.get(i).getStuName());//创建单元格,
            row.createCell(2).setCellValue(list.get(i).getStuSex());//创建单元格,

            //修改单元格的样式
            XSSFCell dataCell = row.createCell(3);//获取的第三个单元
            dataCell.setCellStyle(setDadeFmart(wb,cellStyle));//给单元格赋样式
            dataCell.setCellValue(list.get(i).getStuBir());//创建单元格,

            //设置列宽 256*15
            sheet.setColumnWidth(3,15*256);

        }
        //设置居中
        cellStyle.setAlignment(HorizontalAlignment.CENTER);

        //设置字体颜色
        XSSFFont font = wb.createFont();
        font.setColor(Font.COLOR_RED);
        cellStyle.setFont(font);

        //FileOutputStream fileOut = null;
        try {
            //fileOut = new FileOutputStream("E:\\mingrui\\1808\\demo2.xlsx");
            wb.write(outputStream);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(outputStream != null){
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    public static XSSFCellStyle setDadeFmart(XSSFWorkbook wb,XSSFCellStyle cellStyle){

        //日期类型
        //获得CreationHelper对象,这个应该是一个帮助类
        XSSFCreationHelper creationHelper = wb.getCreationHelper();
        //通过 creationHelper 获取时间格式的 short值
        short dateFormat = creationHelper.createDataFormat().getFormat("yyyy-MM-dd");
        //通过setDataFormat(short值)获取单元格的格式,具体使用什么格式,有参数决定;
        cellStyle.setDataFormat(dateFormat);

        return cellStyle;
    }

2:导入

springmvc文件上传
1)jsp页面的内容

<form action="${path}/poi/importPoi.do" method="post" enctype="multipart/form-data">
        <input type="file" name="excelFile">
        <br>
        <input type="submit" value="上传">
    </form>

2)controller方法

@ResponseBody
    @RequestMapping("importPoi")
    public void importPoi(MultipartFile excelFile){
        poiService.importPoi(excelFile);
        
    }

serviceImpl

@Override
    public void importPoi(MultipartFile excelFile) {
        try {
            String filename = excelFile.getOriginalFilename();//获取文件名
            Workbook wb = null;
            if(filename.indexOf(".xlsx")== -1){//没有xlsx ,说明是03
                wb = new HSSFWorkbook(excelFile.getInputStream());
            }else{//07
                wb = new XSSFWorkbook(excelFile.getInputStream());
            }

            Sheet sheetAt = wb.getSheetAt(0);

            //获取到有效的行数
            //通过getLastRowNum() 获取到有效的行数--下标
            //int lastRowNum = sheetAt.getLastRowNum();
            //通过 getPhysicalNumberOfRows 方法获取到行号
            int rowNum = sheetAt.getPhysicalNumberOfRows();

            System.out.println(rowNum);

            List<Stu> stus = new ArrayList<>();

            for (int i = 1; i < rowNum; i++) {//i代表行号
                Row row = sheetAt.getRow(i);

                Double id = row.getCell(0).getNumericCellValue();
                String name = row.getCell(1).getStringCellValue();
                Double sex = row.getCell(2).getNumericCellValue();
                Date bir = row.getCell(3).getDateCellValue();

                //将数据存放在对象中
                Stu stu = new Stu();
                stu.setStuId(id.intValue());
                stu.setStuName(name);
                stu.setStuSex(sex.intValue());
                stu.setStuBir(bir);

                //直接添加在数据库(但是效率太低),直接添加在list集合中。
                stus.add(stu);
            }

            //把集合传入mapper 批量插入
            poiMapper.importPoi(stus);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

mapper

<insert id="importPoi">
        insert into t_stu (stu_name, stu_sex,stu_bir)  values
        <foreach collection="stus" separator=","  item="stu">
            (#{stu.stuName},#{stu.stuSex},#{stu.stuBir})
        </foreach>
    </insert>

猜你喜欢

转载自blog.csdn.net/m0_37392489/article/details/86489172