ExcelUtils以及不用工具導出Excel的方法

包位置:com.xxxxx.common.utils

/*Excel工具類
 */
public class ExcelUtils{
	//1:通過值  獲取cell
	public static Cell getCellByValue(Sheet sheet,String value){
	  		for( int row = 0 ; row < 10  ; row ++  ){
						for(int col = 0 ;col < 100 ; col ++){
							 try{
								Cell cell = sheet.getCell(col,row);//獲取每一個單元格 10*100	
									if(value.equals(cell.getContents()) ){
										return cell;
										}
									}catch(Exception e){break;}
						}
			}
		return null;
	}
	//2:根據指定的cols,導出Excel列表 //cols爲 JSON類型{name:"",age:""......}
	public static ResponseEntity<byte[]> readList(List<?> list, JSONObject cols)throws Exception{
	   			//獲取Excel文件對象
	   			ByteArrayOutputStream out =  new ByteArrayOutputStream();
	   			WritableWorkbook rwb =  Workbook.createWorkbook(out);
				try{
						//獲取文件的指定工作表 默認的第一個
						WritableWorkbook  sheet  =  rwb.createSheet(SystemUtils.getMessages().get("export,sheet"),0);	
						//代碼塊 ,初始化嗎?
						{
								int colIdx = -1;
								for(Object colsName : cols.keySet() ){
										String sinoName  =  cols.getString( colsName == null ? "" : colsName.toString()  );
										colIdx++;
										sheet.addCell(  new Label (colIdx, 0 ,StringUtils.isBlank(sinoName) ? colsName == null ? "" : colsName.toString() : sinoName)  );
										}
						}
						//遍歷列
						for( int i = 0; ; i ++ ){
									if( list.size() <= i ) break ;	
									Object obj = list.get(i);
									int colIdx = -1;
										for( Object colsName : cols.keySet() ){
											 try{
													colIdx++;
													Object value = BeanUtils.getValue(obj,colsName == null ? "" : colsName.toString());
													if(value != null)  sheet.addCell( new Label (colIdx,i+1,value.toString() )) ;
													}catch(Exception e){
												 e.printStackTrace();
												 continue;				
												}
										}		
								}
					}finally{
					rwb.write();
					rwb.close();
					out.close();
					}
					//3:這一步是幹嘛的?export.sheet = 數據   ; 這個就是導出文件後的名字
					HttpHeaders headers  = new HttpHeaders();
					headers.setContentType(Media.APPLICATION_OCTET_STREAM);
					headers.add("Content-disposition","attachment;filename="+URLEncoder.encode(String.format("%s.xls",SystemUtils.getMessages().get("export.sheet")),"utf-8"));
					return new ResponseEntity<byte[]>(out.toByteArray(),headers,HttpStatus.OK);
	}

	//3:通過map集合 ,導出Excel
	public static RespnseEntity<byte[]> readListByMap(List<?> list ,Map<String, String> cols) throws Exception{
			 			//獲取Excel文件對象
	   			ByteArrayOutputStream out =  new ByteArrayOutputStream();
	   			WritableWorkbook rwb =  Workbook.createWorkbook(out);
				try{
						//獲取文件的指定工作表 默認的第一個
						WritableWorkbook  sheet  =  rwb.createSheet(SystemUtils.getMessages().get("export,sheet"),0);	
						//代碼塊 ,初始化嗎?
						{
								int colIdx = -1;
								for(Object colsName : cols.keySet() ){
										String sinoName  =  cols.getString( colsName == null ? "" : colsName.toString()  );
										colIdx++;
										sheet.addCell(  new Label (colIdx, 0 ,StringUtils.isBlank(sinoName) ? colsName == null ? "" : colsName.toString() : sinoName)  );
										}
						}
						//遍歷列
						for( int i = 0; ; i ++ ){
									if( list.size() <= i ) break ;	
									Object obj = list.get(i);
									int colIdx = -1;
										for( Object colsName : cols.keySet() ){
											 try{
													colIdx++;
													Object value = BeanUtils.getValue(obj,colsName == null ? "" : colsName.toString());
													if(value != null)  sheet.addCell( new Label (colIdx,i+1,value.toString() )) ;
													}catch(RowsExceededException ee){
												throw new Exception("數據的數量,已經超出Excel的最大允許行數");			
													}catch(Exception ee){
													ee.printStackTrace();
													continue;
													}
										}		
								}
					}finally{
					rwb.write();
					rwb.close();
					out.close();
					}
					//3:這一步是幹嘛的?export.sheet = 數據   ; 這個就是導出文件後的名字
					HttpHeaders headers  = new HttpHeaders();
					headers.setContentType(Media.APPLICATION_OCTET_STREAM);
					headers.add("Content-disposition","attachment;filename="+URLEncoder.encode(String.format("%s.xls",SystemUtils.getMessages().get("export.sheet")),"utf-8"));
					return new ResponseEntity<byte[]>(out.toByteArray(),headers,HttpStatus.OK);
	}
		
}

}//類尾

