ssm导出列表数据

1、制作模板:


2、jsp:

<span style="font-size:12px;"><%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %> 
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta charset="utf-8">
<title></title>
<meta name="keywords" content="">
<meta name="description" content="">
<meta name="author" content="">
<META HTTP-EQUIV="Pragma" CONTENT="no-cache">
<META HTTP-EQUIV="Expires" CONTENT="-1">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="shortcut icon" href="">
</head>
<script type="text/javascript">
function enterpListExport(){
	var url = encodeURI(encodeURI('<%=request.getContextPath()%>/czevent/eventListExport.html'));
	window.open(url,'产值事件列表','');
}
</script>
<body >
   <div class="page005">
       <div class="row">
           <div class="col-xs-9">
               <div class="panel panel-ui">
                   <div class="panel-heading">
                       <form class="form-inline">
                           <div class="form-group">
                               <a href="javascript:;" οnclick="jkManage.export();" class="export action">事件导出</a>
                           </div>
                       </form>
                   </div>
                   <div class="panel-body">
                       <table class="table table-print-list">
                           <thead>
                           <tr>
                               <th>所属分类</th>
                               <th>产值事件</th>
                               <th>产值类型</th>
                               <th>产值最小值</th>
                               <th>产值最大值</th>
                               <th>经办人</th>
                               <th>审核人</th>
                               <th>管理</th>
                           </tr>
                           </thead>
                           <tbody id="body_czevent">
                           </tbody>
                       </table>
                       <nav class="text-right">
                           <ul class="pagination" id="pagination_czevent">
                           </ul>
                       </nav>
                   </div>
               </div>
           </div>
       </div>
   </div>
</body>
</html>

</span>

2、controller

<span style="font-size:12px;">
@Controller
@RequestMapping(value="/czevent")
public class CZEventController   extends Component<CzEvent>{
    private static String filename="";
    /**
     * 产值事件导出
     * @param request
     * @param response
     * @param page
     * @param entity
     */
    @RequestMapping(value="eventListExport")
    public void eventListExport(HttpServletRequest request, HttpServletResponse response,Page<CzEvent> page,CzEvent entity){
        try {
            EnterpriseInfo enterpriseInfo = this.getEnterprise(request);
            
            entity.setOrgid(enterpriseInfo.getEnterpriseid());
            this.setParams(request, entity, page);
            List<CzEvent> list = czEventService.queryByPage(page);
            for(CzEvent item : list){
                
                String opids = item.getOperatid();
                item.setOperatid(opids.split("\\|")[0]);
            
            String checkids = item.getCheckedid();
            item.setCheckedid(checkids.split("\\|")[0]);
            
            if (item.getCzparentid().equals("n")) {
                item.setCzparentid("流程内");
            }else if (item.getCzparentid().equals("w")) {
                item.setCzparentid("流程外");
            }
            
            if (item.getCztypeid().equals("1")) {
                item.setCztypeid("实产值");
            }else if (item.getCztypeid().equals("2")) {
                item.setCztypeid("虚产值");
            }else if (item.getCztypeid().equals("3")) {
                item.setCztypeid("创富产值");
            }else{
                item.setCztypeid("");
            }
        }
        
        Date currentTime = new Date();
        String nameString = new String("产值事件".getBytes("GB2312"),"8859_1");
        String tablename = nameString+(new SimpleDateFormat("yyyyMMddHHmmss").format(currentTime));
        
        Map<String, Object> data = new HashMap<String, Object>();
        data.put("list", list);
        response.setHeader("Content-disposition", "attachment; filename="+tablename+".xls");
        //定义输出类型为excel
        response.setContentType("application/msexcel");
        Excel excel = new Excel();
        excel.init("excelmodel/czeventListExport.xls", data);
        excel.writeTo(response.getOutputStream());
    } catch (Exception e) {
        log.error("操作异常",e);
        }
    }
}

</span>

3、Execl.java工具类

package com.util;

/**
 * Excel包装类。
 */
public class Excel {
	Logger logger = Logger.getLogger(Excel.class);
	/** Excel模版路径 */
	private static String REPORT_DIR = "";
	private XLSTransformer transformer = new XLSTransformer();
	private Workbook workbook;

