普元eos根據查詢條件導出excel表格

1.在WEB/WEB-INF建造一個excel-config文件夾,在此文件夾裏放入要導出數據的xls文檔。

xls文檔裏每一列的列名即是“#”+數據庫的字段名,例如:

2.建造幫助類

(1)。ChangeUtil

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Enumeration;
import java.util.StringTokenizer;
import java.util.Vector;

/**
 *
 * 轉換工具類
 *
 * @author primeton
 * wengzr (mailto:)
 */
 
public class ChangeUtil {
 /**
  * 時間格式(年月日)
  */
 public static final String DATE_FORMAT_YMD = "yyyyMMdd";
 /**
  * 時間格式(年月)
  */
 public static final String DATE_FORMAT_YM = "yyyyMM";
 /**
  * 時間格式(年)
  */
 public static final String DATE_FORMAT_Y = "yyyy";
 
 public static final String DATE_FORMAT_YMD_HMS="yyyy-MM-dd HH:mm:ss";
 
 /**
  * ChangeUtil類的缺省構造器。
  */
 private ChangeUtil() {
 }
 
 /**
  * 將一個以','分割的字符串,轉換爲一個Vector對象。這是changeStringToVector(String str, String token)的簡化版本。
  *
  * @param _str 需要轉換的字符串
  * @return 包含了字符串中元素的Vector對象。
  * @see #changeStringToVector
  */
 public static Vector changeStringToVector(String _str){
  return changeStringToVector(_str, ",");
 }
 /**
  * 將一個以字符串token分割的字符串,轉換爲一個Vector對象。如"姓名[token]年齡"被轉換爲一個Vector,該Vector包含兩個元素,第一個是"姓名",第二個是"年齡"。
  *
  * @param _str 需要轉換的字符串
  * @param _token 字符串中分割的token。如空格" ",或":"等。
  * @return 包含了字符串中元素的Vector對象。
  */
 public static Vector changeStringToVector(String _str, String _token) {
  if( _str== null) {
   return null;
  }
 
  Vector<String> temp = new Vector<String>();
  StringTokenizer st = new StringTokenizer(_str, _token);
  while (st.hasMoreTokens()) {
   temp.add(st.nextToken());
  }
  return temp;
 }
 /**
  * 將一個Vector對象中保存的字符串元素使用","分隔符轉換爲一個字符串,這是public static Vector changeStringToVector(String str)的逆操作。
  *
  * @param _v 包含了字符串數據元素的Vector對象
  * @return 一個以","爲分隔符的字符串
     */
 public static String changeVectorToString(Vector _v) {
  return changeVectorToString(_v, ",");
 }
 /**
  * 將一個Vector對象中保存的字符串元素使用token分隔符轉換爲一個字符串,
  * 這是public static Vector changeStringToVector(String str, String token)的逆操作。
  * @param _v 包含了字符串數據元素的Vector對象
  * @param _token 字符串中分割的token。如空格" ",或":"等。
  * @return 一個以token爲分隔符的字符串
  */
 public static String changeVectorToString(Vector _v, String _token) {
  if( _v == null) {
   return null;
  }
  Enumeration enumeration = _v.elements();
  String str = "";
  while (enumeration.hasMoreElements()) {
   str = str + (String) (enumeration.nextElement()) + _token;
  }
  str = str.substring(0, str.length() - 1);
  return str;
 }
 /**
  * 將一個字符串數組中保存的字符串元素使用","分隔符轉換爲一個字符串。
  *
  * @param _strArray 包含了字符串數據元素的字符串數組
  * @return 一個以","爲分隔符的字符串
  * @see #changeArrayToString
  */
 public static String changeArrayToString(String[] _strArray) {
  return changeArrayToString(_strArray, ",");
 }
 /**
  * 將一個字符串數組中保存的字符串元素使用token分隔符轉換爲一個字符串,
  * 這是public static Vector changeStringToVector(String str, String token)的逆操作。
  * @param _strArray 包含了字符串數據元素的字符串數組
  * @param _token 分隔字符串使用的分隔符。
  * @return 一個以token爲分隔符的字符串
  */
 public static String changeArrayToString(String[] _strArray,String _token) {
  if( _strArray == null) {
   return null;
  }
  int size = _strArray.length;
  if (size == 0) {
   return null;
  } else if (size == 1) {
   return _strArray[0];
  } else {
   String temp = _strArray[0];
   for (int i = 1; i < size; i++) {
    temp = temp + _token + _strArray[i];
   }
   return temp;
  }
 }
 /**
  * 將一個使用","分隔符分隔的字符串,轉變爲一個字符串數組。
  *
  * @param _str 用token分隔符分隔的字符串
  * @return 字符串數組
  */
 public static String[] changeStringToArray(String _str) {
  return changeStringToArray(_str, ",");
 }
 /**
  * 將一個使用token分隔符分隔的字符串,轉變爲一個字符串數組。
  *
  * @param _str 用token分隔符分隔的字符串
  * @param _token 字符串的分隔符
  * @return 字符串數組
  */
 public static String[] changeStringToArray(String _str, String _token) {
  if( _str ==null) {
   return null;
  }
  Vector v = changeStringToVector(_str, _token);
  String[] strArray = new String[v.size()];
  int i = 0;
  for (Enumeration em = v.elements(); em.hasMoreElements(); i++) {
   strArray[i] = (String) em.nextElement();
  }
  return strArray;
 }
 /**
  * 獲得以參數_fromDate爲基數的年齡
  *
  * @param _birthday 生日
  * @param _fromDate 起算時間
  * @return 年齡(起算年-出生年)
  */
 public static int getAgeFromBirthday(java.util.Date _birthday,java.util.Date _fromDate) {
  Calendar calendar =  Calendar.getInstance();
  calendar.setTime(_birthday);
  int birthdayYear = calendar.get(Calendar.YEAR);
  int birthdayMonth = calendar.get(Calendar.MONTH);
  int birthdayDay = calendar.get(Calendar.DAY_OF_MONTH);
  calendar.clear();
  calendar.setTime(_fromDate);
  int currentYear = calendar.get(Calendar.YEAR);
  int currentMonth = calendar.get(Calendar.MONTH);
  int currentDay = calendar.get(Calendar.DAY_OF_MONTH);
  calendar.clear();
  int age = currentYear - birthdayYear;
  if (!((currentMonth >= birthdayMonth)&& (currentDay >= birthdayDay))) {
   age--;
  }
  return age;
 }
 /**
  * 獲得當前年齡
  *
  * @param _birthday 生日
  * @return 年齡(起算年-出生年)
  */
 public static int getAgeFromBirthday(java.util.Date _birthday) {
  return getAgeFromBirthday(_birthday,new java.util.Date(System.currentTimeMillis()));
 }
 /**
  * 獲得當前年齡
  *
  * @param _birthday 生日
  * @return 年齡(起算年-出生年)
  */
 public static int getAgeFromBirthday(java.sql.Timestamp _birthday) {
  return getAgeFromBirthday(new java.util.Date(_birthday.getTime()),new java.util.Date(System.currentTimeMillis()));
 }
 /**
  * 使用格式{@link #DATE_FORMAT_YMD}格式化日期輸出
  *
  * @param _date 日期對象
  * @return 格式化後的日期
  */
 public static String formatDate(java.util.Date _date) {
  return formatDate(_date, DATE_FORMAT_YMD);
 }
 /**
  * 使用格式<b>_pattern</b>格式化日期輸出
  *
  * @param _date 日期對象
  * @param _pattern 日期格式
  * @return 格式化後的日期
  */
 public static String formatDate(java.util.Date _date, String _pattern) {
  if( _date == null) {
   return null;
  }
  SimpleDateFormat simpleDateFormat = new SimpleDateFormat(_pattern);
  String stringDate = simpleDateFormat.format(_date);
  return stringDate;
 }
 /**
  * 使用中文字符以簡單的形式("年 月 日")格式化時間串
  *
  * @param _date 日期對象
  * @return 格式化後的日期
  */
 public static String simplefFormatChineseDate(java.util.Date _date) {
  if( _date == null) {
   return null;
  }
  Calendar calendar =  Calendar.getInstance();
  calendar.setTime(_date);
  StringBuffer sb = new StringBuffer();
  sb.append(calendar.get(Calendar.YEAR))
   .append("年")
   .append(calendar.get(Calendar.MONTH) + 1)
   .append("月")
   .append(Calendar.DAY_OF_MONTH)
   .append("日");
  calendar.clear();
  return sb.toString();
 }
 /**
  * 使用中文字符以複雜的形式("年 月 日 上午 時 分 秒")格式化時間串
  *
  * @param _date 日期對象
  * @return 格式化後的日期
  */
 public static String complexFormatChineseDate(java.util.Date _date) {
  if( _date == null) {
   return null;
  }
  Calendar calendar =  Calendar.getInstance();
  calendar.setTime(_date);
  StringBuffer sb = new StringBuffer();
  sb.append(calendar.get(Calendar.YEAR))
   .append("年")
   .append(calendar.get(Calendar.MONTH) + 1)
   .append("月")
   .append(Calendar.DAY_OF_MONTH)
   .append("日")
   .append(Calendar.HOUR_OF_DAY)
   .append("時")
   .append(Calendar.MINUTE)
   .append("分")
   .append(Calendar.SECOND)
   .append("秒");
  calendar.clear();
  return sb.toString();
 }
 /**
  * 將時間串轉變爲時間對象,輸入參數<b>_dateStr</b>必須遵循格式{@link #DATE_FORMAT_YMD}
  *
  * @param _dateStr 時間串
  * @return 時間對象
  */
 public static java.util.Date changeToDate(String _dateStr) throws IllegalArgumentException{
  return changeToDate(_dateStr, DATE_FORMAT_YMD);
 }
 /**
  * 將時間串轉變爲時間對象
  *
  * @param _dateStr 時間串
  * @param _pattern 時間串使用的模式
  * @return 時間對象
  * @throws ParamValidateException 當輸入的時間串和它使用的模式不匹配時擲出
  */
 public static java.util.Date changeToDate(String _dateStr,String _pattern) throws IllegalArgumentException  {
  if (_dateStr == null || _dateStr.trim().equals("")) {
   return null;
  }
  java.util.Date date = null;
  SimpleDateFormat format = new SimpleDateFormat(_pattern);
  try {
   date = format.parse(_dateStr);
  } catch (java.text.ParseException pe) {
   throw new IllegalArgumentException("不能使用模式:[" + _pattern + "]格式化時間串:[" + _dateStr + "]");
  }
  return date;
 }
 /**
  * 將時間串轉變爲數據庫時間對象,輸入參數<b>_dateStr</b>必須遵循格式{@link #DATE_FORMAT_YMD}
  *
  * @param _dateStr 時間串
  * @return 數據庫時間對象
  */
 public static java.sql.Date changeToDBDate(String _dateStr) throws IllegalArgumentException{
  return changeForDBDate(changeToDate(_dateStr, DATE_FORMAT_YMD));
 }
 /**
  * 將時間串轉變爲數據庫時間對象
  *
  * @param _dateStr 時間串
  * @param _pattern 時間串使用的模式
  * @return 時間對象
  * @throws ParamValidateException 當輸入的時間串和它使用的模式不匹配時擲出
  */
 public static java.sql.Date changeToDBDate(String _dateStr,String _pattern) throws IllegalArgumentException {
  return changeForDBDate(changeToDate(_dateStr, _pattern));
 }
 /**
  * 將java.util.Date對象轉換爲java.sql.Date對象
  *
  * @param _date 待轉化的java.util.Date 對象
  * @return java.sql.Date對象
  */
 public static java.sql.Date changeForDBDate(java.util.Date _date) {
  if (_date == null) {
   return null;
  }
  return new java.sql.Date(_date.getTime());
 }
 /**
  * 將java.sql.Date對象轉換爲java.util.Date對象
  *
  * @param _date 待轉化的java.sql.Date對象
  * @return java.util.Date對象
  */
 public static java.util.Date changFromDBDate(java.sql.Date _date) {
  return (java.util.Date) _date;
 }
 /**
  * 將java.util.Date對象轉換爲java.sql.Timestamp對象
  *
  * @param _date 待轉化的java.util.Date 對象
  * @return java.sql.Timestamp對象
  */
 public static java.sql.Timestamp changeToTimestamp(java.util.Date _date) {
  if (_date == null) {
   return null;
  }
  return new java.sql.Timestamp(_date.getTime());
 }
 /**
  * 將java.sql.Timestamp對象轉換爲java.util.Date對象
  *
  * @param _date 待轉化的java.sql.Timestamp 對象
  * @return java.util.Date 對象
  */
 public static java.util.Date changeFromTimestamp(java.sql.Timestamp _date) {
  return (java.util.Date) _date;
 }
 /**
  * 改變字符串的編碼方式(ISO8859_1)爲(GBK),以支持中文
  *
  * @param _str 待轉變的字符串
  * @return 採用GBK編碼的字符串
  */
 public static String changeToGB(String _str) throws Exception{
  if( _str == null) {
   return null;
  }
  String gbStr = null;
  try {
   gbStr = new String(_str.getBytes("ISO8859_1"), "GBK");
  } catch (Exception e) {
   throw e;
  }
  return gbStr;
 }
 /**
  * 改變字符串的編碼方式(GBK)爲(ISO8859_1)
  *
  * @param _str 待轉變的字符串
  * @return 採用ISO8859_1編碼的字符串
  */
 public static String changeFromGB(String _str)throws Exception {
  if( _str == null) {
   return null;
  }
  String isoStr = null;
  try {
   isoStr = new String(_str.getBytes("GBK"), "ISO8859_1");
  } catch (Exception e) {
   throw e;
  }
  return isoStr;
 }
 /**
  * 獲得日期的年
  *
  * @param _date 日期對象
  * @return 日期的年
  */
 public static int getYear(java.util.Date _date) {
 
  Calendar calendar =  Calendar.getInstance();
  calendar.setTime(_date);
  int year = calendar.get(Calendar.YEAR);
  calendar.clear();
  return year;
 }
 /**
  * 獲得日期的月
  *
  * @param _date 日期對象
  * @return 日期的月
  */
 public static int getMonth(java.util.Date _date) {
  Calendar calendar =  Calendar.getInstance();
  calendar.setTime(_date);
  // 以0開始
  int month = calendar.get(Calendar.MONTH);
  calendar.clear();
  return (month + 1);
 }
 /**
  * 獲得日期的天,以月爲基
  *
  * @param _date 日期對象
  * @return 日期的天
  */
 public static int getDay(java.util.Date _date) {
  Calendar calendar = Calendar.getInstance();
  calendar.setTime(_date);
  int day = calendar.get(Calendar.DAY_OF_MONTH);
  calendar.clear();
  return day;
 }
 /**
  * 獲得日期的小時
  *
  * @param _date 日期對象
  * @return 日期的小時
  */
 public static int getHours(java.util.Date _date) {
  Calendar calendar =  Calendar.getInstance();
  calendar.setTime(_date);
  int value = calendar.get(Calendar.HOUR);
  calendar.clear();
  return value;
 }
 /**
  * 獲得日期的分鐘
  *
  * @param _date 日期對象
  * @return 日期的分鐘
  */
 public static int getMinutes(java.util.Date _date) {
  Calendar calendar =  Calendar.getInstance();
  calendar.setTime(_date);
  int value = calendar.get(Calendar.MINUTE);
  calendar.clear();
  return value;
 }
 /**
  * 獲得日期的小秒
  *
  * @param _date 日期對象
  * @return 日期的秒
  */
 public static int getSeconds(java.util.Date _date) {
  Calendar calendar =  Calendar.getInstance();
  calendar.setTime(_date);
  int value = calendar.get(Calendar.SECOND);
  calendar.clear();
  return value;
 }
 /**
  * 計算兩個日期間相隔的天數
  *
  * @param _startDate 起始日期
  * @param _endDate 終止日期
  * @return 相隔天數, 如果結果爲正表示<b>_endDate</b>在<b>_startDate</b>之後;如果結果爲負表示<b>_endDate</b>在<b>_startDate</b>之前;
  * 如果結果爲0表示<b>_endDate</b>和<b>_startDate</b>是同一天。
  */
 public static int getDayCount(java.util.Date _startDate,java.util.Date _endDate) {
  Calendar calendar =  Calendar.getInstance();
  calendar.setTime(_startDate);
  int startDay = calendar.get(Calendar.DAY_OF_YEAR);
  int startYear = calendar.get(Calendar.YEAR);
  calendar.clear();
  calendar.setTime(_endDate);
  int endDay = calendar.get(Calendar.DAY_OF_YEAR);
  int endYear = calendar.get(Calendar.YEAR);
  calendar.clear();
  return (endYear - startYear) * 365 + (endDay - startDay);
 }
 /**
  * 獲得兩個Date間的月數, 天數超過14天算1個月
  *
  * @param _startDate 開始時間
  * @param _endDate 結束時間
  * @return 兩個Date間的月數
  */
 public static int getMonthAmount(java.sql.Date _startDate,java.sql.Date _endDate) {
  int nYear = 0;
  int nMonth = 0;
  int nDay = 0;
  int nMonthAmount = 0;
  Calendar cldStart = Calendar.getInstance();
  Calendar cldEnd = Calendar.getInstance();
  cldStart.setTime(_startDate);
  cldEnd.setTime(_endDate);
  nYear = cldEnd.get(Calendar.YEAR) - cldStart.get(Calendar.YEAR);
  nMonth = cldEnd.get(Calendar.MONTH) - cldStart.get(Calendar.MONTH);
  nDay = cldEnd.get(Calendar.DATE) - cldStart.get(Calendar.DATE);
  if (nDay > 14) {
   nMonthAmount = nYear * 12 + nMonth + 1;
  } else {
   nMonthAmount = nYear * 12 + nMonth;
  }
  return nMonthAmount;
 }
 /**
  * 格式化長整形數
  *
  * @param _inStrObj 長整形字串對象
  * @return 長整形數
  */
 public static long toLong(Object _inStrObj) {
  if (_inStrObj == null || _inStrObj.toString().trim().equals("")) {
   return 0;
  } else {
   return Long.valueOf(_inStrObj.toString()).longValue();
  }
 }
 /**
  * 格式化整形數
  *
  * @param _inStrObj 整形數字串對象
  * @return 整形數
  */
 public static int toInteger(Object _inStrObj) {
  if (_inStrObj == null || _inStrObj.toString().trim().equals("")) {
   return 0;
  } else {
   return new Integer(_inStrObj.toString()).intValue();
  }
 }
 /**
  * 格式化雙精浮點數
  *
  * @param _inStrObj 雙精浮點數字串對象
  * @return 雙精度浮點數,
  */
 public static double toDouble(Object _inStrObj) {
  if (_inStrObj == null || _inStrObj.toString().trim().equals("")) {
   return 0;
  } else {
   return Double.valueOf(_inStrObj.toString()).doubleValue();
  }
 }
 /**
  * 格式化浮點數
  *
  * @param _inStrObj 浮點數字串對象
  * @return 浮點數,如果數據格式錯誤,或字串爲空,這返回0
  */
 public static float toFloat(Object _inStrObj) {
  if (_inStrObj == null || _inStrObj.toString().trim().equals("")) {
   return 0;
  } else {
   return Float.valueOf(_inStrObj.toString()).floatValue();
  }
 }
 /**
  * 將字節數組採用編碼<b>_encoding</b>轉化爲字符串
  *
  * @param _bytes 字節數組
  * @param _encoding 編碼方式
  * @throws ParamValidateException 如果編碼方式不支持時擲出
  * @return 字符串
  */
 public static String toStr(byte[] _bytes, String _encoding) throws IllegalArgumentException{
  if( _bytes == null) {
   return null;
  }
 
  String s = null;
  try {
   s = new String(_bytes, _encoding);
  } catch (Exception e) {
   throw new IllegalArgumentException("不支持的編碼方式:" + _encoding);
  }
  return s;
 }
 /**
  * 格式化布爾對象
  *
  * @param _boolean 布爾對象
  * @return 布爾對象的值,如果<b>_boolean</b>爲null, 返回false
  */
 public static boolean toBoolean(Boolean _boolean) {
  if (_boolean == null) {
   return false;
  } else {
   return _boolean.booleanValue();
  }
 }
 /**
  * 獲得對象的字符串表示, 當<b>_obj</b>爲null時用<b>_replaceStr</b>替代
  *
  * @param _obj 對象
  * @param _replaceStr 替代null值的字符串
  * @return 處理後的字符串
  */
 public static String toStr(Object _obj, String _replaceStr) {
  if (_obj == null) {
   return _replaceStr;
  } else {
   return _obj.toString();
  }
 }
 
