excel多sheet导出工具类
1、多个sheet导出工具类:
import org. apache. commons. lang3. StringUtils ;
import org. apache. poi. hssf. usermodel. * ;
import org. apache. poi. hssf. util. HSSFColor ;
import org. apache. poi. ss. usermodel. * ;
import org. apache. poi. xssf. usermodel. * ;
import org. springframework. web. multipart. MultipartFile ; import javax. servlet. http. HttpServletResponse ;
import java. io. OutputStream ;
import java. net. URLEncoder ;
import java. text. DecimalFormat ;
import java. text. SimpleDateFormat ;
import java. util. * ;
public class ExcelDataHandleUtil { private final static String XLS = "xls" ; private final static String XLSX = "xlsx" ; private final static String SUFFIX_XLS = ".xls" ; private final static String SUFFIX_XLSX = ".xlsx" ; public static List < Map < String , Object > > analysisExcel ( MultipartFile file, String [ ] keyList) throws Exception { Workbook workbook = null ; String fileName = file. getOriginalFilename ( ) ; if ( fileName. endsWith ( XLS ) ) { workbook = new HSSFWorkbook ( file. getInputStream ( ) ) ; } else if ( fileName. endsWith ( XLSX ) ) { workbook = new XSSFWorkbook ( file. getInputStream ( ) ) ; } else { throw new Exception ( "文件不是Excel文件" ) ; } Sheet sheet = workbook. getSheetAt ( 0 ) ; int rows = sheet. getLastRowNum ( ) ; if ( rows == 0 ) { throw new Exception ( "请填写数据" ) ; } List < Map < String , Object > > list = new ArrayList < > ( ) ; for ( int i = 1 ; i <= rows; i++ ) { Row row = sheet. getRow ( i) ; if ( row != null ) { Map < String , Object > map = new HashMap < > ( ) ; for ( int j = 0 ; j < keyList. length; j++ ) { map. put ( keyList[ j] , getCellValue ( row. getCell ( j) ) ) ; } list. add ( map) ; } } return list; } public static void exportExcel ( HttpServletResponse response, List < Map > list, String [ ] keyList, String [ ] columnNameList, String fileName) throws Exception { XSSFWorkbook workbook = new XSSFWorkbook ( ) ; XSSFSheet sheet = workbook. createSheet ( "Sheet1" ) ; XSSFRow row = sheet. createRow ( 0 ) ; XSSFCellStyle style = workbook. createCellStyle ( ) ; style. setAlignment ( HorizontalAlignment . CENTER ) ; XSSFCell cell = row. createCell ( 0 ) ; for ( int i = 0 ; i < columnNameList. length; i++ ) { cell. setCellValue ( columnNameList[ i] ) ; cell. setCellStyle ( style) ; cell = row. createCell ( i + 1 ) ; } for ( int i = 0 ; i < list. size ( ) ; i++ ) { row = sheet. createRow ( i + 1 ) ; Map < String , Object > map = list. get ( i) ; for ( int j = 0 ; j < keyList. length; j++ ) { String key = keyList[ j] ; if ( map. get ( key) != null && StringUtils . isNotBlank ( map. get ( key) . toString ( ) ) ) { row. createCell ( j) . setCellValue ( String . valueOf ( map. get ( key) ) ) ; } } } OutputStream output = response. getOutputStream ( ) ; response. reset ( ) ; response. setHeader ( "Content-disposition" , "attachment; filename=" + URLEncoder . encode ( fileName, "UTF-8" ) + SUFFIX_XLSX ) ; response. setContentType ( "application/msexcel" ) ; workbook. write ( output) ; output. close ( ) ; } public static void exportExcelXLS ( HttpServletResponse response, List < Map > list, String [ ] keyList, String [ ] columnNameList, String fileName) throws Exception { HSSFWorkbook workbook = new HSSFWorkbook ( ) ; HSSFSheet sheet = workbook. createSheet ( "Sheet1" ) ; sheet. setDefaultColumnWidth ( ( short ) 20 ) ; HSSFRow row = sheet. createRow ( 0 ) ; HSSFCellStyle style = workbook. createCellStyle ( ) ; style. setAlignment ( HorizontalAlignment . CENTER ) ; HSSFCell cell = row. createCell ( 0 ) ; style. setAlignment ( HorizontalAlignment . CENTER ) ; style. setFillForegroundColor ( HSSFColor . PALE_BLUE . index) ; style. setFillPattern ( FillPatternType . SOLID_FOREGROUND ) ; style. setBorderBottom ( BorderStyle . THIN ) ; style. setBorderLeft ( BorderStyle . THIN ) ; style. setBorderRight ( BorderStyle . THIN ) ; style. setBorderTop ( BorderStyle . THIN ) ; HSSFFont font = workbook. createFont ( ) ; font. setColor ( HSSFColor . BLACK . index) ; font. setFontHeightInPoints ( ( short ) 12 ) ; font. setBold ( true ) ; style. setFont ( font) ; for ( int i = 0 ; i < columnNameList. length; i++ ) { cell. setCellValue ( columnNameList[ i] ) ; cell. setCellStyle ( style) ; cell = row. createCell ( i + 1 ) ; } for ( int i = 0 ; i < list. size ( ) ; i++ ) { row = sheet. createRow ( i + 1 ) ; Map < String , Object > map = list. get ( i) ; for ( int j = 0 ; j < keyList. length; j++ ) { String key = keyList[ j] ; if ( map. get ( key) != null && StringUtils . isNotBlank ( map. get ( key) . toString ( ) ) ) { row. createCell ( j) . setCellValue ( String . valueOf ( map. get ( key) ) ) ; } } } OutputStream output = response. getOutputStream ( ) ; response. reset ( ) ; SimpleDateFormat df = new SimpleDateFormat ( "yyyyMMddHHmmss" ) ; response. setHeader ( "Content-disposition" , "attachment; filename=" + URLEncoder . encode ( fileName, "UTF-8" ) + SUFFIX_XLS ) ; response. setContentType ( "application/msexcel" ) ; workbook. write ( output) ; output. close ( ) ; } public static void exportExcel ( HSSFWorkbook workbook, int sheetNum, String sheetTitle, List < Map < String , Object > > list, String [ ] keyList, String [ ] columnNameList) { HSSFSheet sheet = workbook. createSheet ( ) ; workbook. setSheetName ( sheetNum, sheetTitle) ; HSSFRow row = sheet. createRow ( 0 ) ; sheet. setDefaultColumnWidth ( ( short ) 20 ) ; HSSFCell cell = row. createCell ( 0 ) ; HSSFCellStyle style = workbook. createCellStyle ( ) ; style. setAlignment ( HorizontalAlignment . CENTER ) ; style. setFillForegroundColor ( IndexedColors . GREY_25_PERCENT . getIndex ( ) ) ; style. setFillPattern ( FillPatternType . SOLID_FOREGROUND ) ; style. setBorderBottom ( BorderStyle . THIN ) ; style. setBorderLeft ( BorderStyle . THIN ) ; style. setBorderRight ( BorderStyle . THIN ) ; style. setBorderTop ( BorderStyle . THIN ) ; HSSFFont font = workbook. createFont ( ) ; font. setColor ( HSSFColor . BLACK . index) ; font. setFontHeightInPoints ( ( short ) 13 ) ; font. setBold ( true ) ; style. setFont ( font) ; for ( int i = 0 ; i < columnNameList. length; i++ ) { cell. setCellValue ( columnNameList[ i] ) ; cell. setCellStyle ( style) ; row. setHeight ( ( short ) ( 30 * 20 ) ) ; cell = row. createCell ( i + 1 ) ; } if ( list != null && ! list. isEmpty ( ) ) { for ( int i = 0 ; i < list. size ( ) ; i++ ) { row = sheet. createRow ( i + 1 ) ; Map < String , Object > map = list. get ( i) ; for ( int j = 0 ; j < keyList. length; j++ ) { String key = keyList[ j] ; if ( map. get ( key) != null && StringUtils . isNotBlank ( map. get ( key) . toString ( ) ) ) { row. createCell ( j) . setCellValue ( String . valueOf ( map. get ( key) ) ) ; } } } } } private static String getCellValue ( Cell cell) { String value = "" ; if ( cell != null ) { switch ( cell. getCellType ( ) ) { case HSSFCell . CELL_TYPE_NUMERIC : value = cell. getNumericCellValue ( ) + "" ; if ( HSSFDateUtil . isCellDateFormatted ( cell) ) { Date date = cell. getDateCellValue ( ) ; if ( date != null ) { value = new SimpleDateFormat ( "yyyy-MM-dd" ) . format ( date) ; } else { value = "" ; } } else { value = new DecimalFormat ( "##0.####" ) . format ( cell. getNumericCellValue ( ) ) ; } break ; case HSSFCell . CELL_TYPE_STRING : value = cell. getStringCellValue ( ) ; break ; case HSSFCell . CELL_TYPE_BOOLEAN : value = cell. getBooleanCellValue ( ) + "" ; break ; case HSSFCell . CELL_TYPE_FORMULA : value = cell. getCellFormula ( ) + "" ; break ; case HSSFCell . CELL_TYPE_BLANK : value = "" ; break ; case HSSFCell . CELL_TYPE_ERROR : value = "非法字符" ; break ; default : value = "未知类型" ; break ; } } return value. trim ( ) ; } }
2、工具类使用
@ApiOperation ( value = "资产中心-资产包-导出" ) @ApiResponse ( code = 200 , message = "返回结果" ) @RequestMapping ( value = "/export" , method = RequestMethod . POST ) public void export ( @RequestBody AssetPackageVersionSearchDto dto, HttpServletResponse response) throws IOException { if ( dto. getProjectMainId ( ) == null ) { throw new LogicException ( 500 , "项目id不能为空" ) ; } AssetPackageVersionResultDto resultDto = this . assetPackageClient. queryDetail ( dto) . getResult ( ) ; Map < String , String > operateStatusMap = getOperateStatus ( ) ; for ( AssetUnitResultDto assetUnitResultDto : resultDto. getAssetUnitList ( ) ) { if ( operateStatusMap. containsKey ( assetUnitResultDto. getOperateStatus ( ) . toString ( ) ) ) { assetUnitResultDto. setOperateStatusName ( operateStatusMap. get ( assetUnitResultDto. getOperateStatus ( ) . toString ( ) ) ) ; } } try { String s1 = JSON . toJSONString ( resultDto. getAssetPackageList ( ) ) ; String s2 = JSON . toJSONString ( resultDto. getAssetUnitList ( ) ) ; List < Map < String , Object > > assetPackageList = JSONObject . parseObject ( s1, new TypeReference < List < Map < String , Object > > > ( ) { } ) ; List < Map < String , Object > > assetUnitList = JSONObject . parseObject ( s2, new TypeReference < List < Map < String , Object > > > ( ) { } ) ; String [ ] assetPackageKey = { "assetPackageCode" , "assetPackageName" , "firstFormatName" , "buildingArea" , "selfBuildingArea" , "saleableBuildingArea" , "matchingArea" , "governmentRepurchaseArea" , "otherArea" , "assetLocation" , "remark" } ; String [ ] assetPackageColumnName = { "资产包编码" , "资产包名称" , "汇总业态" , "总建筑面积(㎡)" , "自持建筑面积(㎡)" , "可售建筑面积(㎡)" , "配套面积(㎡)" , "政府回购面积(㎡)" , "其他面积(㎡)" , "资产包坐落" , "备注" } ; String [ ] assetUnitKey = { "assetUnitName" , "assetUnitCode" , "buildingName" , "assetPackageName" , "assetPackageCode" , "operateStatusName" , "firstFormatName" , "buildingFormatName" , "secondFormatName" , "buildingArea" , "selfBuildingArea" , "saleableBuildingArea" , "matchingArea" , "governmentRepurchaseArea" , "otherArea" , "remark" } ; String [ ] assetUnitColumnName = { "资产单元名称" , "资产单元编码" , "所属楼栋" , "所属资产包名称" , "所属资产包编码" , "资产状态" , "汇总业态" , "建筑业态" , "营销业态" , "总建筑面积(㎡)" , "自持建筑面积(㎡)" , "可售建筑面积(㎡)" , "配套面积(㎡)" , "政府回购面积(㎡)" , "其他面积(㎡)" , "备注" } ; HSSFWorkbook workbook = new HSSFWorkbook ( ) ; ExcelDataHandleUtil . exportExcel ( workbook, 0 , "资产包" , assetPackageList, assetPackageKey, assetPackageColumnName) ; ExcelDataHandleUtil . exportExcel ( workbook, 1 , "资产单元" , assetUnitList, assetUnitKey, assetUnitColumnName) ; String fileName = "资产包数据导出" + DateUtils . dateTimeNow ( ) ; OutputStream output = response. getOutputStream ( ) ; response. reset ( ) ; response. setContentType ( "application/vnd.ms-excel" ) ; response. setCharacterEncoding ( "utf-8" ) ; String dlfileName = URLEncoder . encode ( fileName, "utf-8" ) . replaceAll ( "\\+" , "%20" ) ; response. setHeader ( "Content-Disposition" , "attachment;filename*=utf-8''" + dlfileName + ".xls" ) ; workbook. write ( output) ; output. close ( ) ; } catch ( Exception e) { throw new LogicException ( 500 , "导出失败,请重试!" ) ; } } public Map < String , String > getOperateStatus ( ) { DicCodeVo dicCodeVo = DicCodeVo . init ( ) . addDic ( "assetPackageOperateStatus" , DictPathConstant . ASSET_PACKAGE_OPERATE_STATUS ) ; Map < String , String > map = Maps . newHashMap ( ) ; dicCodeVo. getDic ( ) . entrySet ( ) . forEach ( d -> { if ( "assetPackageOperateStatus" . equals ( d. getKey ( ) ) ) { d. getValue ( ) . getChildren ( ) . forEach ( v -> { map. put ( v. getValue ( ) , v. getName ( ) ) ; } ) ; } } ) ; return map; }