Apache POI处理Excel文档

437 阅读2分钟

1、导包

pom.xml

<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>3.17</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>3.17</version>
</dependency>

2、编写POI工具类

public class POIUtil {
    /**
     * 获取XSSFWorkbook对象
     * @param sheetName sheet名称
     * @param title 标题
     * @param values 内容
     * @param wb XSSFWorkbook对象
     * @return
     */
    public static XSSFWorkbook getXSSFWorkbook(String sheetName, String []title, String[][]values, XSSFWorkbook wb){
        //1.创建一个HSSFWorkbook,对应一个Excel文件
        if(wb==null){
            wb=new XSSFWorkbook();//todo 创建工作簿
        }
        //2.在workbook中添加一个sheet,对应Excel文件中的sheet
        XSSFSheet sheet = wb.createSheet(sheetName);
        //3.在sheet中添加表头第0行
        //创建一行并在其中放入一些单元格。行数为0
        XSSFRow row = sheet.createRow(0); 
        //4.创建单元格,并设置值表头 设置表头居中
        XSSFCellStyle style = wb.createCellStyle();
        style.setAlignment(HorizontalAlignment.CENTER);

        //todo 声明列对象
        XSSFCell cell=null;
        //todo 创建标题
        for(int i=0;i<title.length;i++){
            //todo 创建一个单元格并在其中放置一个值。
            cell=row.createCell(i);
            cell.setCellValue(title[i]);
            cell.setCellStyle(style);
        }
        //todo 创建内容
        for(int i=0;i<values.length;i++){
            row=sheet.createRow(i+1);
            for(int j=0;j<values[i].length;j++){
                //todo 将内容按顺序赋给对应的列对象
                row.createCell(j).setCellValue(values[i][j]);
            }
        }
        return wb;
    }
    
    /**
     * 设置响应头
     * @param response
     * @param fileName
     */
    public static void setResponseHeader(HttpServletResponse response, String fileName){
        try {
            try {
                fileName=new String(fileName.getBytes(),"ISO8859-1");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            response.setContentType("application/octet-stream;charset=ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename="+ fileName);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

3、测试导出

@Controller
@RequestMapping("/poi")
public class POIController {
    @RequestMapping("/ts")
    public void POITest(List<Student> list,HttpServletRequest request, HttpServletResponse response){
        //1、excel标题,list中封装的student对象对应的数据
        String[]title={"名称","性别","年龄","学校","班级"};
        //2、excel文件名
        String fileName="学生信息表"+System.currentTimeMillis()+".xls";
        //3、sheet名
        String sheetName="学生信息表";
        String [][]content=new String[list.size()][];
        for(int i=0;i<list.size();i++){
            content[i] = new String[title.length];
            int temp=0;
            Student student=list.get(i);
            content[i][temp++]=student.getStuName();
            content[i][temp++]=student.getStuSex();
            content[i][temp++]=student.getStuAge();
            content[i][temp++]=student.getStuSchoolName();
            content[i][temp++]=student.getStuClassName();
        }
        //4、创建XSSFWorkbook
        XSSFWorkbook wb= POIUtil.getXSSFWorkbook(sheetName,title,content,null);
        //5、响应到客户端
        try {
            POIUtil.setResponseHeader(response,fileName);
            OutputStream os=response.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}    

4、测试导入

static XSSFRow row;
    public static void main(String[] args) throws Exception{
        FileInputStream fis = new FileInputStream(
                new File("C:\\Users\\Administrator\\Desktop\\学生信息表1541144581002.xls"));
        //打开需要读取的文件
        XSSFWorkbook workbook = new XSSFWorkbook(fis);
        //按照SHEET的名称读取一个电子表格
        XSSFSheet sheet = workbook.getSheet("学生信息表");
//      int size = sheet.getLastRowNum();
//      System.out.println(size);
//      int s= sheet.getPhysicalNumberOfRows();
//      System.out.println(s);
        //获取一个行的迭代器
        Iterator<Row> rowIterator = sheet.rowIterator();
        while(rowIterator.hasNext()) {
            row = (XSSFRow) rowIterator.next();
            Iterator<Cell> cellIterator = row.cellIterator();
            while(cellIterator.hasNext()) {
                Cell cell = cellIterator.next();
                switch(cell.getCellTypeEnum() ) {
                    case NUMERIC:
                        double val = cell.getNumericCellValue();
                        System.out.print(val+"\t\t");
                        break ;
                    case STRING:
                        String str = cell.getStringCellValue();
                        System.out.print(str+"\t\t");

                }
            }
            System.out.println();
        }
        fis.close();
    }