 /**
  * 字符串處理, 當<b>_str</b>爲null時用<b>_replaceStr</b>替代
  *
  * @param _str 原始字符串
  * @param _replaceStr 替代null值的字符串
  * @return 處理後的字符串
  */
 public static String toStr(String _str, String _replaceStr) {
  if (_str == null||_str.equals("null")) {
   return _replaceStr;
  } else {
   return _str;
  }
 }
 /**
  * 字符串處理, 當<b>_str</b>爲null時用<b>""</b>替代
  *
  * @param _str 原始字符串
  * @return 處理後的字符串
  */
 public static String toStr(String _str) {
  return toStr(_str, "");
 }
 /**
  * 獲得對象的字符串表示, 當<b>_obj</b>爲null時用<b>""</b>替代
  *
  * @param _obj 對象
  * @return 獲得對象的字符串
  */
 public static String toStr(Object _obj) {
  if(_obj==null) {
   return "";
  }else{
   return toStr(_obj.toString());
  }
 }
 /**
  * 將字符串採用編碼<b>_encoding</b>轉化爲字節數組
  *
  * @param _str 字符串
  * @param _encoding 編碼方式
  * @throws ParamValidateException 如果編碼方式不支持時擲出
  * @return 字節數組
  */
 public static byte[] toBytes(String _str, String _encoding) throws IllegalArgumentException{
  if( _str == null) {
   return null;
  }
  byte[] b = null;
  try {
   b = _str.getBytes(_encoding);
  } catch (Exception e) {
   throw new IllegalArgumentException("不支持的編碼方式:" + _encoding);
  }
  return b;
 }
 /**
  * 將雙精浮點數代表的金額轉化中文大寫形式
  *
  * @param _dMoney 代表雙精浮點數的金額
  * @return 金額的中文大寫形式,如果輸入參數<b>dMoney</b>大於10^8或小於0.01返回空串。
  */
 public static String toChinese(double _dMoney) {
  String[] strArr = { "零", "壹", "貳", "叄", "肆", "伍", "陸", "柒", "捌", "玖" };
  String[] strArr1 = { "分", "角", "圓", "拾", "佰", "仟", "萬", "拾", "佰", "仟" };
  String[] strArr2 = new String[10];
  String sRtn = "";
  int iTmp;
  double dTmp;
  try {
   _dMoney += 0.001;
   if ((_dMoney >= 100000000) || (_dMoney < 0.01)) {
    sRtn = "";
   } else {
    for (int i = 0; i < 10; i++) {
     dTmp = _dMoney / Math.pow(10, 7 - i);
     iTmp = (new Double(dTmp)).intValue();
     _dMoney -= iTmp * Math.pow(10, 7 - i);
     if (iTmp != 0) {
      strArr2[i] = strArr[iTmp] + strArr1[9 - i];
     } else {
      strArr2[i] = "";
     }
    }
    boolean bFlag = false;
    for (int i = 0; i < 10; i++) {
     if (!"".equals(strArr2[i])) {
      sRtn += strArr2[i];
      bFlag = true;
     } else {
      if (i == 3) {
       sRtn += "萬";
       bFlag = true;
      } else if (i == 7) {
       sRtn += "圓";
       bFlag = true;
      } else if (bFlag) {
       sRtn += "零";
       bFlag = false;
      }
     }
    }
    if (sRtn.startsWith("萬")) {
     sRtn = sRtn.substring(1, sRtn.length());
    }
    if (sRtn.startsWith("圓")) {
     sRtn = sRtn.substring(1, sRtn.length());
    }
    while (sRtn.startsWith("零")) {
     sRtn = sRtn.substring(1, sRtn.length());
    }
    if (sRtn.lastIndexOf("零") == (sRtn.length() - 1)) {
     sRtn = sRtn.substring(0, sRtn.length() - 1);
    }
    if (sRtn.startsWith("圓")) {
     sRtn = sRtn.substring(1, sRtn.length());
    }
    iTmp = sRtn.indexOf("圓");
    if (iTmp != -1) {
     if ("零".equals(sRtn.substring(iTmp - 1, iTmp))) {
      sRtn =
       sRtn.substring(0, iTmp - 1)
        + sRtn.substring(iTmp, sRtn.length());
     }
    }
    iTmp = sRtn.indexOf("萬");
    if (iTmp != -1) {
     if ("零".equals(sRtn.substring(iTmp - 1, iTmp))) {
      sRtn =
       sRtn.substring(0, iTmp - 1)
        + sRtn.substring(iTmp, sRtn.length());
     }
    }
    while (sRtn.startsWith("零")) {
     sRtn = sRtn.substring(1, sRtn.length());
    }
    sRtn += "整";
   }
  } catch (Exception ex) {
  }
  return sRtn;
 }
 /**
  * 根據輸入的String返回BigDecimal,或者若String非數字串,返回null
  *
  * @param _str  待轉化的字符串
  * @return BigDecimal對象
  */
 public static BigDecimal toBigDecimal(String _str) {
  BigDecimal bd = null;
  if (_str != null) {
   try {
    bd = new BigDecimal(_str);
   } catch (Exception e) {
    return null;
   }
  }
  return bd;
 }
 /**
  * 根據年,月,日,轉化爲Timestamp類型,便於DB插入處理
  *
  * @param _sDate 格式爲:yyyy-mm-dd
  * @return Timestamp的時間格式
  */
 public static Timestamp toTimestamp(String _sDate) {
  Timestamp ts = null;
  if (_sDate == null || "".equals(_sDate)) {
   return null;
  }
  ts = Timestamp.valueOf(_sDate + " 00:00:00.000000000");
  return ts;
 }
 /**
  * 替換Html文檔中的"&nbsp"爲" ", "&lt"爲"<", "&gt"爲">","<br>"爲"\r\n"
  *
  * @param _rawStr 原始Html文檔
  * @return 替換後的Html文檔
  */
 public static String changeHtmlStr(String _rawStr) {
  String str = null;
  if (_rawStr != null) {
   str = replaceString( "&nbsp;", " ", _rawStr);
   str = replaceString( "&lt;","<", str);
   str = replaceString( "&gt;",">", str);
   str = replaceString( "&amp;","&", str);
   str = replaceString( "&quot;","\"", str);
   str = replaceString( "<br>", "\r\n",str);
  }
  return str;
 }
 /**
  * 使用新串替換原有字符串中老串
  *
  * @param _oldStr 待替換的字符串
  * @param _newStr 新字符串
  * @param _wholeStr 整個字符串
  * @return 替換後新串
  */
 public static String replaceString(String _oldStr,String _newStr,String _wholeStr) {
  if( _wholeStr == null){
   return null;
  }
  if( _newStr == null) {
   return _wholeStr;
  }
 
  int start=0, end=0;
  StringBuffer result=new StringBuffer();
   result=result.append(_wholeStr);
   while ( result.indexOf(_oldStr, start)>-1) {
      start=result.indexOf(_oldStr, start);
      end=start+_oldStr.length();
      result.replace(start,end,_newStr);
      start += _newStr.length();
   }
  return result.toString();
 }
 /**
  * 如果是正向替換,使用新串替換原有字符串中第一個老串;如果是逆向替換,使用新串替換原有字符串中最後一個老串
  *
  * @param _oldStr 待替換的字符串
  * @param _newStr 新字符串
  * @param _wholeStr 整個字符串
  * @param _reverse 替換方向,如果爲false正向替換,否則逆向替換
  * @return 替換後新串
  */
 public static String replaceFirstString(String _oldStr,String _newStr,String _wholeStr, boolean _reverse) {
  if( _wholeStr == null){
   return null;
  }
  if( _newStr == null) {
   return _wholeStr;
  }
  StringBuffer result=new StringBuffer(_wholeStr);
  int start=0, end=0;
  if(!_reverse) {
   if (result.indexOf(_oldStr)>-1) {
    start=result.indexOf(_oldStr);
    end=start+_oldStr.length();
    result.replace(start,end,_newStr);
   }
  }else{
   if (result.lastIndexOf(_oldStr)>-1) {
    start=result.lastIndexOf(_oldStr);
    end=start+_oldStr.length();
    result.replace(start,end,_newStr);
   }
  }
  return result.toString();
 }
 
