PageRenderTime 80ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 0ms

/src/main/java/com/newland/beecode/service/impl/XPathExcelTemplateService.java

https://github.com/wangwenan/myproject01
Java | 382 lines | 267 code | 57 blank | 58 comment | 79 complexity | 570e3a94263985c3f578f86e63ce1583 MD5 | raw file
Possible License(s): MIT, BSD-3-Clause, LGPL-2.0
  1. /*
  2. * Created on 2004-7-23
  3. *
  4. * Project: CashManagement
  5. */
  6. package com.newland.beecode.service.impl;
  7. import java.io.File;
  8. import java.io.FileOutputStream;
  9. import java.text.SimpleDateFormat;
  10. import java.util.Collection;
  11. import java.util.Date;
  12. import java.util.Hashtable;
  13. import java.util.Iterator;
  14. import java.util.List;
  15. import java.util.Map;
  16. import org.apache.commons.jxpath.JXPathContext;
  17. import org.apache.commons.logging.Log;
  18. import org.apache.commons.logging.LogFactory;
  19. import org.apache.poi.hssf.usermodel.HSSFCell;
  20. import org.apache.poi.hssf.usermodel.HSSFCellStyle;
  21. import org.apache.poi.hssf.usermodel.HSSFDataFormat;
  22. import org.apache.poi.hssf.usermodel.HSSFFont;
  23. import org.apache.poi.hssf.usermodel.HSSFRow;
  24. import org.apache.poi.hssf.usermodel.HSSFSheet;
  25. import org.apache.poi.hssf.usermodel.HSSFWorkbook;
  26. import org.apache.poi.hssf.util.HSSFColor;
  27. import org.apache.poi.hssf.util.Region;
  28. import com.newland.beecode.exception.AppException;
  29. import com.newland.beecode.exception.ErrorsCode;
  30. import com.newland.beecode.service.ExcelService;
  31. import com.newland.utils.CellDefine;
  32. import com.newland.utils.Formatter;
  33. import com.newland.utils.Util;
  34. /**
  35. * XPathExcelTemplateService 基于XPath的Excel文件模板服务
  36. * Project: CashManagement
  37. * @author shen
  38. * @todo 开发基于jelly的excel xml文件生成模板服务,虽然自能支持Office XP以上的Excel,但功能更加强大
  39. * 2004-7-23
  40. */
  41. public class XPathExcelTemplateService implements ExcelService {
  42. final static Log log = LogFactory.getLog(XPathExcelTemplateService.class);
  43. public final static String STYLE_TEXT = "text";
  44. public final static String STYLE_DATE = "date";
  45. public final static String STYLE_DATETIME = "datetime";
  46. public final static String STYLE_NUMBER = "number";
  47. private String title;
  48. private String sheetName;
  49. /**
  50. * 统计行
  51. */
  52. private String countLine;
  53. private List cellList;
  54. private int maxRowIndex = 30000;
  55. /**
  56. * @throws AppBizException
  57. * @see netbank.CoreSyst.file.ExcelTemplateService#generateExcelFile(java.lang.Object)
  58. */
  59. public File generateExcelFile(Collection dataCollection, String beginTime,
  60. String endTime) throws AppException {
  61. try {
  62. HSSFWorkbook wb = new HSSFWorkbook();
  63. HSSFSheet sheet = null;
  64. HSSFRow row = null;
  65. int rowIndex = 0;
  66. int sheetIndex=0;
  67. Map bookStyleCache = new Hashtable();
  68. Iterator it = dataCollection.iterator();
  69. while (it.hasNext()) {
  70. if (rowIndex % this.maxRowIndex == 0) {
  71. if (rowIndex != 0) {
  72. row = sheet.createRow(rowIndex++);
  73. this.genCountRow(row, wb, rowIndex);
  74. }
  75. //新建sheet
  76. sheet = wb.createSheet(this.sheetName+sheetIndex++);
  77. //行数重置
  78. rowIndex = 0;
  79. //创建标题
  80. row = sheet.createRow(rowIndex++);
  81. this.genHerderRow(wb, sheet, row, beginTime, endTime);
  82. //创建首列
  83. row = sheet.createRow(rowIndex++);
  84. this.genFirstRow(wb, row);
  85. }
  86. row = sheet.createRow(rowIndex++);
  87. JXPathContext context = JXPathContext.newContext(it.next());
  88. for (short i = 0; i < cellList.size(); i++) {
  89. CellDefine cf = (CellDefine) cellList.get(i);
  90. // 单元格值处理
  91. Formatter formatter = cf.getFormatter();
  92. Object value = null;
  93. if (cf.getPath() != null) {
  94. try {
  95. value = context.getValue(cf.getPath());
  96. } catch (Throwable e) {
  97. log.error(cf.getPath() + "为空");
  98. }
  99. if (formatter != null) {
  100. value = formatter.format(value);
  101. }
  102. }
  103. if (cf.getDefaultValue() != null && value == null)
  104. value = cf.getDefaultValue();
  105. createCell(wb, row, i, value, cf, bookStyleCache);
  106. }
  107. }
  108. // 创建统计行
  109. if(sheet!=null){
  110. row = sheet.createRow(rowIndex++);
  111. this.genCountRow(row, wb, rowIndex);
  112. }
  113. // Write the output to a file
  114. File file = File.createTempFile("excelout", ".xls");
  115. FileOutputStream fileOut = new FileOutputStream(file);
  116. wb.write(fileOut);
  117. fileOut.close();
  118. return file;
  119. } catch (Exception e) {
  120. log.error("gen Excel error", e);
  121. throw new AppException(ErrorsCode.SYSTEM_ERR, "gen Excel error", e);
  122. }
  123. }
  124. public void genHerderRow(HSSFWorkbook wb, HSSFSheet sheet, HSSFRow row,
  125. String beginTime, String endTime) {
  126. if (title != null) {
  127. sheet.addMergedRegion(new Region(0, (short) 0, 0, (short) 7));
  128. String cellValue = "";
  129. if (!Util.bIsEmpty(beginTime)) {
  130. cellValue = "startTime:" + beginTime;
  131. }
  132. if (!Util.bIsEmpty(endTime)) {
  133. cellValue = cellValue + " endTime:" + endTime;
  134. } else {
  135. cellValue = cellValue + " endTime:"
  136. + new SimpleDateFormat("yyyy-MM-dd").format(new Date());
  137. }
  138. cellValue = title + " " + cellValue;
  139. HSSFCell cell = row.createCell((short) 0);
  140. //cell.setEncoding(HSSFCell.ENCODING_UTF_16);
  141. //TODO 无此接口
  142. cell.setCellValue(cellValue);
  143. }
  144. }
  145. public void genFirstRow(HSSFWorkbook wb, HSSFRow row) {
  146. // 列头
  147. for (short i = 0; i < cellList.size(); i++) {
  148. CellDefine cellDefine = (CellDefine) cellList.get(i);
  149. HSSFCell cell = row.createCell(i);
  150. HSSFCellStyle style = wb.createCellStyle();
  151. style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
  152. HSSFFont font = wb.createFont();
  153. font.setColor(HSSFColor.BLUE_GREY.index);
  154. font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
  155. style.setFont(font);
  156. style.setFillForegroundColor(HSSFColor.GREY_50_PERCENT.index);
  157. //style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
  158. cell.setCellStyle(style);
  159. setCellValue(cell, cellDefine.getName());
  160. }
  161. }
  162. public void genCountRow(HSSFRow row, HSSFWorkbook wb, int rowIndex) {
  163. // 统计行
  164. if (this.countLine != null) {
  165. String str[] = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J",
  166. "K", "L", "M", "N", "O" };
  167. for (short i = 0; i < cellList.size(); i++) {
  168. CellDefine cellDefine = (CellDefine) cellList.get(i);
  169. HSSFCell cell = row.createCell(i);
  170. if (i == 0) {
  171. HSSFCellStyle style = wb.createCellStyle();
  172. style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
  173. HSSFFont font = wb.createFont();
  174. font.setColor(HSSFColor.BLUE_GREY.index);
  175. font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
  176. style.setFont(font);
  177. //style.setFillForegroundColor(HSSFColor.ORANGE.index);
  178. //style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
  179. cell.setCellStyle(style);
  180. setCellValue(cell, this.countLine);
  181. }
  182. if (cellDefine.isCount()) {
  183. HSSFCellStyle style = wb.createCellStyle();
  184. style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
  185. cell.setCellStyle(style);
  186. cell.setCellType(HSSFCell.CELL_TYPE_FORMULA);
  187. //cell.setEncoding(HSSFCell.ENCODING_UTF_16);
  188. //TODO 无此接口
  189. cell.setCellFormula("SUM(" + str[i] + "3:" + str[i]
  190. + (rowIndex - 1) + ")");
  191. }
  192. }
  193. }
  194. }
  195. public void createCell(HSSFWorkbook book, HSSFRow row, short col,
  196. Object value, CellDefine cd, Map bookStyleCache) {
  197. if (value == null)
  198. return;
  199. HSSFCell cell = row.createCell(col);
  200. // 确定样式
  201. HSSFCellStyle style = (HSSFCellStyle) bookStyleCache
  202. .get(new Short(col));
  203. if (style == null) {
  204. style = getCellStyle(book, value, cd);
  205. if (style != null)
  206. bookStyleCache.put(new Short(col), style);
  207. }
  208. if (style != null)
  209. cell.setCellStyle(style);
  210. // 确定值
  211. if (value instanceof String) {
  212. cell.setCellType(HSSFCell.CELL_TYPE_STRING);
  213. //cell.setEncoding(HSSFCell.ENCODING_UTF_16);
  214. //TODO 无此接口
  215. cell.setCellValue((String) value);
  216. } else if (value instanceof java.util.Date) {
  217. cell.setCellValue((Date) value);
  218. } else if (value instanceof Boolean) {
  219. cell.setCellValue(((Boolean) value).booleanValue());
  220. } else if (value instanceof Number) {
  221. cell.setCellValue(((Number) value).doubleValue());
  222. } else {
  223. cell.setCellType(HSSFCell.CELL_TYPE_STRING);
  224. //cell.setEncoding(HSSFCell.ENCODING_UTF_16);
  225. //TODO 无此接口
  226. cell.setCellValue(value.toString());
  227. }
  228. }
  229. public HSSFCellStyle getCellStyle(HSSFWorkbook book, Object value,
  230. CellDefine cd) {
  231. // 确定样式
  232. HSSFCellStyle style = book.createCellStyle();
  233. HSSFDataFormat format = book.createDataFormat();
  234. String cellFormat = null;
  235. if (cd.getStyleName() != null && cd.getCellFormat() == null) {
  236. if (STYLE_TEXT.equalsIgnoreCase(cd.getStyleName())) {
  237. cellFormat = "text";
  238. } else if (STYLE_NUMBER.equalsIgnoreCase(cd.getStyleName())) {
  239. cellFormat = "#,##0.00";
  240. } else if (STYLE_DATE.equalsIgnoreCase(cd.getStyleName())) {
  241. cellFormat = "yyyy-MM-dd";
  242. } else if (STYLE_DATETIME.equalsIgnoreCase(cd.getStyleName())) {
  243. cellFormat = "yyyy-MM-dd HH:mm:ss";
  244. }
  245. } else if (cd.getCellFormat() != null) {
  246. cellFormat = cd.getCellFormat();
  247. }
  248. // 未指定数据格式根据类型设置数据格式
  249. if (cellFormat == null) {
  250. if (value instanceof Date)
  251. cellFormat = "yyyy-MM-dd";
  252. else if (value instanceof String) {
  253. cellFormat = "text";
  254. }
  255. }
  256. if (cellFormat != null) {
  257. try {
  258. style.setDataFormat(format.getFormat(cellFormat));
  259. } catch (Exception e) {
  260. log.warn("Excel单元格样式格式设置错误 ", e);
  261. }
  262. }
  263. // 设置对齐方式
  264. if (cd.getAlign() != null) {
  265. if ("left".equalsIgnoreCase(cd.getAlign())) {
  266. style.setAlignment(HSSFCellStyle.ALIGN_LEFT);
  267. } else if ("center".equalsIgnoreCase(cd.getAlign())) {
  268. style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
  269. } else if ("right".equalsIgnoreCase(cd.getAlign())) {
  270. style.setAlignment(HSSFCellStyle.ALIGN_RIGHT);
  271. }
  272. }
  273. return style;
  274. }
  275. public void setCellValue(HSSFCell cell, Object value) {
  276. // 确定值
  277. if (value instanceof String) {
  278. cell.setCellType(HSSFCell.CELL_TYPE_STRING);
  279. //cell.setEncoding(HSSFCell.ENCODING_UTF_16);
  280. //TODO 无此接口
  281. cell.setCellValue((String) value);
  282. } else if (value instanceof java.util.Date) {
  283. cell.setCellValue((Date) value);
  284. } else if (value instanceof Boolean) {
  285. cell.setCellValue(((Boolean) value).booleanValue());
  286. } else if (value instanceof Number) {
  287. cell.setCellValue(((Number) value).doubleValue());
  288. } else {
  289. cell.setCellType(HSSFCell.CELL_TYPE_STRING);
  290. //cell.setEncoding(HSSFCell.ENCODING_UTF_16);
  291. //TODO 无此接口
  292. cell.setCellValue(value.toString());
  293. }
  294. }
  295. /**
  296. * @param dataFieldList The dataFieldList to set.
  297. */
  298. public void setCellList(List dataFieldList) {
  299. this.cellList = dataFieldList;
  300. }
  301. /**
  302. * @param sheetName The sheetName to set.
  303. */
  304. public void setSheetName(String sheetName) {
  305. this.sheetName = sheetName;
  306. }
  307. /**
  308. * @param title The title to set.
  309. */
  310. public void setTitle(String title) {
  311. this.title = title;
  312. }
  313. public String getCountLine() {
  314. return countLine;
  315. }
  316. public void setCountLine(String countLine) {
  317. this.countLine = countLine;
  318. }
  319. public int getMaxRowIndex() {
  320. return maxRowIndex;
  321. }
  322. public void setMaxRowIndex(int maxRowIndex) {
  323. this.maxRowIndex = maxRowIndex;
  324. }
  325. }