	/**
	 * 初始化生成Excel。
	 * 
	 * @param templateFileName
	 *            模版文件名称
	 * @param model
	 *            数据模型
	 */
	public void init(String templateFileName, Map<String, ?> model) {
		try {
			String string = getClass().getResource("/").getPath();
			logger.info("Excel==============string:"+string);
			String[] strs = string.split("/");
			String path = "";
			for (int i = 0; i < strs.length - 2; i++) {
				path += strs[i] + File.separator;
			}
			path = path + templateFileName;
//			path = path.substring(1, path.length());
			logger.info(">>>>>>>>>>模板文件路径为:" + path);
			File file = new File(path);
			
			InputStream in = new FileInputStream(file);

			//InputStream in = getClass().getResourceAsStream(path);
			workbook = transformer.transformXLS(in, model);
			//transformer.t
			in.close();

		} catch (Exception e) {
			throw new BusinessException("生成Excel时发生异常。", e);
		}
	}

	/**
	 * 初始化生成多工作表的Excel。
	 * 
	 * @param data
	 *            Excel数据
	 */
	public void init(ExcelData data) {
		try {
			// 如果没有设置工作表名称列表,则根据指定的工作表名称字段自动生成。
			List<String> sheetNames = data.getSheetNames();
			if (sheetNames.isEmpty()) {
				for (Object sheetModel : data.getSheetModels()) {
					sheetNames.add(BeanUtils.getField(sheetModel,
							data.getSheetNameField()).toString());
				}
			}
			InputStream in = getClass().getResourceAsStream(
					REPORT_DIR + "/" + data.getTemplateFileName());
			workbook = transformer.transformMultipleSheetsList(in,
					data.getSheetModels(), sheetNames,
					data.getSheetModelName(), data.getOtherModel(),
					data.getStartSheetNum());
			in.close();
		} catch (Exception e) {
			throw new BusinessException("生成Excel时发生异常。", e);
		}
	}

	/**
	 * 转换成Excel文件输出流。
	 * 
	 * @return 返回Excel文件输出流。
	 */
	public ByteArrayOutputStream toOutputStream() {
		try {
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			workbook.write(out);
			out.flush();
			return out;
		} catch (Exception e) {
			throw new BusinessException("转换Excel文件输出流时发生异常。", e);
		}
	}

	/**
	 * 转换成Excel文件输入流。
	 * 
	 * @return 返回Excel文件输入流。
	 */
	public ByteArrayInputStream toInputStream() {
		try {
			ByteArrayOutputStream out = toOutputStream();
			ByteArrayInputStream in = new ByteArrayInputStream(
					out.toByteArray());
			out.close();
			return in;
		} catch (Exception e) {
			throw new BusinessException("转换Excel文件输入流时发生异常。", e);
		}
	}

	/**
	 * 将Excel文件写入到输出流。
	 * 
	 * @param out
	 *            输出流
	 */
	public void writeTo(OutputStream out) {
		try {
			workbook.write(out);
			out.flush();
			out.close();
		} catch (Exception e) {
			logger.info("Excel==============Exception:"+e.getMessage());
			throw new BusinessException("将Excel文件写入到输出流时发生异常。", e);
		}
	}

	public XLSTransformer getTransformer() {
		return transformer;
	}

	public void setTransformer(XLSTransformer transformer) {
		this.transformer = transformer;
	}

	public Workbook getWorkbook() {
		return workbook;
	}