 /**
  * 將字符串轉換爲HTML形式,以便在JavaScript中使用
  *
  * @param _sourceStr 原字符串
  * @return 轉換後的字符串
  */
 public static String changeToHTMLStr(String _sourceStr) {
  if (_sourceStr == null) {
   return null;
  }
  StringBuffer buff = new StringBuffer(1024);
  int n = _sourceStr.length();
  char c;
  for (int i = 0; i < n; i++) {
   c = _sourceStr.charAt(i);
   if (c == '"') {
    buff.append('\\');
    buff.append(c);
   } else if (c == '\\') {
    buff.append('\\');
    buff.append(c);
   } else if (c == '\r') {
    buff.append("\\r");
   } else if (c == '\n') {
    buff.append("\\n");
   } else {
    buff.append(c);
   }
  }
  return buff.toString();
 }
 /**
  * 得到 _value截取小數點後_len位 以後的值
  *
  * @param _value 原值
  * @param _len 小數點後的位數
  * @return 截取以後的值
  */
 public static float roundFloat(float _value, int _len) throws IllegalArgumentException{
  int iLen = _len;
  checkParamPositive("_len", _len);
  float d = (float) Math.pow(10, iLen);
  float fValue = _value * d;
  return Math.round(fValue) / d;
 }
 /**
  * 獲得float的字符串表示,首先對_value按_len進行四捨五入截位,如果截位後小數點後位數小於_len,則使用0補齊。
  *
  * @param _value 原值
  * @param _len 小數點後的位數
  * @return float的字符串
  */
 public static String formatFloat(float _value, int _len) throws IllegalArgumentException{
  String fStr = String.valueOf(roundFloat(_value, _len));
  StringBuffer sb = new StringBuffer(fStr);
  int leftBit = fStr.length() - fStr.indexOf(".") - 1;
  if (leftBit < _len) {
   for (int i = 0; i < (_len - leftBit); i++) {
    sb.append("0");
   }
  }
  return sb.toString();
 }
 /**
  * 得到 _value截取小數點後_len位 以後的值
  *
  * @param _value 原值
  * @param _len 小數點後的位數
  * @return 截取以後的值
  */
 public static double roundDouble(double _value, int _len) throws IllegalArgumentException {
  int iLen = _len;
  checkParamPositive("_len", _len);
  double d = Math.pow(10, iLen);
  double dValue = _value * d;
  return Math.round(dValue) / d;
 }
 /**
  * 獲得double的字符串表示,首先對_value按_len進行四捨五入截位,如果截位後小數點後位數小於_len,則使用0補齊。
  *
  * @param _value 原值
  * @param _len 小數點後的位數
  * @return double的字符串
  */
 public static String formatDouble(double _value, int _len) throws IllegalArgumentException{
  String fStr = String.valueOf(roundDouble(_value, _len));
  StringBuffer sb = new StringBuffer(fStr);
  int leftBit = fStr.length() - fStr.indexOf(".") - 1;
  if (leftBit < _len) {
   for (int i = 0; i < (_len - leftBit); i++) {
    sb.append("0");
   }
  }
  return sb.toString();
 }
 
 
 /**
  * 獲得字符串的左邊<p>_len</p>個字符串
  *
  * @param _str 字符串
  * @param _len 長度
  * @return <p>_len</p>個字符串
  */
 public static String leftString(String _str, int _len) {
  if (_str == null) {
   return null;
  }
  if (_len < 0) {
   return "";
  }
  if (_str.length() <= _len) {
   return _str;
  } else {
   return _str.substring(0, _len);
  }
 }
 /**
  * 獲得字符串的右邊<p>_len</p>個字符串
  *
  * @param _str 字符串
  * @param _len 長度
  * @return 字符串的右邊<p>_len</p>個字符串
  */
 public static String rightString(String _str, int _len) {
  if (_str == null) {
   return null;
  }
  if (_len < 0) {
   return "";
  }
  if (_str.length() <= _len) {
   return _str;
  } else {
   return _str.substring(_str.length() - _len);
  }
 }
 