獲取之後可以自己試一下 ,可不可行?
export.sheet = 訂單報價單 這個只是給文件起個名字。在配置文件,properties中。
具體用法:
DemandExportController.java

@Controller
@RequestMapping("/crm/demand/export")
public class DemandExportController extends AbstractController<DemandExportModel>{
	@Autowired
	DemandExportMapper mapper;
	
	@Autowired
	DemandExportService service;
	
	@Override
	public DemandExportService getBaseService(){ return service ;}
	@Override
	public DemandExportMapper getBaseMapper(){ return  mapper ;}
		
	/*查詢列表
	*/
	@RequestMapping("/selectExportList.do")
	@ResponseBody
	public String selectExportList(DemandExportModel model ,HttpServletRequest request,HttpServletResponse response) throws Exception{
			try{
					model.setPositionId( SystemUtils.getUserModel().getPositionId() );
					List<DemandExportModel> list = mapper.selectExportList(model);
					return StringUtils.resultSuccessToJson(list);
				}catch(Exception e ){
			 return StringUtils.resultFailToJson(e);	
				}	
	}
	/*商務需求單導出Excel -- 接口
	*/
	@RequestMapping("/demandListExcel.do")
	@ResponseBody
	public ResponseEntity<byte[]> demandListExcel(  DemandExportModel model ,HttpServletRequest request,HttpServletResponse response ) throws Exception{
		model.setPageSize(100000);
		model.setPositionId( SystemUtils.getUserModel().getPositionId() );
		List<DemandExportModel> list = mapper.selectExportList(model);
		if( StringUtils.isNotNullOrEmptyStr(model.getCols()) ){
			JSONObject json = JSONObject.fromObject(model.getCols()); 
			//cols,model中說明:導出Excel時,選中的字段存儲列
			return ExcelUtils.readList(list,json); //其實我不知道怎麼用的,什麼效果。是不是cols要傳一個 JSON類型的字符串
			//裏面裝需要導出的字段名稱,根據需要。但是我看項目裏面的好像都沒用到。全部走的下面的map導出。
		}else{
		Map<String String > map = new LinkedHashMap<>();
		map.put("billId","單號");
		map.put("firstLine","一級產品線"); 
		map.put("secondLine","二級產品線"); 
		map.put("fcurrentStep","工作流當前環節描述"); 
		map.put("baseBomNum","基礎BOM料號"); 
		map.put("baseBomName","基礎BOM名稱"); 
		map.put("amounts","數量"); 
		map.put("creator","創建人"); 
		map.put("brand","品牌"); 
		map.put("orderDate","下單日期"); 
		map.put("division","下單部門"); 
		map.put("accountName","客戶名稱"); 
		map.put("busSaler","業務員"); 
		map.put("busMan","商務員");
	 	map.put("ebusAuditMan","商務審批人"); 
		map.put("innerModel","內部型號"); 
		map.put("outModel","外部型號"); 
		map.put("language","語言"); 
		//。。。有很多,列表上有很多字段,差不多快90了。所以Excel  10*100應該夠了。
		return ExcelUtils.readListByMap(list,map);
		}	
	}
	
}

針對哪個 cols,我問了師父,原來一直在用,就是點擊導出的時候會有一個 彈窗,裏面全是 字段右邊有一個勾選框,就是看你導出的時候需不需要,彈窗下面一個 導出按鈕,就是根據選中的字段進行導出。傳參類似這種:因爲是JsonObject.fromObejct,所以應該是:
cols:"{ “attentionState”:“關注”,
“opptynum”:“項目編號”,
“opptyname”:“項目名稱”,
“accountname”:“甲方客戶”,
“orderamount”:“預計產單金額(萬)”
}" //就是這種導出的時候只會展示這幾個字段。具體前端怎麼傳這樣的參數,我不知道,不過應該不難。前端應該是定義了一個JSONObject ,往裏面放字段,後臺是用字符串進行接受的。也就是前段傳的是一個 Json類型的字符串。cols:"{“accountname”:“甲方客戶”,opptyNum:“項目編號”}"。
sum:true
2019-03-27
不用ExcelUtils,直接手寫導出Excel的代碼