	public void setWorkbook(Workbook workbook) {
		this.workbook = workbook;
	}
	
	
	public InputStream getInputStream(String tpath){
		InputStream in=null;
		try {
			String string = getClass().getResource("/").getPath();
			logger.info("Excel==============string:"+string);
			String[] strs = string.split("/");
			String path = "";
			for (int i = 0; i < strs.length - 2; i++) {
				path += strs[i] + File.separator;
			}
			path = path + tpath;
//			path = path.substring(1, path.length());
			logger.info(">>>>>>>>>>模板文件路径为:" + path);
			File file = new File(path);
			
			in = new FileInputStream(file);
		} catch (Exception e) {
		}
		return in;
	}
	/** 
     * 根据HSSFCell类型设置数据 
     *  
     * @param cell 
     * @return 
     */  
    public String getCellFormatValue(Cell cell) {  
        String cellvalue = "";  
        if (cell != null) {  
            // 判断当前Cell的Type  
            switch (cell.getCellType()) {  
            // 如果当前Cell的Type为NUMERIC  
            case HSSFCell.CELL_TYPE_FORMULA: {  
                // 判断当前的cell是否为Date  
                if (HSSFDateUtil.isCellDateFormatted(cell)) {  
                    // 如果是Date类型则,转化为Data格式  
                    Date date = cell.getDateCellValue();  
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");  
                    cellvalue = sdf.format(date);  
  
                } else {  
                    // 如果是纯数字  
                    // 取得当前Cell的数值  
                    BigDecimal big = new BigDecimal(cell.getNumericCellValue());  
                    cellvalue = String.valueOf(big.longValue());  
                }  
                break;  
            }  
            case HSSFCell.CELL_TYPE_NUMERIC: {  
            	 if (HSSFDateUtil.isCellDateFormatted(cell)) {  
                     // 如果是Date类型则,转化为Data格式  
                     Date date = cell.getDateCellValue();  
                     SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");  
                     cellvalue = sdf.format(date);  
   
                 } else {  
                     // 如果是纯数字  
                     // 取得当前Cell的数值  
                     BigDecimal big = new BigDecimal(cell.getNumericCellValue());  
                     cellvalue = String.valueOf(big.longValue());  
                 } 
                    // 如果是double,返回结果。  
                break;  
            }  
            // 如果当前Cell的Type为STRIN  
            case HSSFCell.CELL_TYPE_STRING:  
                // 取得当前的Cell字符串  
                cellvalue = cell.getRichStringCellValue().getString();  
                break;  
            // 默认的Cell值  
            default:  
                cellvalue = " ";  
            }  
        } else {  
            cellvalue = "";  
        }  
        return cellvalue;  
  
    }  
    
    public Iterator<Row> readExcel(String filePath) throws Exception {
         POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(filePath));  
         HSSFWorkbook workBook = new HSSFWorkbook(fs);  
         HSSFSheet sheet = workBook.getSheetAt(0);  
         Iterator<Row> it = sheet.rowIterator(); 
    	 return  it;
    }
}



导出Excel是一个常见的功能需求,以下是一种基于SSM框架的导出Excel实现方式: 1. 首先需要引入POI相关的依赖,可以在pom.xml中添加以下依赖: ``` <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>4.1.1</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>4.1.1</version> </dependency> ``` 2. 在controller中添加导出Excel的方法,如下所示: ``` @RequestMapping("/exportExcel") public void exportExcel(HttpServletResponse response) throws IOException { // 获取要导出数据 List<Student> studentList = studentService.getAllStudents(); // 创建工作簿 XSSFWorkbook workbook = new XSSFWorkbook(); // 创建工作 XSSFSheet sheet = workbook.createSheet("学生信息"); // 创建头 XSSFRow row = sheet.createRow(0); row.createCell(0).setCellValue("ID"); row.createCell(1).setCellValue("学号"); row.createCell(2).setCellValue("姓名"); row.createCell(3).setCellValue("性别"); row.createCell(4).setCellValue("出生日期"); row.createCell(5).setCellValue("地址"); row.createCell(6).setCellValue("电话"); row.createCell(7).setCellValue("照片"); row.createCell(8).setCellValue("备注"); row.createCell(9).setCellValue("所属宿舍"); // 填充数据 for (int i = 0; i < studentList.size(); i++) { row = sheet.createRow(i + 1); row.createCell(0).setCellValue(studentList.get(i).getId()); row.createCell(1).setCellValue(studentList.get(i).getStuNo()); row.createCell(2).setCellValue(studentList.get(i).getStuName()); row.createCell(3).setCellValue(studentList.get(i).getStuSex()); row.createCell(4).setCellValue(studentList.get(i).getStuBirth()); row.createCell(5).setCellValue(studentList.get(i).getStuAddress()); row.createCell(6).setCellValue(studentList.get(i).getStuPhone()); row.createCell(7).setCellValue(studentList.get(i).getStuPhoto()); row.createCell(8).setCellValue(studentList.get(i).getStuRemark()); row.createCell(9).setCellValue(studentList.get(i).getStuDormitory()); } // 设置响应头信息 response.setContentType("application/vnd.ms-excel"); response.setHeader("Content-Disposition", "attachment;filename=student.xls"); // 输出Excel文件 workbook.write(response.getOutputStream()); workbook.close(); } ``` 3. 在前端页面中添加导出Excel的按钮,并绑定到controller中的导出方法上。 ``` <a href="/exportExcel" class="btn btn-primary">导出Excel</a> ``` 以上就是基于SSM框架导出Excel的一种实现方式,通过POI库构造Excel文件,并通过HttpServletResponse对象输出Excel文件。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

雨润泽林

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值