 /**
  * 右填充字符<p>_padChar</p>,使整個字符串長度爲<p>_size</p>
  *
  * @param _str 原始字符串
  * @param _size 添充後字符的總長度
  * @param _padChar 待填充字符
  * @return 右填充後的字符串,如:rightPad('hell', 3, '0')=hell;rightPad('hell', 10, '0')=hell000000
  */
 public static String rightPad(String _str, int _size, char _padChar) {
  if (_str == null) {
   return null;
  }
  int pads = _size - _str.length();
  if (pads <= 0) {
   return _str; // returns original String when possible
  }
  return _str.concat(padding(pads, _padChar));
 }
 /**
  * 左填充字符<p>_padChar</p>,使得填充後的字符串總長爲<p>_size</p>
  *
  * @param _str 原始字符串
  * @param _size 添充後字符的總長度
  * @param _padChar 待填充字符
  * @return 左填充後的字符串,如:leftPad('hell', 10, '0')=000000hell;leftPad('hell', 3, '0')=hell
  */
 public static String leftPad(String _str, int _size, char _padChar) {
  if (_str == null) {
   return null;
  }
  int pads = _size - _str.length();
  if (pads <= 0) {
   return _str; // returns original String when possible
  }
  return padding(pads, _padChar).concat(_str);
 }
 /**
  * 字符串<p>padChar</p>重複<p>repeat</p>位
  *
  * @param _repeat 重複次數
  * @param _padChar 待重複字符
  * @return 重複後的結果字串,如:padding(5, 'a')=aaaaa;padding(0, 'a'):""
  */
 private static String padding(int _repeat, char _padChar) {
  String value = "";
  String padStr = String.valueOf(_padChar);
  if(_repeat>0) {
   for(int i = 0;i<_repeat;i++) {
    value = value.concat(padStr);
   }
  }
  return value;
 }
 
 private static void checkParamPositive(String _str, int _value) throws IllegalArgumentException  {
  if (_value <= 0) {
   throw new IllegalArgumentException("參數:" + _str + "不能小於等於0");
  }
 }
 
}





(2)。ExcelTemplate

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
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.hssf.util.Region;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import com.eos.data.xpath.XPathLocator;
import com.eos.foundation.data.DataObjectUtil;
import com.eos.foundation.database.DatabaseUtil;
import com.primeton.data.sdo.impl.PropertyImpl;
import com.primeton.data.sdo.impl.TypeReference;
import com.primeton.data.sdo.impl.types.BooleanType;
import com.primeton.data.sdo.impl.types.DateTimeType;
import com.primeton.data.sdo.impl.types.DateType;
import com.primeton.data.sdo.impl.types.DecimalType;
import com.primeton.data.sdo.impl.types.FloatType;
import com.primeton.data.sdo.impl.types.IntType;
import com.primeton.data.sdo.impl.types.IntegerType;
import com.primeton.data.sdo.impl.types.LongType;
import commonj.sdo.DataObject;
import commonj.sdo.Type;
/**
 *
 * Excel模板實現類<BR>
 * 實現通過自定義Excel數據模版,將結果集填充到模版相應位置,自動創建輸出到指定的文件,允許Excel模版設置公式,調用方法如下:<BR>
 * <pre>
 *     ExcelTemplate template=new ExcelTemplate(templateFilePath,outputFilePath)
 *     //template.setIncludeFormula(true);設置包含公式
 *     template.generate(ResultSet);//resultset爲ArrayList對象,數據行以Map封裝
 *     //template.generate(titleMap,dataList)//顯示主表、明細表信息
 * </pre>
 *
 * @author primeton
 * wengzr (mailto:)
 */
