實體類:
@Data public class DeviceExcel { /** * 名稱 */ @Excel(name="名稱",width = 20) private String name; /** * 編號 */ @Excel(name="編號",width = 20) private String code; /** * 上傳圖片 */ @Excel(name = "上傳圖片", type = 2 ,height = 30,width = 20 ) private String picture; /** * 備注 */ @Excel(name="備注",width = 40) private String memo; }
Excel的源碼:
導出代碼:
public void exportDevice(HttpServletRequest request, HttpServletResponse response) { //獲取要導出的數據 List<DeviceExcel> deviceExcelList = constructDeviceExcelList(deviceList); //導出數據 Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(),DeviceExcel.class,deviceExcelList); //下載數據 ExcelPoiUtil.downLoadExcelXlsx(request,response,workbook,"文件名稱"); }
public static void downLoadExcelXlsx(HttpServletRequest request, HttpServletResponse response, Workbook workbook, String fileName){ final String userAgent = request.getHeader("USER-AGENT"); try { ServletOutputStream outputStream = response.getOutputStream(); //清空輸出流 response.reset(); fileName = encoderName(userAgent, fileName); //這里設置一下讓瀏覽器彈出下載提示框,而不是直接在瀏覽器中打開 response.setHeader("Content-Disposition", "attachment; filename=" + fileName + "-" + DateTimeUtil.getCurrDateStr()+ ".xlsx"); response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); response.setCharacterEncoding("UTF8"); workbook.write(outputStream); outputStream.close(); } catch (IOException e) { e.printStackTrace(); throw new ServerException(ExceptionCode.FILE_FORMAT_ERROR.getExceptionCode(),"文件下載異常"); } } private static String encoderName(String userAgent, String fileName) throws IOException{ if("MSIE".equals(userAgent)){ //IE瀏覽器 fileName = URLEncoder.encode(fileName,"UTF8"); }else if("Mozilla".equals(userAgent)){ //google,火狐瀏覽器 fileName = new String(fileName.getBytes(), "ISO8859-1"); }else{ //其他瀏覽器 fileName = URLEncoder.encode(fileName,"UTF8"); } return fileName; }