Java complete POI function

  POM文件   
  
<
dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!--mysql驱动--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.17</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.17</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>tk.mybatis</groupId> <artifactId>mapper-spring-boot-starter</artifactId> <version>1.2.3</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.47</version> </dependency> <dependency> <groupId>net.sourceforge.nekohtml</groupId> <artifactId>nekohtml</artifactId> <version>1.9.15</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
实体bean

@Data @AllArgsConstructor @NoArgsConstructor
public class TRole { private Integer id; private String name; private Integer age; }
/**
*Excel工具类
*/
public class ExcelUtil {

    public static final String FILE_NAME = "用户表";

    public static final String EXCEL_XLS = "xls";
    public static final String EXCEL_XLSX = "xlsx";


    public static boolean isExcelXls(String filePath) {
        return filePath.matches("^.+\\.(?i)(xls)$");
    }

    public static boolean isExcelXlsx(String filePath) {

        return filePath.matches("^.+\\.(?i)(xlsx)$");
    } 

    / ** 
     * Some cell is Numeric format with index E. Therefore, if you want to get that type String, the need for format conversion. 
     * 
     * @Param Cell 
     * @return 
     * / 
    public  static String getStringFromNumericCell (the Cell Cell) {
         return  new new DecimalFormat ( "#" ) .format (cell.getNumericCellValue ()); 
    } 

    / ** 
     * title generated by the object and sheet objects WorkBook 
     * 
     * @param WB WorkBook objects 
     * @param Sheet Sheet Object
      * / 
    public  static  void createTitle (WB the Workbook, Sheet Sheet) {
         //Generating a table header row );
        = Sheet.createRow Row Row (0 );
         // set the column width 
        sheet.setColumnWidth (. 1, 12 is 256 * ); 
        sheet.setColumnWidth ( . 3, 256 *. 17 );
         // set style: font bold, centering 
        CellStyle cellStyle = wb.createCellStyle (); 
        cellStyle.setAlignment (HorizontalAlignment.CENTER); 
        the font font = wb.createFont (); 
        font.setBold ( to true ); 
        cellStyle.setFont (font); 
        // The object properties set the cell header 
        cell cell0 = row.createCell (0 ); 
        cell0.setCellValue ( "ID"
        cell0.setCellStyle(cellStyle);
        Cell cell1 = row.createCell(1);
        cell1.setCellValue("name");
        cell1.setCellStyle(cellStyle);
        Cell cell2 = row.createCell(2);
        cell2.setCellValue("age");
        cell2.setCellStyle(cellStyle);
    }

    /**
     * 生成文件在本地
     * @param fileName
     * @param wb
     */
    public static void buildExcelFile(String fileName, Workbook wb) {
        try {
            FileOutputStream fos = new FileOutputStream(fileName);
            wb.write(fos);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 返回给浏览器
     * @param fileName
     * @param wb
     * @param response
     */
    public static void buildExcelFile(String fileName, Workbook wb, HttpServletResponse response) {
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));
            ServletOutputStream outputStream = response.getOutputStream();
            wb.write(outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace (); 
        } 
    } 
}
/**
*Controller层操作,省略service和dao
*/

@Controller
@RequestMapping("/excel")
public class ExcelController {

@Autowired
ExcelService excelService;

@RequestMapping("/")
public String toIndex() {
return "excel";
}

@ResponseBody
@RequestMapping("/download/{way}")
public String excelFileDownload(@PathVariable String way, HttpServletResponse response) throws IOException {
Workbook wb = null;
String filename = ExcelUtil.FILE_NAME;
if (ExcelUtil.EXCEL_XLS.equals(way)) {
wb = new HSSFWorkbook();
filename += ".xls";
} else if ((ExcelUtil.EXCEL_XLSX.equals(way))) {
wb = new XSSFWorkbook();
filename += ".xlsx";
}
Sheet sheet = wb.createSheet("角色表");
ExcelUtil.createTitle(wb, sheet);

//从数据库查出数据
List<TRole> tRoles = excelService.getAllRoles();
//记录新增行数据
int rowNum = 1;
for (TRole tRole : tRoles) {
Row row = sheet.createRow(rowNum);
row.createCell(0).setCellValue(tRole.getId());
row.createCell(1).setCellValue(tRole.getName());
row.createCell(2).setCellValue(tRole.getAge());
rowNum++;
}
//生成excel文件(在当前文件夹下)
//ExcelUtil.buildExcelFile(filename, wb);
//浏览器下载excel
ExcelUtil.buildExcelFile(filename, wb, response);
wb.close();
return "File downloaded successfully";

}


@ResponseBody
@RequestMapping("/upload")
public String excelFileUpload(MultipartFile file) throws IOException {
Workbook wb = null;
List<TRole> tRoleList = new ArrayList<>();
if (!ExcelUtil.isExcelXlsx(file.getOriginalFilename()) && !ExcelUtil.isExcelXls(file.getOriginalFilename())) {

return "The file must be of excel type";
}
IF (. file.getOriginalFilename () == null || file.getOriginalFilename () the equals ( "") || file.getSize () == 0) {
return "of The File CAN BE Not empty";
}
the try {
IF (ExcelUtil .isExcelXlsx (file.getOriginalFilename ())) {
WB = new new XSSFWorkbook (file.getInputStream ());
} the else {
WB = new new HSSFWorkbook (file.getInputStream ());
}
// Get the first table (the default is set it into a table)
sheet sheet wb.getSheetAt = (0);
// get the number of rows
int rowsNum sheet.getPhysicalNumberOfRows = ();
// through the rows
for (int I = 0; I <rowsNum; I ++) {
// header row is omitted
IF (I == 0) {
Continue;
}
Row Row = sheet.getRow (I);
// traversing each row of cells
// for (int J = 0; J <row.getPhysicalNumberOfCells (); J ++) {
/ / = row.getCell the cell cell (J);
//}
// here we specifically direct the operation of the cell
. Integer id = Integer.valueOf (Double.valueOf ( row.getCell (0) .getNumericCellValue ()) intValue () );
String name = row.getCell (. 1) .getStringCellValue ();
Integer = Integer.valueOf Age (Double.valueOf (row.getCell (2) .getNumericCellValue ()) intValue ());.
tRole tRole new new tRole = ( id, name, age);
tRoleList.add(tRole);
}

} catch (IOException e) {
e.printStackTrace();
} finally {
wb.close();
}
return JSON.toJSONString(tRoleList);
}
}

 

Guess you like

Origin www.cnblogs.com/hucheng1997/p/11426086.html