public class ExcelTemplate {
 /**
  * 模板文件名
  */
 private String templateFile;
 /**
  * 輸出文件名
  */
 private String outputFile;
 /**
  * Excel模板定義的輸出字段名數組
  */
 private String[] fieldNames;
 /**
  * 輸出的起始行,默認爲-1,不輸出
  */
 private int startRow=-1;
 private int tempStartRowNum=-1;
 /**
  * 默認字體大小
  */
 private int fontSize=10;
 /**
  * 默認字體
  */
 private String fontName="宋體";
 /**
  * 是否設置信息標題欄邊框,默認情況不設置邊框
  */
 private boolean titleCellBold=false;
 /**
  * 是否設置空白欄邊框,默認情況不設置邊框
  */
 private boolean blankCellBold=false;
 /**
  * 是否自動分工作薄
  */
 private boolean autoSheet=false;
 /**
  * 是否自動分頁
  */
 private boolean autoPagination=false;
 /**
  * 分頁行數
  */
 private int maxrow=-1;
 /**
  * 是否有公式
  */
 private boolean hasFormula=false;
 /**
  * 關鍵字
  * &-表示模版信息內容字段
  * #-表示模版明細內容字段
  * formula-表示模版函數關鍵字
  * ~-表示Cell當前行,當包含":"時,表示當前行減1
  */
 private final String TITLE_FLAG="&";
 private final String CONTENT_FLAG="#";
 private final String FORMULA_FLAG="formula";
 private final String UNLIMIT_FLAG="~";
 private final String FIELD_AUTO_ID="_id";
 /**
  * 公式計算操作符號
  */
 private final String[] OP_FLAG=new String[]{"+","-","*","/","%",":"};
 /**
  * 默認構造函數
  *
  */
 public ExcelTemplate(){
 }
 /**
  * 構造器
  * @param templateFile 模版文件
  * @param outputFile 輸出文件
  */
 public ExcelTemplate(String templateFile,String outputFile){
  this.templateFile=templateFile;
  this.outputFile=outputFile;
 }
 /**
  * 設置模版文件是否包含Excel公式
  * @param hasFormula
  */
 public void setIncludeFormula(boolean hasFormula){
  this.hasFormula=hasFormula;
 }
 /**
  * 設置標題欄是否需要邊框
  * @param b
  */
 public void setTitleCellBold(boolean titleCellBold){
  this.titleCellBold=titleCellBold;
 }
 /**
  * 設置空白行是否需要顯示邊框
  * @param blankCellBold
  */
 public void setBlankCellBold(boolean blankCellBold){
  this.blankCellBold=blankCellBold;
 }
 /**
  * 設置是否分工作薄
  * @param b
  */
 public void setAutoSheet(boolean autoSheet){
  this.autoSheet=autoSheet;
  this.autoPagination=(autoSheet?false:autoPagination);
 }
 /**
  * 是否自動分頁
  * @param autoPagination
  */
 public void setAutoPagination(boolean autoPagination){
  this.autoPagination=autoPagination;
  this.autoSheet=(autoPagination?false:autoSheet);
 }
 /**
  * 設置分頁最大行
  * @param maxrow
  */
 public void setMaxRow(int maxrow){
  this.maxrow=maxrow;
 }
 /**
  * 設置字體大小,默認10號字體
  * @param size
  */
 public void setFontSize(int size){
  this.fontSize=size;
 }
 public void setFontName(String fontName){
  this.fontName=fontName;
 }
 /**
  * 初始化工作模版,獲取模版配置起始行(start)以及對應字段填充位置(fieldNames)
  * @param sheet
  */
 private void initialize(HSSFSheet sheet){
        boolean setStart=false;
        int rows  = sheet.getPhysicalNumberOfRows();
        for (int r = 0; r < rows; r++){
            HSSFRow row   = sheet.getRow(r);
            if (row != null) {
                int cells = row.getPhysicalNumberOfCells();
                for(short c = 0; c < cells; c++){
                 HSSFCell cell  = row.getCell(c);
                 if(cell!=null)
                 {
                  String value=null;
                  if(cell.getCellType()==HSSFCell.CELL_TYPE_NUMERIC){
                   value=""+cell.getNumericCellValue();
                  }else if(cell.getCellType()==HSSFCell.CELL_TYPE_BOOLEAN){
                   value=""+cell.getBooleanCellValue();
                  }else{
                   value=cell.getRichStringCellValue().getString();
                  }
                     if(value!=null&&!"".equals(value))
                     {
                      value=value.trim();
                      //內容數據
                      if(value.startsWith(CONTENT_FLAG)){
                          if(!setStart){
                           this.startRow=r;//設置內容填充起始行
                           this.fieldNames=new String[cells];
                           setStart=true;
                          }
                          this.fieldNames[c]=value.substring(1);//初始化內容字段
                      }
                     }
                 }
                }
            }
        }
 }
 /**
  * 計算公式,默認範圍從0行到工作薄結尾
  * @param wb
  * @param sheet
  */
 private void calcFormula(HSSFWorkbook wb,HSSFSheet sheet){
  this.calcFormula(wb,sheet,0,sheet.getPhysicalNumberOfRows());
 }
 /**
  * 計算公式函數,範圍從開始行(start_row)到結束行(end_row)
  * @param wb HSSFWorkbook
  * @param sheet HSSFSHeet
  * @param start_rang
  * @param end_rang
  */
 private void calcFormula(HSSFWorkbook wb,HSSFSheet sheet,int start_rang,int end_rang){
        //int rows  = sheet.getPhysicalNumberOfRows();
  HSSFCellStyle borderStyle=this.getBorderStyle(wb);
  HSSFCellStyle noneStyle=this.getNoneStyle(wb);  
        for (int r = start_rang; r < end_rang; r++){
            HSSFRow row   = sheet.getRow(r);
            if (row != null) {
                int cells = row.getPhysicalNumberOfCells();
                for(short c = 0; c < cells; c++){
                 HSSFCell cell  = row.getCell(c);
                 if(cell!=null){
                  if(cell.getCellType()==HSSFCell.CELL_TYPE_STRING){
                         String value=cell.getRichStringCellValue().getString();
                         if(value!=null){
                          value=value.trim().toLowerCase();
                          if(value.startsWith(FORMULA_FLAG))
                          {
                           int index=value.indexOf("=");
                           String formula=value.substring(index+1);
                           //判斷函數是否包含以#開頭,如果是以#開頭表示必須顯示邊框,
                           String flag=formula.substring(0,1);
                           boolean showBold=false;
                           if(flag.equals(CONTENT_FLAG)){
                            formula=formula.substring(1);
                            showBold=true;
                           }
                             //如果包含':'符號則統計公式不包含當前行,否則會引發公式循環引用錯誤.
                           if(formula.indexOf(":")!=-1){
                            formula=formula.replaceAll(UNLIMIT_FLAG,r+"").toUpperCase();
                           }else{
                            formula=formula.replaceAll(UNLIMIT_FLAG,(r+1)+"").toUpperCase();
                           }
                           //判斷公式對應的Cell內容是否爲blank,
                           //如果公式對應的CELL內容爲空,則設置爲""
                           int rightIndex=formula.indexOf(")");
                           int leftIndex=formula.indexOf("(");
                           String content=formula.substring(leftIndex+1,rightIndex);
                           int opIndex=this.getOpIndex(content);
                           String startPos=content.substring(0,opIndex);
                           String endPos=content.substring(opIndex+1);
                           int start_col=this.getColumnIndex(startPos.charAt(0));
                        int start_row=Integer.parseInt(startPos.substring(1));
                        int end_col=this.getColumnIndex(endPos.charAt(0));
                        int end_row=Integer.parseInt(endPos.substring(1));
                        HSSFCell startC=sheet.getRow(start_row-1).getCell((short)start_col);
                        HSSFCell endC=sheet.getRow(end_row-1).getCell((short)end_col);
                        //判斷公式開始Cell與結束cell內容是否無效
                        //當爲均爲無效的cell值,並且當前公式不包含":",則設置公式框內容爲"",
                        //包含":" 則設置爲計算公式
                        if(invalidCellValue(startC)&&invalidCellValue(endC)){
                         if(formula.indexOf(":")==-1){
                          cell.setCellValue( new HSSFRichTextString(""));
                         }else{
                                cell=row.createCell((short)c);
                                cell.setCellType(HSSFCell.CELL_TYPE_FORMULA);
                                cell.setCellFormula(formula);
                         }
                        }else{
                            //重建Cell
                            cell=row.createCell((short)c);
                            cell.setCellType(HSSFCell.CELL_TYPE_FORMULA);
                            cell.setCellFormula(formula);
                        }
                           if(showBold){
                            cell.setCellStyle(borderStyle);
                           }else{
                            cell.setCellStyle(noneStyle);
                           }
                          }
                         }
                  }
                 }
                }
            }
        }
 }
 /**
  * 設置公式文本框爲空白欄,當統計開始行減1==startRowNum時
  * @param cell
  * @param startRowNum
  */
 private void setFormulaBlankCell(HSSFCell cell,int startRowNum){
     if (cell != null) {
   if (cell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
    String value = cell.getRichStringCellValue().getString();
    if (value != null) {
     value = value.trim().toLowerCase();
     if (value.startsWith(FORMULA_FLAG)) {
      int index = value.indexOf("=");
      String formula = value.substring(index + 1);
      String flag = formula.substring(0, 1);
      if (flag.equals(CONTENT_FLAG))formula = formula.substring(1);
      if (formula.indexOf(":") != -1) {
       int rightIndex = formula.indexOf(")");
       int leftIndex = formula.indexOf("(");
       String content = formula.substring(leftIndex + 1,rightIndex).toUpperCase();
       int opIndex = this.getOpIndex(content);
       String startPos = content.substring(0, opIndex);
       String colValue = startPos.substring(1,opIndex);
       if(Integer.parseInt(colValue)-1==startRowNum)
        cell.setCellType(HSSFCell.CELL_TYPE_BLANK);
      }
     }
    }
   }
  }
 
 }
 /**
  * 生成填充模版標題數據
  *
  * @param titleMap
  * @param wb
  * @param sheet
  * @throws Exception
  */
 private void generateTitleDatas(DataObject exportInfo,HSSFWorkbook wb,HSSFSheet sheet)throws Exception{
        int rows  = sheet.getPhysicalNumberOfRows();
        HSSFCellStyle borderStyle=this.getBorderStyle(wb);
        HSSFCellStyle noneStyle=this.getNoneStyle(wb);       
        for (int r = 0; r < rows; r++){
            HSSFRow row   = sheet.getRow(r);
            if (row != null) {
                int cells =row.getPhysicalNumberOfCells();
                for(short c = 0; c < cells; c++){
                 HSSFCell cell  = row.getCell(c);
                 if(cell!=null){
                  if(cell.getCellType()==HSSFCell.CELL_TYPE_STRING){
                         String value=cell.getRichStringCellValue().getString();
                         if(value!=null){
                          value=value.trim();
                          if(value.startsWith(TITLE_FLAG)){
                           value=value.substring(1);
                           //獲取對應的值,支持XPATH取值
                           Object obj=XPathLocator.newInstance().getValue(exportInfo, value);
                           String content=obj+"";
                           //String content=exportInfo.getString(value);
                           if(content==null)content="";
                           //重建Cell,填充標題值
                           cell=row.createCell((short)c);                           
                           cell.setCellType(HSSFCell.CELL_TYPE_STRING);                           
                           cell.setCellValue( new HSSFRichTextString(content));
                           if(!titleCellBold){
                            cell.setCellStyle(noneStyle);
                           }else{
                            cell.setCellStyle(borderStyle);
                           }
                          }
                         }
                  }
                 }
                }
            }
        }
 }

 /**
  * 將指定的對象數組resulset輸出到指定的Excel位置
  * @param resultset List<DataObject>對象數組
  * @param wb HSSFWorkbook
  * @param sheet HSSFSheet
  */
 private void generateContentDatas(List<DataObject> resultset,HSSFWorkbook wb,HSSFSheet sheet){
  HSSFCellStyle borderStyle=this.getBorderStyle(wb);
  HSSFCellStyle noneStyle=this.getNoneStyle(wb);
  //默認行號
  int autoRowId=1;
        for(Iterator it=resultset.iterator();it.hasNext();autoRowId++){
         DataObject content=(DataObject)it.next();
         HSSFRow sourceRow=sheet.getRow(startRow);
         HSSFRow row=sheet.createRow(startRow++);
         for(int i=0;i<sourceRow.getPhysicalNumberOfCells();i++){
          //輸出自動生成的行號
          if(fieldNames[i]!=null&&fieldNames[i].equals(FIELD_AUTO_ID)){
             HSSFCell cell=row.createCell((short)i);           
           cell.setCellStyle(borderStyle);
           cell.setCellType(HSSFCell.CELL_TYPE_STRING);
        cell.setCellValue(autoRowId);
        continue;
          }
          if(fieldNames[i]!=null){
           HSSFCell cell=row.createCell((short)i);           
           cell.setCellStyle(borderStyle);
           if(content!=null){
            //字段名支持xpath取值
            Object value=XPathLocator.newInstance().getValue(content, fieldNames[i]);
               //Object value=content.get(fieldNames[i]);
               if(value!=null){
                if(value instanceof Double|| value instanceof BigDecimal){
                 cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
                 cell.setCellValue(Double.parseDouble(value.toString()));
                }else{
                 cell.setCellType(HSSFCell.CELL_TYPE_STRING);
                 cell.setCellValue(new HSSFRichTextString(value.toString()));
                }
               }else{
                cell.setCellType(HSSFCell.CELL_TYPE_BLANK);
               }
           }else{
            cell.setCellType(HSSFCell.CELL_TYPE_BLANK);
            if(!blankCellBold){
             cell.setCellStyle(noneStyle);
            }else{
             cell.setCellStyle(borderStyle);
            }
           }
          }else{
        HSSFCell sourceCell=sourceRow.getCell((short)i);
        if(sourceCell!=null&&
          sourceCell.getCellType()==HSSFCell.CELL_TYPE_STRING&&
          sourceCell.getRichStringCellValue().getString()!=null&&
          sourceCell.getRichStringCellValue().getString().toLowerCase().startsWith(FORMULA_FLAG)){
         HSSFCell cell=row.createCell((short)i);
         cell.setCellType(HSSFCell.CELL_TYPE_STRING);
         cell.setCellValue(sourceCell.getRichStringCellValue());
        }
       }
         }
         if(it.hasNext()){
          //向下平推一行
          //sheet.shiftRows(startRow-1,sheet.getLastRowNum(),1);
          shiftDown(sheet,startRow-1, sheet.getLastRowNum(), 1);
         }
        }
 }
 /**
  * 將結果集填充到Excel模版,resultset必須是以Map封裝行
  * @param
  * @param resultset 數據內容
  * @throws Exception
  */
 public void generate(List<DataObject> resultset)throws Exception{
  this.generate(resultset,null);
 }
 /**
  * 將結果集填充到Excel模版,resultset必須是以Map封裝行
  * @param titleMap 標題信息
  * @param resultset 結果集
  * @throws Exception
  */
 public void generate(List<DataObject> resultset,DataObject exportInfo)throws Exception{
        POIFSFileSystem fs =new POIFSFileSystem(new FileInputStream(templateFile));
        HSSFWorkbook wb = new HSSFWorkbook(fs);
        HSSFSheet sheet = wb.getSheetAt(0);
        initialize(sheet);
        if(startRow==-1)
         return ;

        if(this.autoPagination){
         this.generatePagination(wb,sheet,resultset,exportInfo);
        }
        else if(this.autoSheet){
         generatePaginationSheet(wb,sheet,resultset,exportInfo);
        }
        else{
            //先填充標題
            if(exportInfo!=null)
             this.generateTitleDatas(exportInfo,wb,sheet);
            //生成數據內容
            this.generateContentDatas(resultset,wb,sheet);
            if(hasFormula){
             this.calcFormula(wb,sheet);
            }
        }
        FileOutputStream fileOut = new FileOutputStream(outputFile);
        wb.write(fileOut);
        fileOut.close();
 }
 /**
  * EXCEL分頁
  * 必須在EXCEL模版的最後一行插入EXCEL分頁符!
  * @param wb HSSFWorkbook
  * @param sourceSheet HSSFSheet
  * @param resultset 填充數據集
  * @param titleMap 信息欄內容
  * @throws Exception
  */
 private void generatePagination(HSSFWorkbook wb,HSSFSheet sourceSheet,List<DataObject> resultset,DataObject exportInfo)
throws Exception{
     int startPosition=startRow;
     tempStartRowNum=startRow;
     int count=resultset.size() / maxrow;
     int num=resultset.size() % maxrow;
     int rows=sourceSheet.getPhysicalNumberOfRows();
     System.out.println("rows="+rows);
     if(num>0){
      count=count+1;
      num=maxrow-num;
      //不足指定的maxrow,添加空行
      for(int i=0;i<num;i++){
       resultset.add(null);
      }
     }
     //刪除最後一行的分頁符
     try{
      sourceSheet.removeRowBreak(rows-1);
     }catch(NullPointerException npe){
      throw new Exception("指定的EXCEL模版文件["+this.templateFile+"] 未插入分頁符");
     }
     //超過1頁則插入分頁符
     for(int i=1;i<count;i++){
      //設置分頁符
      sourceSheet.setRowBreak(i*rows-1);
      this.copyRows(sourceSheet,sourceSheet,0,rows,i*rows+1);
     }
     if(exportInfo!=null)
      this.generateTitleDatas(exportInfo,wb,sourceSheet);
     int current_page=0;
     while(current_page<count){
      List<DataObject> newList=resultset.subList(current_page*maxrow,maxrow*(current_page+1));
      this.generateContentDatas(newList,wb,sourceSheet);
      current_page++;
      //計算下一行的數據填充起始位置
      startRow=current_page*rows+maxrow+startPosition;
     }
        if(hasFormula)
         this.calcFormula(wb,sourceSheet);
 }

