Use Java to export the data into Excel spreadsheet format

Introduction: background processing approach using data derived in this paper show the front end of the table.

The introduction of dependence

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.17</version>
        </dependency>

Writing PoiUtils

public  class PoiUtils { 

    public   static ResponseEntity < byte []> exportExcel (List <Market> marketList) throws IOException { 
        HttpHeaders headers = null ;
         // create a document 
        HSSFWorkbook Workbook = new new HSSFWorkbook ();
         // Create excel document 
        HSSFSheet sheet = workbook. createSheet is ( "market table" ); 
  
        // define a column width 
        sheet.setColumnWidth (0, 256 *. 5 ); 
        sheet.setColumnWidth ( . 1, 10 * 256 ); 
        sheet.setColumnWidth ( 2, 256 * 10 );
        sheet.setColumnWidth(3, 10 * 256);
        sheet.setColumnWidth(4, 10 * 256);
        //设置表头
        HSSFRow headerRow = sheet.createRow(0);
        headerRow.createCell(0).setCellValue("编号");
        headerRow.createCell(1).setCellValue("主题");
        headerRow.createCell(2).setCellValue("预算");
        headerRow.createCell(3).setCellValue("线索");

        for (int i=0;i<marketList.size();i++){
            HSSFRow row = sheet.createRow(i+1);
            Market market = marketList.get(i);
            row.createCell(0).setCellValue(market.getId());
            row.createCell(1).setCellValue(market.getTheme());
            row.createCell(2).setCellValue(market.getbudget());
            row.createCell(3).setCellValue(market.getClue());
        }


        //将excel写入到ByteArrayOutStream中
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        workbook.write(bos);
        headers=new HttpHeaders();
        headers.setContentDispositionFormData ( "Attachment" ,
                new new String ( "Employees table .xls" .getBytes ( "UTF-8"), "ISO-8859-1" ));
         // create ResponseEntity entity and return to 
        return  new new ResponseEntity < byte []> (bos.toByteArray () , headers, HttpStatus.CREATED); 

    } 
}

display effect

 

Guess you like

Origin www.cnblogs.com/gfbzs/p/12272988.html