jxls2.*系列(最新版本2.3.0)是基于jdk7的,项目必须为1.7以上才可以用2.*系列
以下例子基于1.*系列,
(2.*系列excel模板的设计是使用excel批注实现,1.*系列使用标签实现)
0:pom中引入jar包
net.sf.jxls jxls-core 1.0.6 net.sf.jxls jxls-reader 1.0.6
1:定义view
import java.io.InputStream; import java.io.OutputStream; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.sf.jxls.transformer.XLSTransformer; import org.apache.poi.ss.usermodel.Workbook; import org.springframework.web.servlet.view.AbstractView; public class JxlsExcelView extends AbstractView { private static final String CONTENT_TYPE = "application/vnd.ms-excel"; private String templatePath; private String exportFileName; /** * @param templatePath 模版相对于当前classpath路径 * @param exportFileName 导出文件名 */ public JxlsExcelView(String templatePath, String exportFileName) { this.templatePath = templatePath; this.exportFileName = exportFileName; setContentType(CONTENT_TYPE); } @Override protected void renderMergedOutputModel(Mapmodel, HttpServletRequest request, HttpServletResponse response) throws Exception { InputStream is = null; OutputStream os = null; os = response.getOutputStream(); response.setContentType(getContentType()); // 解决导出文件名中文乱码 String filename = new String(exportFileName.getBytes("gb2312"), "iso8859-1"); response.setHeader("content-disposition", "attachment;filename=" + filename + ".xls"); // 获取excel模板 is = JxlsExcelView.class.getClassLoader().getResourceAsStream(templatePath); //转换成excel并输出 XLSTransformer transformer = new XLSTransformer(); Workbook workbook = transformer.transformXLS(is, model); //将内容写入输出流并把缓存的内容全部发出去 workbook.write(os); os.flush(); os.close(); is.close(); } }
2:resources/jxls/template中设计模板online_user.xls
3:调用
// 导出 @RequestMapping public ModelAndView export(ActionContext context, HttpServletResponse response) throws Exception { // 1:准备数据 ListuserList = getUserList(); // 2:数据放置到jxls需要的map中 Map modal = new HashMap (); modal.put("users", userList); modal.put("totalCount", userList.size()); // 3:导出文件 return new ModelAndView(new JxlsExcelView("jxls/template/online_user.xls","在线用户列表"), modal); }