 /**
  * 生成分頁的工作薄模版
  * @param wb HSSFWorkbook
  * @param sourceSheet HSSFSheet
  * @param resultset 填充數據集
  * @param titleMap 信息(標題)欄內容
  */
 private void generatePaginationSheet(HSSFWorkbook wb,HSSFSheet sourceSheet,List<DataObject> resultset,DataObject exportInfo)
throws Exception{
     int startPosition=startRow;
     int count=resultset.size() / maxrow;
     int num=resultset.size() % maxrow;
     if(num>0){
      count=count+1;
      num=maxrow-num;
      //不足指定的maxrow,添加空行
      for(int i=0;i<num;i++){
       resultset.add(null);
      }
     }
     for(int i=1;i<count;i++){
      HSSFSheet newsheet=wb.createSheet("Page "+i);
      this.copyRows(sourceSheet,newsheet,0,sourceSheet.getLastRowNum(),0);
     }
     if(count>1){
      for(int i=0;i<wb.getNumberOfSheets();i++){
       startRow=startPosition;
       List<DataObject> newList=resultset.subList(i*maxrow,maxrow*(i+1));
       HSSFSheet sheet=wb.getSheetAt(i);
             //先填充標題
             if(exportInfo!=null)
              this.generateTitleDatas(exportInfo,wb,sheet);
                this.generateContentDatas(newList,wb,sheet);
                if(hasFormula)
                 this.calcFormula(wb,sheet);
      }
     }else{
   HSSFSheet sheet=wb.getSheetAt(0);
         if(exportInfo!=null)
          this.generateTitleDatas(exportInfo,wb,sheet);
            this.generateContentDatas(resultset,wb,sheet);
            if(hasFormula)
             this.calcFormula(wb,sheet);
     }
 }
 private HSSFCellStyle getBorderStyle(HSSFWorkbook wb){
        HSSFCellStyle style = wb.createCellStyle();
        HSSFFont font=wb.createFont();
        font.setFontHeightInPoints((short)fontSize);
        font.setFontName(fontName);
        style.setFont(font);
        style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        style.setBorderRight(HSSFCellStyle.BORDER_THIN);
        style.setBorderTop(HSSFCellStyle.BORDER_THIN);
        return style;
 }
 private HSSFCellStyle getNoneStyle(HSSFWorkbook wb){
        HSSFCellStyle style = wb.createCellStyle();
        HSSFFont font=wb.createFont();
        font.setFontHeightInPoints((short)fontSize);
        font.setFontName(fontName);
        style.setFont(font);
        style.setBorderBottom(HSSFCellStyle.BORDER_NONE);
        style.setBorderLeft(HSSFCellStyle.BORDER_NONE);
        style.setBorderRight(HSSFCellStyle.BORDER_NONE);
        style.setBorderTop(HSSFCellStyle.BORDER_NONE);
        return style;
 }

 /**
     * 向下平推表格,並複製格式與內容
     * @param thisrow:當前行號
     * @param lastrow:最後行號
     * @param shiftcount:平推量
     */
    private void shiftDown(HSSFSheet sheet,int thisrow, int lastrow, int shiftcount) {
        sheet.shiftRows(thisrow, lastrow, shiftcount);
        for (int z = 0; z < shiftcount; z++) {
            HSSFRow row = sheet.getRow(thisrow);
            HSSFRow oldrow = sheet.getRow(thisrow + shiftcount);
            //將各行的行高複製
            oldrow.setHeight(row.getHeight());
            //將各個單元格的格式複製
            for (short i = 0; i <= oldrow.getPhysicalNumberOfCells(); i++) {
                HSSFCell cell = row.createCell(i);
                HSSFCell oldcell = oldrow.getCell(i);
                if (oldcell != null) {                   
                    switch(oldcell.getCellType()){
                    case HSSFCell.CELL_TYPE_STRING:
                     cell.setCellType(HSSFCell.CELL_TYPE_STRING);
                     cell.setCellValue(oldcell.getRichStringCellValue());
                     break;
                    case HSSFCell.CELL_TYPE_NUMERIC:
                     cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
                     cell.setCellValue(oldcell.getNumericCellValue());
                     break;
                    default:
                     cell.setCellType(HSSFCell.CELL_TYPE_STRING);
                     cell.setCellValue(oldcell.getRichStringCellValue());
                    }
                    cell.setCellStyle(oldcell.getCellStyle());
                 }
            }
            //將有列跨越的複製
            Vector regs = findRegion(sheet,oldrow);
            if (regs.size() != 0) {
                for (int i = 0; i < regs.size(); i++) {
                    Region reg = (Region) regs.get(i);
                    reg.setRowFrom(row.getRowNum());
                    reg.setRowTo(row.getRowNum());
                    sheet.addMergedRegion(reg);
                }
            }
            thisrow++;
        }
    }
     /**
     * 查找所有的合併單元格
     * @param oldrow
     * @return
     */
    private Vector findRegion(HSSFSheet sheet ,HSSFRow oldrow) {
        Vector<Region> regs = new Vector<Region>();
        int num = sheet.getNumMergedRegions();
        int curRowid = oldrow.getRowNum();
        for (int i = 0; i < num; i++) {
            Region reg = sheet.getMergedRegionAt(i);
            if (reg.getRowFrom() == reg.getRowTo() && reg.getRowFrom() == curRowid) {
                regs.add(reg);
            }
        }
        return regs;
    }

    /**
     * 複製EXCEL行到指定的工作薄上
     * ××如果是分頁顯示,需要增加一個判斷:當複製行包含公式forumla=sum(G7:G~)字樣時候,必須修改其實行G7爲相應的新行。
     * @param sourceSheet  原工作薄
     * @param targetSheet 目標工作薄
     * @param pStartRow 複製起始行
     * @param pEndRow 複製終止行
     * @param pPosition 插入位置
     */
    private void copyRows(HSSFSheet sourceSheet, HSSFSheet targetSheet,int pStartRow, int pEndRow, int pPosition) {
  HSSFRow sourceRow = null;
  HSSFRow targetRow = null;
  HSSFCell sourceCell = null;
  HSSFCell targetCell = null;
  Region region = null;
  int cType;
  int i;
  short j;
  int targetRowFrom;
  int targetRowTo;
  if ((pStartRow == -1) || (pEndRow == -1)) {
   return;
  }
  // 拷貝合併的單元格
  for (i = 0; i < sourceSheet.getNumMergedRegions(); i++) {
   region = sourceSheet.getMergedRegionAt(i);
   if ((region.getRowFrom() >= pStartRow)&& (region.getRowTo() <= pEndRow)) {
    targetRowFrom = region.getRowFrom() - pStartRow + pPosition;
    targetRowTo = region.getRowTo() - pStartRow + pPosition;
    region.setRowFrom(targetRowFrom);
    region.setRowTo(targetRowTo);
    targetSheet.addMergedRegion(region);
   }
  }
  // 設置列寬
  for (i = pStartRow; i <= pEndRow; i++) {
   sourceRow = sourceSheet.getRow(i);
   if (sourceRow != null) {
    for (j = sourceRow.getFirstCellNum(); j < sourceRow.getLastCellNum(); j++) {
     targetSheet.setColumnWidth(j, sourceSheet.getColumnWidth(j));
    }
    break;
   }
  }
  // 拷貝行並填充數據
  for (; i <= pEndRow; i++) {
   sourceRow = sourceSheet.getRow(i);
   if (sourceRow == null) {
    continue;
   }
   targetRow = targetSheet.createRow(i - pStartRow + pPosition);
   targetRow.setHeight(sourceRow.getHeight());
   for (j = sourceRow.getFirstCellNum(); j < sourceRow.getLastCellNum(); j++) {
    sourceCell = sourceRow.getCell(j);
    if (sourceCell == null) {
     continue;
    }
    targetCell = targetRow.createCell(j);    
    targetCell.setCellStyle(sourceCell.getCellStyle());
    cType = sourceCell.getCellType();
    targetCell.setCellType(cType);
    switch (cType) {
    case HSSFCell.CELL_TYPE_BOOLEAN:
     targetCell.setCellValue(sourceCell.getBooleanCellValue());
     break;
    case HSSFCell.CELL_TYPE_ERROR:
     targetCell.setCellErrorValue(sourceCell.getErrorCellValue());
     break;
    case HSSFCell.CELL_TYPE_FORMULA:
     targetCell.setCellFormula(parseFormula(sourceCell.getCellFormula()));
     break;
    case HSSFCell.CELL_TYPE_NUMERIC:
     targetCell.setCellValue(sourceCell.getNumericCellValue());
     break;
    case HSSFCell.CELL_TYPE_STRING:
     targetCell.setCellValue(sourceCell.getRichStringCellValue());
     break;
    }
    if(this.autoPagination){
     this.setFormulaBlankCell(sourceCell,tempStartRowNum);
    }
   }
  }
 }
    private String parseFormula(String pPOIFormula) {
  final String cstReplaceString = "ATTR(semiVolatile)"; //$NON-NLS-1$
  StringBuffer result = null;
  int index;
  result = new StringBuffer();
  index = pPOIFormula.indexOf(cstReplaceString);
  if (index >= 0) {
   result.append(pPOIFormula.substring(0, index));
   result.append(pPOIFormula.substring(index+ cstReplaceString.length()));
  } else {
   result.append(pPOIFormula);
  }
  return result.toString();
 }
 
