0
点赞
收藏
分享

微信扫一扫

poi读取Excel

落拓尘嚣 2022-04-23 阅读 51
java

依赖

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml-schemas</artifactId>
    <version>3.8</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>3.8</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>3.8</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-scratchpad</artifactId>
    <version>3.8</version>
</dependency>

控制层方法

@ApiOperation(value = "Excel模板下载", notes = "Excel模板下载")
@GetMapping(value = "/downTemplateExcel", produces = { "application/json;charset=UTF-8" })
public void downTemplateExcel(HttpServletResponse servletResponse) throws IOException {
    excelService.downTemplateExcel(servletResponse);
}

@ApiOperation(value = "Excel模板导入", notes = "Excel模板导入")
@PostMapping(value = "/importExcel", produces = { "application/json;charset=UTF-8" })
public R importExcel(MultipartFile file) throws IOException {
    return excelService.importExcel(file);
}

业务逻辑层方法

import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.*;

@Service
@Transactional
public class ExcelService extends BaseServiceImpl<Excel> {
    //Excel模板下载
    public void downTemplateExcel(HttpServletResponse servletResponse) throws IOException {
        // 创建工作簿
        XSSFWorkbook workbook = new XSSFWorkbook();
        // 创建工作表
        XSSFSheet sheet = workbook.createSheet("sheet名称");
        // 创建行
        XSSFRow row = sheet.createRow(0);
        // 定义行高
        row.setHeightInPoints(30);
        // 设置字体样式
        XSSFFont font = workbook.createFont();
        font.setBoldweight(Font.BOLDWEIGHT_BOLD); // 字体加粗
        font.setFontHeightInPoints((short) 15); // 字号
        // 创建style
        XSSFCellStyle styletitle = workbook.createCellStyle();
        styletitle.setFont(font);
        styletitle.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 水平居中
        styletitle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); // 垂直居中

        XSSFCell celltitle = row.createCell(0); // 创建单元格
        row.createCell(0).setCellValue("第一列"); //给单元格填写内容
        celltitle.setCellStyle(styletitle);  //设置属性   以此类推,需要几列写几列,可以用switch case写

        celltitle = row.createCell(1);
        row.createCell(1).setCellValue("第二列");
        celltitle.setCellStyle(styletitle);

        celltitle = row.createCell(2);
        row.createCell(2).setCellValue("第三列");
        celltitle.setCellStyle(styletitle);

        celltitle = row.createCell(3);
        row.createCell(3).setCellValue("第四列");
        celltitle.setCellStyle(styletitle);

        celltitle = row.createCell(4);
        row.createCell(4).setCellValue("第五列");
        celltitle.setCellStyle(styletitle);

        celltitle = row.createCell(5);
        row.createCell(5).setCellValue("第六列");
        celltitle.setCellStyle(styletitle);

        celltitle = row.createCell(6);
        row.createCell(6).setCellValue("第七列");
        celltitle.setCellStyle(styletitle);

        celltitle = row.createCell(7);
        row.createCell(7).setCellValue("第八列");
        celltitle.setCellStyle(styletitle);

        celltitle = row.createCell(8);
        row.createCell(8).setCellValue("第九列");
        celltitle.setCellStyle(styletitle);

        celltitle = row.createCell(9);
        row.createCell(9).setCellValue("第十列");
        celltitle.setCellStyle(styletitle);

        for (int i = 0; i < 10; i++) {
            sheet.setColumnWidth(i, 21 * 256);
        }

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        workbook.write(out);
        servletResponse.setContentType("application/octet-stream");
//        servletResponse.setContentType("application/vnd.ms-excel");
        servletResponse.setHeader("Content-Disposition", "attachment;fileName=" +
                new String("模板名称.xlsx".getBytes("gbk"), "iso8859-1"));
        OutputStream os = servletResponse.getOutputStream();
        out.writeTo(os);
        out.flush();
        out.close();
        os.flush();
        os.close();
    }
    
    //导入Excel方法
    public R importExcel(MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        if (!originalFilename.endsWith(".xlsx"))
            return R.error("模板类型上传错误");
        // 创建工作簿
        XSSFWorkbook workbook = new XSSFWorkbook(file.getInputStream());
        // 创建工作表
        XSSFSheet sheet = workbook.getSheetAt(0);
        //创建一个存放实体类的list集合
        List<Excel> list = new ArrayList<>();
        // 获取行
        int rowCount = sheet.getPhysicalNumberOfRows();
        Row rowTitle = sheet.getRow(0);  //获取Excel第一行内容:标题
        if (rowTitle.getPhysicalNumberOfCells() != 10) //判断一下标题个数是不是满足导入的标准
            return R.error().message("模板数据格式错误");
        for (int i = 1; i < rowCount; i++) {    //遍历所有行,第一行是标题,所有不要从下标0开始
            int nullCount = 0;
            Row rowData = sheet.getRow(i);     //获取一行的信息内容
            if (rowData != null) {
                List<String> cellList = new ArrayList<>();
                // 读取列
//                int cellCount = rowData.getPhysicalNumberOfCells(); //获取一共有多少列
                for (int j = 0; j < 10; j++) {  //遍历一行中每列的数据, 写死10列,获取前十列信息,其他不考虑
                    Cell cell = rowData.getCell(j);    //获取每个单元格的数据
                    if (cell != null) {
                        int cellType = cell.getCellType();   //判断读取到的数据是什么类型,1代表字符串
                        if (cellType != 1)
                            cell.setCellType(1); //将不是字符串类型的变成字符串类型
                        String stringCellValue = cell.getStringCellValue();   //获取读取到的单元格的数据
                        if (!org.springframework.util.StringUtils.isEmpty(stringCellValue))    //将此行中的所有数据存储到cellList中,空的存null
                            cellList.add(stringCellValue);
                        else {
                            cellList.add(null);
                            nullCount += 1;
                        }
                    }else {
                        cellList.add(null);
                        nullCount += 1;
                    }
                }
                if (cellList.size() == 0 || cellList.size() == nullCount)  //要是cellList当中没有内容跳出此次循环进入下一次
                    continue;
                for (int j = 0; j < cellList.size(); j++) {   //遍历此行当中每个单元格的数据,并给实体对应的字段赋值
                    switch (j) {
                        case 0:
                            System.out.println(cellList.get(j));
                            break;
                        case 1:
                            System.out.println(cellList.get(j));
                            break;
                        case 2:
                            System.out.println(cellList.get(j));
                            break;
                        case 3:
                            System.out.println(cellList.get(j));
                            break;
                        case 4:
                            System.out.println(cellList.get(j));
                            break;
                        case 5:
                            System.out.println(cellList.get(j));
                            break;
                        case 6:
                            System.out.println(cellList.get(j));
                            break;
                        case 7:
                            System.out.println(cellList.get(j));
                            break;
                        case 8:
                            System.out.println(cellList.get(j));
                            break;
                        case 9:
                            System.out.println(cellList.get(j));
                            break;
                    }
                }
            }
        }
        return R.ok().message("导入成功!");
    } 
}

举报

相关推荐

0 条评论