包位置: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 —行号 中文品名 产品描述。。。