    /**
  * 將列的索引換算成ABCD字母,這個方法要在插入公式時用到
  * @param colIndex 列索引。
  * @return ABCD字母。
  */
    /*
    private String getColLetter(int colIndex){
     String ch = "";
        if (colIndex  < 26)
            ch = "" + (char)((colIndex) + 65);
        else
           ch = "" + (char)((colIndex) / 26 + 65 - 1) + (char)((colIndex) % 26 + 65);
        return ch;
    }
    */
    private int getColumnIndex(char c){
     int i=c;
     return i-65;
    }
    private int getOpIndex(String s){
     for(int i=0;i<OP_FLAG.length;i++){
      int index=s.indexOf(OP_FLAG[i]);
      if(index!=-1){
       return index;
      }
     }
     return -1;
    }
    /**
     * 判斷是否無效Cell
     * @param cell
     * @return
     */
    private boolean invalidCellValue(HSSFCell cell){
     if(cell.getCellType()==HSSFCell.CELL_TYPE_BLANK){
      return true;
     }
     else if(cell.getCellType()==HSSFCell.CELL_TYPE_STRING){
      if(cell.getRichStringCellValue().getString()==null||cell.getRichStringCellValue().getString().equals("")){
       return true;
      }
     }
     else if(cell.getCellType()==HSSFCell.CELL_TYPE_ERROR){
      return true;
     }
     return false;
    }
    /**
     * 將目標Excel文件的內容導入到數據表
     * @param targetFile Excel文件路徑
     * @param entityName SDO數據實體全名
     * @return 返回1 導入成功
     *
     * @throws Exception
     */
    public int importData(String targetFile,String entityName,int submitCount)throws Exception{
        POIFSFileSystem fs =new POIFSFileSystem(new FileInputStream(targetFile));
        HSSFWorkbook wb = new HSSFWorkbook(fs);
        for(int sheetCount=0;sheetCount<wb.getNumberOfSheets();sheetCount++){
         HSSFSheet sheet = wb.getSheetAt(sheetCount);
         int rows  = sheet.getPhysicalNumberOfRows();
            initialize(sheet);
            if(startRow==-1)
             continue;
            List<DataObject> dataObjects=new ArrayList<DataObject>();
            //第一行爲#字段名
            //第二行爲字段標題,因此內容讀取從startRow+2
            for(int rowCount=startRow+2;rowCount<rows;rowCount++){
             HSSFRow sourceRow=sheet.getRow(rowCount);
             DataObject importEntity=DataObjectUtil.createDataObject(entityName);
             //判斷某一行是否允許插入,當該行的所有列cell均爲BLANK時不插入數據庫
             boolean allowInsert=false;
             //以下構造導入的實體對象,並根據Excel單元格的內容填充實體屬性值
             for(int cellCount=0;cellCount<fieldNames.length;cellCount++){
              String propertyName=fieldNames[cellCount];
              HSSFCell cell=sourceRow.getCell((short)cellCount);
              if(cell.getCellType()==HSSFCell.CELL_TYPE_BLANK)
               continue;
              allowInsert=true;
              String value=null;
              if(cell.getCellType()==HSSFCell.CELL_TYPE_NUMERIC){
                if (HSSFDateUtil.isCellDateFormatted(cell)){
                             SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                             value= dateFormat.format((cell.getDateCellValue()));
                         
                          }else{
                             value=String.valueOf((long) cell.getNumericCellValue());
                          }
              }else if(cell.getCellType()==HSSFCell.CELL_TYPE_BOOLEAN){
               value=cell.getBooleanCellValue()+"";
              }else{
               value=cell.getRichStringCellValue().getString();
              }
              TypeReference typeReference=(TypeReference)importEntity.getType().getProperty(propertyName).getType();
              Type propertyType=typeReference.getActualType();
              if(propertyType instanceof IntType||propertyType instanceof IntegerType){
               //防止可能出現的Excel表格讀取自動加.號
                 if(value.indexOf(".")!=-1)
                value=value.substring(0,value.indexOf("."));
               importEntity.set(fieldNames[cellCount],ChangeUtil.toInteger(value));
              }
              else if(propertyType instanceof BooleanType){
               importEntity.set(fieldNames[cellCount],ChangeUtil.toBoolean(Boolean.valueOf(value)));
              }
              else if(propertyType instanceof FloatType){
               importEntity.set(fieldNames[cellCount],ChangeUtil.toFloat(value));
              }
              else if(propertyType instanceof LongType){
               if(value.indexOf(".")!=-1)
                value=value.substring(0,value.indexOf("."));
               importEntity.set(fieldNames[cellCount],ChangeUtil.toLong(value));
              }
              else if(propertyType instanceof DecimalType){
               importEntity.set(fieldNames[cellCount],ChangeUtil.toBigDecimal(value));
              }
              else if(propertyType instanceof DateType){
               importEntity.set(fieldNames[cellCount],ChangeUtil.changeToDBDate(value));
              }
              else if(propertyType instanceof DateTimeType){
               importEntity.set(fieldNames[cellCount],ChangeUtil.toTimestamp(value));
              }
              else{
               importEntity.set(fieldNames[cellCount], value);
              }
             }

             if(dataObjects.size()<submitCount){
              if(allowInsert)
               dataObjects.add(importEntity);
             }else{
              if(dataObjects.size()>0){
               DatabaseUtil.insertEntityBatch("default", dataObjects.toArray(new DataObject[dataObjects.size()]));
               dataObjects.clear();
              }
             }
             if(rowCount==rows-1){
              if(dataObjects.size()>0)
               DatabaseUtil.insertEntityBatch("default", dataObjects.toArray(new DataObject[dataObjects.size()]));
             }

            }
        }
        return 1;
    }

    /**
     * 如果模板文件是否存在
     * @param filename 模板文件名
     * @return 文件存在返回true,否則false
     * @throws IOException
     */
    protected boolean isExistTemplate(String templateFile)throws IOException{
     File file=new File(templateFile);
     return file.exists();
    }

    /**
     * 預初始化模板文件<BR>
     * 當用戶指定的模板文件不存在時,將自動生成指定的模板文件,並第一行設置爲要導出的字段列
     * @param templateFile 模板文件名
     * @param dataObject 數據實體對象
     * @throws Exception
     */
    public void prepareInitializeTemplate(String templateFile,DataObject dataObject) throws Exception{
      HSSFWorkbook wb = new HSSFWorkbook();
      FileOutputStream fileOut = new FileOutputStream(templateFile);
      HSSFSheet sheet = wb.createSheet("new sheet");
      //設置模板的第一行爲輸出字段定義列
      HSSFRow row = sheet.createRow((short)0);
      Object[] properties=dataObject.getType().getDeclaredProperties().toArray();
      for(int i=0;i<properties.length;i++){
       PropertyImpl property=(PropertyImpl)properties[i];
       HSSFCell cell = row.createCell((short)i);
       HSSFRichTextString text=new HSSFRichTextString("#"+property.getName());
       cell.setCellValue(text);
      }
      wb.write(fileOut);
      fileOut.close();
    }
}



(3)。ExcelUtil

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
 
import com.eos.foundation.common.io.FileUtil;
import com.eos.foundation.eoscommon.ConfigurationUtil;
import com.eos.runtime.core.ApplicationContext;
import com.eos.system.annotation.Bizlet;
import com.eos.system.annotation.BizletParam;
import com.eos.system.annotation.ParamType;
import commonj.sdo.DataObject;
/**
 *
 * Excel文件操作工具類<BR>
 *
 * @author primeton
 * wengzr (mailto:)
 */
@Bizlet("Excel工具操作類")
public class ExcelUtil {
 private ExcelUtil(){
  //工具類不允許實例化
 }

 /**
  * 將Excel數據導入到數據庫指定的表,默認每500條數據執行一次批處理導入
  *
  * @param excelFile Excel文件名
  * @param entityFullName 導入的實體全名
  * @return
  * @throws Exception
  */
 @Bizlet(
  value="將Excel數據導入到數據庫指定的表",
  params = {
   @BizletParam(index = 0, paramAlias = "excelFile",type=ParamType.CONSTANT),
         @BizletParam(index = 1, paramAlias = "entityFullName",type=ParamType.CONSTANT)
    }
 )
 public static int importExcel(String excelFile,String entityFullName)throws Exception{
  ExcelTemplate template=new ExcelTemplate();
  return template.importData(excelFile, entityFullName, 500);
 }

