您的位置:首页 > 编程语言 > Java开发

在EasyJWeb中使用Java Excel API 处理电子表格

2008-04-10 19:50 671 查看
  在J2EE应用开发中,由于各种各样的原因,经常会需要处理一些旧的Excel格式电子表格数据,或者是生成电子表格。  处理Excel电子表格的方法比如多,比如可以使用jdbc来像读数据库中的数据一样来读取电子表格的内容。这里演示的是使用开源的电子表格处理工具jxl,即Java Excel API来进行处理。关于jxl及相关使用,可以在网上搜索到很多资料。这里只是简单演示在EasyJWeb中的使用方法,这是前段时间公司一个项目中的应用,需要生成一特定的Excel表格,供客户端下载。  WEB MVC中Action中的代码如下:public class PersonChangeAction extends BaseCrudAction {private ExcelReportService excelReportService=ExcelReportService.getInstance();public Page doDownloadMenu(WebForm form, Module module)throws Exception {  
String town=CommUtil.null2String(form.get("queryTown"));
  String village=CommUtil.null2String(form.get("queryVillage"));
  String team=CommUtil.null2String(form.get("queryTeam"));
  String belongDept="";
  ActiveUser user=(ActiveUser)this.getCurrentUser(form);  
  if(!userService.checkAdmin(user))
  {
    belongDept=user.getDept();
  }
    ActionContext.getContext().getResponse().setContentType("application/x-msdownload");
  String fileName="XXXXX人员名单";
  if(!"".equals(town))fileName+="-"+town;
  if(!"".equals(village))fileName+="-"+village;
  if(!"".equals(team))fileName+="-"+team;
  fileName+=".xls";
  ActionContext.getContext().getResponse().setHeader("Content-Disposition","attachment; filename=/""+new String(fileName.getBytes("gbk"),"iso8859-1")+"/"");
  java.io.OutputStream out=com.easyjf.web.ActionContext.getContext().getResponse().getOutputStream();
  excelReportService.personChangeExcelList(out, belongDept, town, village, team);
  return null;
 }..} Action中的doDownloadMenu对应downloadMenu命令,这段代码注要实现了向客户端返回二进制流文件的功能,注意一些细节。其中流中的内容,即Excel表格的内容,通过ExcelReportService的personChangeExcelList方法来处理,该方法属于业务逻辑层,主要功能是把符合条件的对象,添加到Excel表格中,这个方法内容大致如下: public synchronized void personChangeExcelList(java.io.OutputStream out,String belongDept,String town,String village,String team)
 { 
  String scope = "1=1"; 
  String scope1="1=1";
  Collection paras = new ArrayList();   
 //省略部分查询代码  if(!"1=1".equals(scope))scope1+=" and personId in (select cid as personId from person where "+scope+") ";
  DbPageList pList = new DbPageList(PersonChange.class, scope1, paras);
  pList.doList(1, 500);
  try{
  jxl.write.WritableWorkbook book=jxl.Workbook.createWorkbook(out);
  jxl.write.WritableSheet sheet=book.createSheet("XXXX人员名单", 0);
  int pages=pList.getPages();
  String[] lables={"姓名","镇(乡、街道)","村(居委)","组","户主","就业方式","就业转移时间","就业转移地点","就业单位","就业工资","就业工种","联系电话"};
  for(int l=0;l   
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: