poi导出excel

package cn.myapps.core.dynaform.view.ejb;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;

import cn.myapps.base.action.ParamsTable;
import cn.myapps.base.dao.DAOFactory;
import cn.myapps.base.dao.DataPackage;
import cn.myapps.base.dao.HibernateSQLUtils;
import cn.myapps.base.dao.IDesignTimeDAO;
import cn.myapps.base.dao.PersistenceUtils;
import cn.myapps.base.ejb.AbstractDesignTimeProcessBean;
import cn.myapps.constans.Environment;
import cn.myapps.core.dynaform.document.dql.SQLFunction;
import cn.myapps.core.dynaform.document.ejb.Document;
import cn.myapps.core.dynaform.document.ejb.DocumentProcess;
import cn.myapps.core.dynaform.document.ejb.DocumentProcessBean;
import cn.myapps.core.dynaform.view.dao.ViewDAO;
import cn.myapps.core.macro.runner.IRunner;
import cn.myapps.core.macro.runner.JavaScriptFactory;
import cn.myapps.core.resource.ejb.ResourceProcess;
import cn.myapps.core.user.action.WebUser;
import cn.myapps.util.DbTypeUtil;
import cn.myapps.util.ProcessFactory;
import cn.myapps.util.StringUtil;
import cn.myapps.util.property.DefaultProperty;
import cn.myapps.util.sequence.Sequence;

public class ViewProcessBean extends AbstractDesignTimeProcessBean implements ViewProcess {
 static final Logger log = Logger.getLogger(ViewProcessBean.class);
 static final int LINES = 100;// 每页显示100条数据
 private int jTemp = 0;// 作为j的中间变量

 /**
  * @see cn.myapps.base.dao.IDesignTimeDAO#buildSessionFactory()
  */
 protected IDesignTimeDAO getDAO() throws Exception {
  return DAOFactory.getDefaultDAO(View.class.getName());
 }

 /**
  * 根据视图名与应用标识查询,返回视图对象
  *
  * @param name
  *            视图名
  * @param application
  *            应用标识
  * @return 视图对象
  * @throws Exception
  */
 public View getViewByName(String name, String application) throws Exception {
  View view = ((ViewDAO) getDAO()).findViewByName(name, application);
  return view;
 }

 /**
  * 根据应用标识查询,返回视图集合
  *
  * @param application
  *            应用标识
  * @return 视图集合
  * @throws Exception
  */
 public Collection get_viewList(String application) throws Exception {
  return this.doSimpleQuery(null, application);
  // return ((ViewDAO) getDAO()).simpleQuery(null, application);
 }

 /**
  * 根据模块主键与应用标识查询,返回视图(view)的DataPackage.
  *
  * @param moduleid
  *            模块主键
  * @param application
  *            应用标识
  * @return 视图(view)的DataPackage
  * @throws Exception
  */
 public DataPackage getViewsByModuleId(String moduleid, String application) throws Exception {
  return ((ViewDAO) getDAO()).getViewsByModuleId(moduleid, application);
 }

 /**
  * 根据模块主键与应用标识查询,返回视图(view)的集合
  *
  * @param moduleid
  *            模块主键
  * @param application
  *            应用标识
  * @return 视图(view)的集合
  * @throws Exception
  */
 public Collection getViewsByModule(String moduleid, String application) throws Exception {
  return ((ViewDAO) getDAO()).getViewByModule(moduleid, application);
 }

 /**
  * 根据View主键,删除值对象
  *
  * @param pk
  *            VIEW 主键
  * @see cn.myapps.base.ejb.IDesignTimeProcess#doRemove(String)
  */
 public void doRemove(String pk) throws Exception {
  try {
   PersistenceUtils.beginTransaction();
   ResourceProcess rp = (ResourceProcess) ProcessFactory.createProcess(ResourceProcess.class);
   View view = (View) getDAO().find(pk);

   String rid = view.getRelatedResourceid();
   if (rid != null) {
    rp.doRemove(rid);
   }
   getDAO().remove(pk);
   PersistenceUtils.commitTransaction();
  } catch (Exception e) {
   e.printStackTrace();
   PersistenceUtils.rollbackTransaction();
  }
 }

 /**
  * 把视图中显示的文档转换为Excel文件
  *
  * @param viewid
  * @param user
  * @param params
  *            {filename: 文件名, filedir: 文件所在目录, formfiled: 表单各字段值}
  * @throws Exception
  */
 public String expDocToExcel(String viewid, WebUser user, ParamsTable params) throws Exception {
  View view = (View) doView(viewid);// 查找出相应的视图

  if (view != null) {
   ArrayList errors = new ArrayList();
   DataPackage datas = null;
   Collection excelData = null;
   Collection heads = null;
   boolean firstCreateExcel = true;
   boolean endCreateExcel = false;

   HSSFWorkbook workbook = null;
   HSSFSheet sheet = null;
   HSSFCellStyle cellStyle = null;
   POIFSFileSystem fs = null;

   int pageSize = 0;// 总页数

   Document currdoc = new Document();

   if (view.getSearchForm() != null) {
    currdoc = view.getSearchForm().createDocument(params, user);
   }

   IRunner runner = JavaScriptFactory.getInstance(params.getSessionid(), view.getApplicationid());

   int count = (int) view.getEditModeType().count(params, user, currdoc);// 获得总条数
   // System.out.println("----->count:"+count);

   if (count > 0) {
    // 获得总页数
    if ((int) (count % LINES) != 0) {
     pageSize = count / LINES + 1;
    } else {
     pageSize = count / LINES;
    }

    // 分页查询写Excel文件
    for (int tempPage = 1; tempPage <= pageSize; tempPage++) {
     datas = view.getEditModeType().getDataPackage(params, tempPage, LINES, user, currdoc);

     heads = this.getHeads(view);
     excelData = this.getExcelData(datas, view, user, params, runner, errors);

     // 判断是否第一次加载数据
     if (tempPage == 1) {
      if (tempPage == pageSize) {
       endCreateExcel = true;
      }
      // 创建新的Excel 工作簿
      workbook = new HSSFWorkbook();
      sheet = workbook.createSheet();
      cellStyle = workbook.createCellStyle();

      creatExcelFile(workbook, cellStyle, sheet, heads, excelData, getSavePath(params), firstCreateExcel,
        endCreateExcel);
      firstCreateExcel = false;

     } else {
      // 判断是否是最后一次加载数据
      if (tempPage == pageSize) {
       endCreateExcel = true;
      }
      fs = new POIFSFileSystem(new FileInputStream(getSavePath(params)));
      workbook = new HSSFWorkbook(fs);
      sheet = workbook.getSheetAt(0);
      cellStyle = workbook.getCellStyleAt((short) 0);
      creatExcelFile(workbook, cellStyle, sheet, heads, excelData, getSavePath(params), firstCreateExcel,
        endCreateExcel);
     }

    }
    firstCreateExcel = true;
    endCreateExcel = false;
    jTemp = 0;
   }

   String fileName = params.getParameterAsString("filename").toLowerCase().trim();
   if (StringUtil.isBlank(fileName)) {
    fileName = Sequence.getSequence();
   }
   fileName += ".xls";
   return fileName;
  } else {
   throw new Exception("{*[View.is.not.exist]*}");
  }
 }

 /**
  * 获得保存目录
  *
  * @param excelData
  * @param params
  * @return
  * @throws Exception
  */
 public String getSavePath(ParamsTable params) throws Exception {

  // 生成保存目录
  String fileDir = params.getParameterAsString("filedir");
  if (StringUtil.isBlank(fileDir)) {
   fileDir = DefaultProperty.getProperty("REPORT_PATH");
  }

  String savePath = Environment.getInstance().getRealPath(fileDir);
  File saveDir = new File(savePath);
  if (!saveDir.exists()) {
   saveDir.mkdirs();
  }
  // 生成文件
  String fileName = params.getParameterAsString("filename").toLowerCase().trim();
  if (StringUtil.isBlank(fileName)) {
   fileName = Sequence.getSequence();
  }
  fileName += ".xls";

  if (savePath.lastIndexOf("/") < 0 && savePath.lastIndexOf("\\") < 0) {
   savePath += savePath + "/" + fileName;
  } else {
   savePath += fileName;
  }

  return savePath;

 }

