前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >springSSM 使用poi导出excel(一)

springSSM 使用poi导出excel(一)

作者头像
用户5640963
发布2019-07-28 11:38:54
5400
发布2019-07-28 11:38:54
举报
文章被收录于专栏:卯金刀GG卯金刀GG

使用的核心知识为java的反射机制,注解的使用,下面是过程代码:

1、js部分

function exportExcelCom(actionurl){

代码语言:javascript
复制
var $form = $("<form>");   //定义一个form表单

$form.attr('style', 'display:none');   //在form表单中添加查询参数

$form.attr('target', '');

$form.attr('method', 'post');

$form.attr('action', actionurl);

$('body').append($form);  //将表单放置在web中

    $form.submit(); 

}

2、spring Controller

@RequestMapping(value = "/exportExcel")

public void exportExcel(HttpServletRequest request,

HttpServletResponse response) throws SecurityException,

IllegalArgumentException, ClassNotFoundException, NoSuchMethodException, Exception{

System.out.println("执行导出***");

代码语言:javascript
复制
   byte[] fileNameByte = ("职业病基础知识.xls").getBytes("GBK");    
    String filename = new String(fileNameByte, "ISO8859-1"); 
    List<ZywsptGfxwjb> list = new ArrayList<ZywsptGfxwjb>();
    /*ZywsptGfxwjb zywsptGfxwjb = new ZywsptGfxwjb();
    zywsptGfxwjb.setMc("名称1");
    zywsptGfxwjb.setGjz("关键系");
    list.add(zywsptGfxwjb);*/
    list = gfxwjService.selectObjExist();
    byte[] bytes = excelService.export(list);
    response.setContentType("application/x-msdownload");    
    response.setContentLength(bytes.length);    
    response.setHeader("Content-Disposition", "attachment;filename="    
            + filename);    
    response.getOutputStream().write(bytes);
}

3、通用类方法

public static byte[] export(String sheet1, String title, Class<?> clazz,List<?> list) throws IOException, ClassNotFoundException, SecurityException, NoSuchMethodException, IllegalArgumentException, Exception{ ByteArrayOutputStream out = new ByteArrayOutputStream();

代码语言:javascript
复制
// 第一步,创建一个webbook,对应一个Excel文件    
    HSSFWorkbook wb = new HSSFWorkbook();

    // 第二步,在webbook中添加一个sheet,对应Excel文件中的sheet    
    HSSFSheet sheet = wb.createSheet(sheet1); 

    // 第三步,在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short  

    HSSFRow row = sheet.createRow((int) 0);

    // 第四步,创建单元格,并设置值表头 设置表头居中    
    HSSFCellStyle style = wb.createCellStyle();

    style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式

    //设置表头    
    List<ExportFiledsBean> excelHead = getExcelHead(clazz);
    String clazzName = clazz.getName();
    Class  _class = Class.forName(clazzName);
    
    HSSFCell cell = null;
    // excel头    
    for (int i = 0; i < excelHead.size(); i++) {   
    	ExportFiledsBean exportFiledsBean = excelHead.get(i);
        cell = row.createCell(i);    
        cell.setCellValue(exportFiledsBean.getName());    
        cell.setCellStyle(style);
    }  
    
    for (int i = 0;i<list.size();i++)
    {
    	row = sheet.createRow((int) i + 1); 
    	Object obj = (Object) list.get(i);
    	for(int j=0;j<excelHead.size();j++)
    	{
    		ExportFiledsBean exportFiledsBean = excelHead.get(j);
    		String getFuncName = exportFiledsBean.getGetFuncName();
    		
    		Method addMethod = _class.getMethod(getFuncName);
    		Object result = addMethod.invoke(obj);
    		if(result==null)
    		{
    			row.createCell((int) j).setCellValue("");
    		}else{
    			row.createCell((int) j).setCellValue(result.toString());
    		}
    	}
    	
    }
    wb.write(out); 
    // 第五步,写入实体数据 实际应用中这些数据从数据库得到
	return out.toByteArray();
}

private static List<ExportFiledsBean> getExcelHead(Class<?> clazz){

	return AunotationUtil.getExportFileds(clazz);

}

private void insertCell(HSSFRow row,int i,Object object){    

    if(object==null){    

        row.createCell(i).setCellValue("");    
            
    }else{    

        row.createCell(i).setCellValue(object.toString());    
            
    }    
        
}

4、注解方法解析类

public class AunotationUtil {

代码语言:javascript
复制
/**
 * 获取注解的方法
 * [@param](https://my.oschina.net/u/2303379) clazz
 * [@return](https://my.oschina.net/u/556800)
 */
public static List<ExportFiledsBean> getExportFileds(Class<?> clazz){

	List<ExportFiledsBean> exportFiledsBeans = new ArrayList<ExportFiledsBean>();

	String clazzName = clazz.getName();

	//System.out.println("class的name:"+clazzName);

	Field[] fileds = clazz.getDeclaredFields();
	for(Field field :fileds)
	{
		if(field.isAnnotationPresent(ExportField.class))
		{
			ExportField exportField=(ExportField)field.getAnnotation(ExportField.class);
			String fieldName = field.getName();
			String name = exportField.name();
			String setFuncName = exportField.setFuncName();
			String getFuncName = exportField.getFuncName();
			boolean bl = exportField.isExport();
			
			ExportFiledsBean exportFiledsBean = new ExportFiledsBean();
			if(bl==true)
			{
				exportFiledsBean.setFiledName(fieldName);
				exportFiledsBean.setName(name);
				exportFiledsBean.setSetFuncName(setFuncName);
				exportFiledsBean.setGetFuncName(getFuncName);
				//System.out.println(fieldName+":"+name+":"+setFuncName+":"+getFuncName);
				exportFiledsBeans.add(exportFiledsBean);
			}
		}
	}
	
	return exportFiledsBeans;
}

public static void main(String[] arg)
{
	AunotationUtil.getExportFileds(ZywsptGfxwjb.class);
}

}

5、注解

@Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface ExportField {

代码语言:javascript
复制
public String name() default "filedName";
public String setFuncName() default "setField";
    public String getFuncName() default "getField";
    public boolean isExport() default false;

}

6、pojo类

public class ExportFiledsBean {

代码语言:javascript
复制
private String filedName;

private String name;

private String setFuncName;

private String getFuncName;

}

public class ZywsptGfxwjb {

代码语言:javascript
复制
@ExportField(name="编码",setFuncName="setId",getFuncName="getId",isExport=false)
private BigDecimal id;

@ExportField(name="名称",setFuncName="setMc",getFuncName="getMc",isExport=true)
private String mc;

@ExportField(name="关键字",setFuncName="setGjz",getFuncName="getGjz",isExport=true)
private String gjz;

}

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档