 /**
  * 將指定的對象數組exportObjects導出到指定模板的Excel文件
  *
  * @param exportObjects 待導出的對象數組
  * @param exportInfo  模板文件的其他附加信息(非結果集內容)
  * @param templateFilename 模板文件名(不帶擴展名),對應到在user-config.xml配置路徑下的模板文件
  * @return 返回生成的Excel文件下載路徑
  * @throws Exception
  */
 @Bizlet(
  value="將指定的對象數組導出到指定模板的Excel文件",
  params = {
   @BizletParam(index = 0, paramAlias = "exportObjects",type=ParamType.VARIABLE),
         @BizletParam(index = 1, paramAlias = "exportInfo",type=ParamType.VARIABLE),
         @BizletParam(index = 2, paramAlias = "templateFilename",type=ParamType.CONSTANT)
     }
 )
 public static String exportExcel(DataObject[] exportObjects,DataObject exportInfo,String templateFilename) throws Exception{
  return exportExcel(exportObjects,exportInfo,templateFilename,false,false);
 }
 /**
  * 分頁將對象數組導出到指定的模板Excel文件,注意:此時模板文件必需包含Excel表格的分頁符
  * @param exportObjects 待導出的對象數組
  * @param exportInfo  模板文件的其他附加信息(非結果集內容)
  * @param templateFilename 模板文件名(不帶擴展名),對應到在user-config.xml配置路徑下的模板文件
  * @return 返回生成的Excel文件下載路徑
  * @throws Exception
  */
 @Bizlet(
  value="分頁將對象數組導出到指定的模板Excel文件",
  params = {
   @BizletParam(index = 0, paramAlias = "exportObjects",type=ParamType.VARIABLE),
         @BizletParam(index = 1, paramAlias = "exportInfo",type=ParamType.VARIABLE),
         @BizletParam(index = 2, paramAlias = "templateFilename",type=ParamType.CONSTANT)
     }
 )
 public static String exportExcelWithPagnation(DataObject[] exportObjects,DataObject exportInfo,String templateFilename)
throws Exception{
  return exportExcel(exportObjects,exportInfo,templateFilename,true,false);
 }
 /**
  * 分工作表將對象數組導出到指定的模板Excel文件,默認情況下輸出工作表最大行:20000
  * @param exportObjects 待導出的對象數組
  * @param exportInfo  模板文件的其他附加信息(非結果集內容)
  * @param templateFilename 模板文件名(不帶擴展名),對應到在user-config.xml配置路徑下的模板文件
  * @return 返回生成的Excel文件下載路徑
  * @throws Exception
  */
 @Bizlet(
  value="分工作表將對象數組導出到指定的模板Excel文件",
  params = {
   @BizletParam(index = 0, paramAlias = "exportObjects",type=ParamType.VARIABLE),
         @BizletParam(index = 1, paramAlias = "exportInfo",type=ParamType.VARIABLE),
         @BizletParam(index = 2, paramAlias = "templateFilename",type=ParamType.CONSTANT)
     }
 )
 public static String exportExcelWithSheet(DataObject[] exportObjects,DataObject exportInfo,String templateFilename)
throws Exception{
  return exportExcel(exportObjects,exportInfo,templateFilename,false,true);
 }
 /**
  * 導出Excel文件,根據指定路徑下的模板生成輸出的Excel文件
  *
  * @param exportObjects 待導出的對象數組
  * @param exportInfo 模板文件的其他附加信息(非結果集內容)
  * @param templateFilename 模板文件名(不帶擴展名),對應到在user-config.xml配置路徑下的模板文件
  * @param autoPagination 是否分頁
  * @param autoSheet 是否分工作表
  * @return 返回生成的Excel文件下載路徑
  * @throws Exception
  */
 private static String exportExcel(DataObject[] exportObjects,DataObject exportInfo,String templateFilename,
boolean autoPagination,boolean autoSheet) throws Exception{
  String filename=templateFilename;
  if(filename.indexOf(".xls")==-1){
   filename+=".xls";
  }
  //臨時路徑是服務器當前war下面的excel-config目錄
  String templateDir=ApplicationContext.getInstance().getWarRealPath()+ConfigurationUtil.getContributionConfig
(UtilConfiguration.CONTRIBUTION_ABFRAME_UTILS,
    UtilConfiguration.MODULE_ABFRAME,
    UtilConfiguration.GROUP_EXCEL,
    UtilConfiguration.EXCEL_TEMPLATE_PATH);
  String excelExportMaxnum=ConfigurationUtil.getContributionConfig(UtilConfiguration.CONTRIBUTION_ABFRAME_UTILS,
    UtilConfiguration.MODULE_ABFRAME,
    UtilConfiguration.GROUP_EXCEL,
    UtilConfiguration.EXCEL_EXPORT_MAXNUM);
 
  if(!templateDir.endsWith("/")){
   templateDir+="/";
  }
  String tempDir=templateDir+"temp/";
  File file=new File(tempDir);
  if(!file.exists()){
   //創建臨時目錄
   FileUtil.mkDir(tempDir);
   //file.createNewFile();
  }
  String templateFile=templateDir+filename;
  String outputFile=tempDir+generateOutputExcelFile(filename);
  ExcelTemplate template=new ExcelTemplate(templateFile,outputFile);
  template.setAutoPagination(autoPagination);
  template.setAutoSheet(autoSheet);
  int excelExportMaxnumInt = 0;
  try{
   excelExportMaxnumInt = Integer.parseInt(excelExportMaxnum);
  }catch (Exception e){
   e.printStackTrace();
  }
  template.setMaxRow(excelExportMaxnumInt);
  template.generate(Arrays.asList(exportObjects),exportInfo);
  return outputFile;
 }
 /**
  * 生成EXCEL輸出文件,默認帶時間戳
  * @param templateFilename 文件名
  * @return
  */
 private static String generateOutputExcelFile(String templateFilename){
  String filename=templateFilename;
  System.out.println("filename"+filename);
  if(templateFilename.endsWith(".xls")){
   filename=templateFilename.substring(0,templateFilename.length()-4);
  }
  SimpleDateFormat format=new SimpleDateFormat("yyyyMMddHHmmss");
  String datetimeString=format.format(new Date());
  filename=filename+"_"+datetimeString+".xls";
  return filename;
 }
}



(4)。UtilConfiguration

/**
 *
 * Utility構件包配置常量定義
 *
 * @author primeton
 * wengzr (mailto:)
 */
public interface UtilConfiguration {
 public static final String CONTRIBUTION_ABFRAME_UTILS="com.primeton.example.excel";
 public static final String MODULE_ABFRAME="example-config";
 public static final String GROUP_EXCEL="excel-config";
 /**
  * EXCEL模板路徑
  */
 public static final String EXCEL_TEMPLATE_PATH="excel_template_path";
 
 /**
  * 導出EXCEL最大行數
  */
 public static final String EXCEL_EXPORT_MAXNUM="excel_export_maxnum";

}


3.建造兩個jsp頁面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" session="false" %>
<%@include file="/common/common.jsp"%>
<%@include file="/common/skins/skin0/component.jsp"%>
<h:css href="/css/style1/style-custom.css" />
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<!--
  - Author(s): Administrator
  - Date: 2017-09-25 11:04:01
  - Description:
-->
<head>
<title>導出</title>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
    <script src="<%= request.getContextPath() %>/common/nui/nui.js" type="text/javascript"></script>
    
</head>
<body>
    <h:form action = "com.primeton.example.excel.exportFood.flow" id="queryForm">
    <!--頁面流action中的query-->
        <input type="hidden" name="_eosFlowAction" value="query"/>
        <input type="hidden" name="criteria/_entity" value="com.primeton.example.excel.sampledataset.ToFood">
          <w:panel id="panel1" width="100%" title="查詢條件">
            <table align="center" border="0" width="100%" class="form_table">
              <tr>
                <td class="form_label">
                  食物名稱
                </td>
                <td colspan="1">
                  <h:text property="criteria/_expr[1]/foodname"/>
                  <h:hidden property="criteria/_expr[1]/_op" value="like"/>
                  <h:hidden property="criteria/_expr[1]/_likeRule" value="all"/>
                </td>
                <td class="form_label">
                 類別
                </td>
                <td colspan="1">
                  <!--<d:select dictTypeId="gender" nullLabel="--請選擇--" property="criteria/_expr[2]/fkfoodtypeid"/>-->
                  <h:select property="criteria/_expr[2]/fkfoodtypeid">
                        <option value="">--請選擇--</option>
                        <option value="1">1</option>
                        <option value="2">2</option>
                  </h:select>
                  <h:hidden property="criteria/_expr[2]/_op" value="="/>
                </td>
                <td>
                    <a class="nui-button" onclick="out()" iconCls="icon-edit">
                        導出excel
                    </a>
                </td>
              </tr>
              
            </table>
          </w:panel>
          <h:hidden property="criteria/_orderby[1]/_sort" value="asc"/>
          <h:hidden property="criteria/_orderby[1]/_property" value="id"/>
        
    </h:form>
    
    <script type="text/javascript">
        nui.parse();
        function out(){
            document.getElementById("queryForm").submit();
        }
    </script>
</body>
</html>

(2)。download.jsp

<%@page pageEncoding="UTF-8"%>
<%@page import="javax.servlet.ServletOutputStream"%>
<%@page import="java.io.*"%>
<%@page import="com.eos.web.taglib.util.*" %><%
      //獲取標籤中使用的國際化資源信息
      String fileNotExist=com.eos.foundation.eoscommon.ResourcesMessageUtil.getI18nResourceMessage("l_fileNotExist");
      Object root= com.eos.web.taglib.util.XpathUtil.getDataContextRoot("request", pageContext);
      String localFile=(String)XpathUtil.getObjectByXpath(root,"downloadFile");
    
      System.out.println(">>>>download file is "+localFile);
      byte[] buffer = new byte[512];
      int size = 0;
      response.reset();
      response.setContentType("application/vnd.ms-excel");
       //response.setHeader("Content-disposition", "attachment;filename=\""+ java.net.URLEncoder.encode(localFile,"UTF-8") + "\"");
       response.setHeader("Content-disposition", "attachment;filename=\""+ java.net.URLEncoder.encode("tempExcel.xls","UTF-8") + "\"");
      ServletOutputStream os = null;
      FileInputStream in = null;
      try {
         os = response.getOutputStream();
         File downloadFile=new File(localFile);
         if(downloadFile!=null&&downloadFile.exists()){
             in = new FileInputStream(new File(localFile));
             while ((size = in.read(buffer)) != -1) {
               os.write(buffer, 0, size);
             }
            out.clear();
             out = pageContext.pushBody();
         }else{
            out.print(fileNotExist); //"文件不存在!"
         }
         } catch(Exception e) {
          e.printStackTrace();
       } finally {
            try {
             if(in!=null)in.close();
             if(os!=null)os.close();
             File file=new File(localFile);
             if (file!=null&&file.isFile()&&file.exists()) {
               file.delete();
             }

           } catch (IOException e) {
             e.printStackTrace();
           }
       }
%>


4.建造一個頁面流:如圖所示:

newFile.jsp就是建造的第一個jsp頁面。

query中聲明瞭輸出參數的變量criteria    類型是criteriaType

exportEmpExcel中的返回值是downloadFile 類型是變量。

5.在配置contribution.eosinf中進行配置:

<!-- 相關配置 -->
    <module name="example-config">
        <!-- Excel相關配置 -->
        <group name="excel-config">
            <!-- EXCEL模板路徑 -->
            <configValue key="excel_template_path">/WEB-INF/excel-config/</configValue>
            <!-- 導出EXCEL最大行數 -->
            <configValue key="excel_export_maxnum">10000</configValue>
        </group>
    </module>

至此,導出excel表格就完成了,當查詢條件爲空是則是導出全部數據,有條件時導出符合條件的數據。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章