java jxl 导出 excel

import jxl.Workbook;
import jxl.write.Label;

public void compareExport(HttpServletResponse response) 
{  
	String header="字段1,字段2";        
	String column="filed1,filed2";        
	List<Map<String,Object>>  list = dao.getList();        
	export(header,column,list,"excel的名字",response); 
}

public void export(String header,String column,List<Map<String,Object>>  list,
String excelName,HttpServletResponse response) throws Exception{
	        response.setCharacterEncoding("UTF-8");  
	        response.setContentType("application/vnd.ms-excel");  
	        excelName=excelName+ new SimpleDateFormat("MMddHHmm").format(new Date())+".xls";
	        response.setHeader("Content-Disposition", "attachment; filename="  
+new String(excelName.getBytes("GB2312"), "iso8859-1"));  
	        response.setHeader("Pragma", "No-cache");  
	        response.setHeader("Cache-Control", "No-cache");  
	        response.setDateHeader("Expires", 0);  
	        // 这个地方一定要进行编码的转换要不然中文字符会出现乱码.  
	        // 设置下载头信息.end,  
	        OutputStream output = null;  
	        InputStream fis = null;  
	        try {  
	            output = response.getOutputStream();  
	            WritableWorkbook wwb = Workbook.createWorkbook(output);  
	            WritableSheet ws = wwb.createSheet("用户通讯录", 0); 
	            String[] headerArr=header.split(",");
	            String[] columnArr=column.split(",");
	            for (int i=0;i<headerArr.length;i++) {
	            	//设置表头
	            	ws.addCell(new Label(i, 0, headerArr[i]));
	            	// 设置显示长度.
	            	ws.setColumnView(i, 20); 
				}
	            for (int i = 0; i < list.size();i++) {  
	            	Map<String,Object> obj = (Map<String,Object>) list.get(i);  
	                for(int j=0;j<columnArr.length;j++){
	                	Object val=obj.get(columnArr[j]);
	                	if (null==val || "null".equals(val.toString())) {
	                		val="";
						}
	                	ws.addCell(new Label(j, i + 1, val.toString() )); 
	                }
	            }  
	            wwb.write();  
	            wwb.close();  
	        } catch (Exception e) {  
	            System.out.println("Error!");  
	            e.printStackTrace();  
	        } finally {// 正常关闭输入输出流.  
	            try {  
	                if (fis != null) {  
	                    fis.close();  
	                    fis = null;  
	                }  
	            } catch (Exception e) {  
	                e.printStackTrace();  
	            }  
	            try {  
	                if (output != null) {  
	                    output.close();  
	                    output = null;  
	                }  
	            } catch (Exception e) {  
	                e.printStackTrace();  
	            }  
	        }  
	}

猜你喜欢

转载自blog.csdn.net/calvin4cn/article/details/50884717