public static ResponseEntity<byte[]> readList(List<QuoteProductModel> list ,String template) throws Exception{
	 	//獲取Excel文件對象
		ByteArrayOutputStream out = new ByteArrayoutputStream();
		Workbook temp = Workbook.getWorkbook(new File(template)); //template爲 路徑
		WritableWorkbook rwb = Workbook.createWorkbook(out,temp);
		try{
				WritableSheet sheet = rwb.getSheet(0);
				Cell cell1 = ExcelUtils.getCellByValue(sheet,"行號");
				Cell cell2 = ExcelUtils.getCellByValue(sheet,"中文品名");
				Cell cell3 = ExcelUtils.getCellByValue(sheet,"產品描述");
				Cell cell4 = ExcelUtils.getCellByValue(sheet,"內部型號");
				Cell cell5 = ExcelUtils.getCellByValue(sheet,"外部型號");
				Cell cell6 = ExcelUtils.getCellByValue(sheet,"物料號");
				Cell cell7 = ExcelUtils.getCellByValue(sheet,"數量");
				Cell cell8 = ExcelUtils.getCellByValue(sheet,"意向單價");
				Cell cell9 = ExcelUtils.getCellByValue(sheet,"實際質保期");
				Cell cell10 = ExcelUtils.getCellByValue(sheet,"總金額");
				//定義行號
				int line = cell1.getRow();
				for(QuoteProductModel model :list){
					line ++;
					Label lable = new Label(cell1.getColums(),line,String.format("%d",line)); //行號
				 	Label lable1 = new Label(cell2.getColums(),line,model.getChsDesc());    //中文品名
				 	Label lable2 = new Label(cell3.getColums(),line,model.getProduct());    //中文品名
				 	Label lable3 = new Label(cell4.getColums(),line,model.getProductInModel());    //中文品名
				 	Label lable4 = new Label(cell5.getColums(),line,model.getProductOutModel());    //中文品名
				 	Label lable5 = new Label(cell6.getColums(),line,model.getPartNumber());    //中文品名
				 	Label lable6 = new Label(cell7.getColums(),line,model.getQuantityRequested());    //中文品名
				 	Label lable7 = new Label(cell8.getColums(),line,model.getUnitPrice());    //中文品名
				 	Label lable8 = new Label(cell9.getColums(),line,model.getAwp());    //中文品名
				 	Label lable9 = new Label(cell10.getColums(),line,model.getAmount());    //中文品名
				 	sheet.addCell(lable);
				 	sheet.addCell(lable1);
				 	sheet.addCell(lable2);
				 	sheet.addCell(lable3);
				 	sheet.addCell(lable4);
				 	sheet.addCell(lable5);
				 	sheet.addCell(lable6);
				 	sheet.addCell(lable7);
				 	sheet.addCell(lable8);
				 	sheet.addCell(lable9);
				}		
			}finally{
			rwb.write();
			rwb.close();
			out.close();
			temp.close();
			}
	//設置文件名
	HttpHeaders headers = new HttpHeaders();
	headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
	headers.add("Content-disposition","attachment;filename="+URLEncoder.encode(String.format("%s.xls",SystemUtils.getMessages().get("export.sheet1")),"utf-8"));
		
	return new ResponseEntity<byte[]>(out.toByteArray(),headers,HttpStatus.OK);
}

//該方法在導出用到,如下:



@RequestMapping("/out.do")
@ResponseBody
public ResponseEntity<byte[]> out(QuoteProductModel model,HttpServletRequest request,HttpServletResponse response)throws Exception{
		if(StringUtils.isBlank(model.getQuoteId())){throw new Exception("quote.0001");}
		
		//以下不用管,只是爲了創建條件,查詢主要價格的。
		List<String> list = new ArrayList<>();
		list.add("Primary Price Rep");
		Map<String,String> map = qservice.profileAttrs(list);
		String primaryPrice  = map.get("Primary Price Rep");  //讀取全局變量
		if(primaryPrice  ==  null) primaryPrice = "" ;
		model.setLoginName( SystemUtils.getUserModel().getLoginName() );		
		model.setDepartment(  SystemUtils.getUserModel().getDepartment() );
		model.setPrimaryPrice(primaryPrice);
		//以上代碼不用管,與導出基本沒啥關係。只是給主要價格設置值。

		List<QuoteProductModel> list1 = getBaseMapper.selectPage(model); //取得數據信息 
		String templateFile = request.getServletContext().getRealPath("/")+"template/productlist.xls"; //服務器版本
		logger.info("----------------------------------"+templateFile);
		return readList(list1,templateFile);
}

項目下 webapp – template—productlist.xls —行號 中文品名 產品描述。。。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章