 /**
  * 获得存入Excel数据
  *
  * @param datas
  * @param view
  * @param user
  * @param params
  * @param runner
  * @param errors
  * @return
  * @throws Exception
  */
 public Collection getExcelData(DataPackage datas, View view, WebUser user, ParamsTable params, IRunner runner,
   ArrayList errors) throws Exception {
  Collection excelData = new ArrayList();// excel数据
  Collection columns = view.getColumns();
  for (Iterator iter = datas.datas.iterator(); iter.hasNext();) {
   Document doc = (Document) iter.next();
   runner.initBSFManager(doc, params, user, errors);
   Object result = null;

   Map line = new HashMap();
   for (Iterator iterator = columns.iterator(); iterator.hasNext();) {
    Column col = (Column) iterator.next();
    result = col.getTextString(doc, runner, user);
    String resultStr=result.toString();
    resultStr = resultStr.replaceAll("<[^>]*>", "");
    //if(resultStr.)
    line.put(col.getName(), resultStr);
   }

   excelData.add(line);
   log.info("line(" + excelData.size() + ")..........");
  }

  return excelData;
 }

 /**
  * 获得Excel的头
  *
  * @param datas
  * @param view
  * @return
  * @throws Exception
  */
 public Collection getHeads(View view) throws Exception {
  Collection heads = new ArrayList();// excel头
  Collection columns = view.getColumns();

  for (Iterator iter = columns.iterator(); iter.hasNext();) {
   Column col = (Column) iter.next();
   heads.add(col.getName());
  }

  return heads;
 }

 /**
  * 创建新的Excel 工作簿
  *
  * @param heads
  * @param datas
  * @param outputFile
  *            创建新的Excel
  * @throws IOException
  */

 public void creatExcelFile(HSSFWorkbook workbook, HSSFCellStyle cellStyle, HSSFSheet sheet, Collection heads,
   Collection datas, String outputFile, boolean firstCreateExcel, boolean endCreateExcel) throws IOException {

  if (heads != null && datas != null && datas.size() > 0) {
   if (firstCreateExcel) {
    cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy"));
    HSSFRow headrow = sheet.createRow((short) 0);
    int i = 0;
    for (Iterator iter = heads.iterator(); iter.hasNext();) {
     String head = (String) iter.next();
     HSSFCell cell = headrow.createCell((short) i);
     cell.setEncoding(HSSFCell.ENCODING_UTF_16);
     cell.setCellType(HSSFCell.CELL_TYPE_STRING);
     cell.setCellValue(head);
     i++;
    }
   }

   int j = 0;
   if (firstCreateExcel) {
    j = 1;
   } else {
    j = jTemp + 1;
   }
   for (Iterator iter = datas.iterator(); iter.hasNext();) {
    Map map = (Map) iter.next();
    HSSFRow row = sheet.createRow((short) j);
    int k = 0;
    for (Iterator iterator = heads.iterator(); iterator.hasNext();) {
     String columnName = (String) iterator.next();
     Object result = (Object) map.get(columnName);
     HSSFCell cell = row.createCell((short) k);
     cell.setEncoding(HSSFCell.ENCODING_UTF_16);

     if (result instanceof String) {
      cell.setCellType(HSSFCell.CELL_TYPE_STRING);
      cell.setCellValue((String) result);
     } else if (result instanceof Double) {
      cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
      cell.setCellValue(((Double) result).doubleValue());
     } else if (result instanceof Date) {
      cell.setCellStyle(cellStyle);
      cell.setCellValue((Date) result);
     }
     k++;
    }
    j++;
   }
   jTemp += datas.size();
  }

  if (firstCreateExcel) {
   FileOutputStream fOut = new FileOutputStream(outputFile);
   // 把相应的Excel 工作簿存盘
   workbook.write(fOut);
   fOut.flush();

   // 操作结束,关闭文件
   fOut.close();

   log.info("Excel文件生成.................");
  }

  // 新建一输出文件流
  FileOutputStream fOut = new FileOutputStream(outputFile);
  // 把相应的Excel 工作簿存盘
  workbook.write(fOut);
  fOut.flush();

  // 操作结束,关闭文件
  fOut.close();

  log.info("Excel文件追加成功.................");

 }

 /**
  *
  * @param view
  *            视图
  * @param params
  *            参数
  * @param user
  *            当前用户
  * @param sDoc
  *            查询文档
  * @return
  */
 public String getQueryString(View view, ParamsTable params, WebUser user, Document sDoc) {
  try {
   return view.getEditModeType().getQueryString(params, user, sDoc);
  } catch (Exception e) {
   e.printStackTrace();
  }

  return "";
 }

 public DataPackage getDataPackage(View view, ParamsTable params, WebUser user, String applicationid, Date stDate,
   Date endDate, int lines) throws Exception {
  DocumentProcess dp = new DocumentProcessBean(applicationid);
  DataPackage datas = null;
  Document doc = null;
  String _currpage = params.getParameterAsString("_currpage");
  int page = (_currpage != null && _currpage.length() > 0) ? Integer.parseInt(_currpage) : 1;
  if (view.getSearchForm() != null) {
   try {
    doc = view.getSearchForm().createDocument(params, user);
   } catch (Exception e) {
    e.printStackTrace();
   }
  } else {
   doc = new Document();
  }
  SQLFunction sqlFuction = DbTypeUtil.getSQLFunction(applicationid);
  SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  String fielter = "";
  String fieldName = view.getRelationDateColum();
  if (fieldName.toUpperCase().trim().startsWith("$")) {
   fielter = sqlFuction.toChar(fieldName.substring(1), "yyyy-MM-dd HH:mm:ss") + ">= '" + format.format(stDate)
     + "' and ";
   fielter += sqlFuction.toChar(fieldName.substring(1), "yyyy-MM-dd HH:mm:ss") + "<= '" + format.format(endDate) + "'";
  } else {
   fielter = sqlFuction.toChar("ITEM_" + fieldName, "yyyy-MM-dd HH:mm:ss") + ">= '" + format.format(stDate) + "' and ";
   fielter += sqlFuction.toChar("ITEM_" + fieldName, "yyyy-MM-dd HH:mm:ss") + "<= '" + format.format(endDate) + "'";
  }
  
  HibernateSQLUtils sqlUtil = new HibernateSQLUtils();
  if (view.getEditMode().equals(View.EDIT_MODE_DESIGN)) {
   String sql = getQueryString(view, params, user, doc);
   sql = sqlUtil.appendCondition(sql, fielter);
   datas = dp.queryBySQLPage(sql, params, page, lines, user.getDomainid());
  } else if (view.getEditMode().equals(View.EDIT_MODE_CODE_DQL)) {
   String dql = getQueryString(view, params, user, doc);
   dql += " AND #T" + fieldName + ">= '" + format.format(stDate) + "' and #T" + fieldName + "<= '"
     + format.format(endDate) + "'";
   datas = dp.queryByDQLPage(dql, params, page, lines, user.getDomainid());
  } else if (view.getEditMode().equals(View.EDIT_MODE_CODE_SQL)) {
   String sql = getQueryString(view, params, user, doc);
   sql = sqlUtil.appendCondition(sql, fielter);
   datas = dp.queryBySQLPage(sql, params, page, lines, user.getDomainid());
  }
  return datas;
 }
 
 /**
  * 根据视图名与模块标识查询,返回是否视图对象
  *
  * @param name
  *            视图名
  * @param module
  *            模块标识
  * @return 是否视图对象
  * @throws Exception
  */
 public boolean get_existViewByNameModule(String name, String module)
   throws Exception {
  return ((ViewDAO) getDAO()).existViewByNameModule(name, module);
 }
}

你可能感兴趣的:(poi导出excel)