PageRenderTime 167ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/examples/security-webapp/src/main/java/org/crank/controller/ExcelExportControllerBean.java

http://krank.googlecode.com/
Java | 341 lines | 236 code | 71 blank | 34 comment | 31 complexity | 02c045ab5f627f369858e993f26ef14b MD5 | raw file
  1. package org.crank.controller;
  2. import java.io.IOException;
  3. import java.io.PrintWriter;
  4. import java.util.ArrayList;
  5. import java.util.List;
  6. import java.util.regex.Pattern;
  7. import javax.faces.context.FacesContext;
  8. import javax.servlet.ServletOutputStream;
  9. import javax.servlet.http.HttpServletResponse;
  10. import org.apache.poi.hssf.usermodel.HSSFCell;
  11. import org.apache.poi.hssf.usermodel.HSSFCellStyle;
  12. import org.apache.poi.hssf.usermodel.HSSFFont;
  13. import org.apache.poi.hssf.usermodel.HSSFFooter;
  14. import org.apache.poi.hssf.usermodel.HSSFHeader;
  15. import org.apache.poi.hssf.usermodel.HSSFPrintSetup;
  16. import org.apache.poi.hssf.usermodel.HSSFRow;
  17. import org.apache.poi.hssf.usermodel.HSSFSheet;
  18. import org.apache.poi.hssf.usermodel.HSSFWorkbook;
  19. import org.htmlparser.Parser;
  20. import org.htmlparser.filters.TagNameFilter;
  21. import org.htmlparser.util.NodeList;
  22. import org.htmlparser.util.ParserException;
  23. import org.htmlparser.util.ParserUtils;
  24. import org.joda.time.DateTime;
  25. import org.joda.time.format.DateTimeFormat;
  26. import org.joda.time.format.DateTimeFormatter;
  27. /**
  28. * This is a "global" controller bean.
  29. *
  30. * This will most likely be refactored into the crud framework at some point.
  31. *
  32. * @author Paul Tabor
  33. */
  34. public class ExcelExportControllerBean {
  35. private boolean showForm = true;
  36. private boolean showListing = true;
  37. private boolean showDetailForm = true;
  38. private boolean showDetailListing = true;
  39. private String htmlBuffer = "";
  40. private int numRows = 10;
  41. public void exportHtmlTableToExcel() throws IOException{
  42. //Set the filename
  43. DateTime dt = new DateTime();
  44. DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd_HHmmss");
  45. String filename = dt.toString(fmt) + ".xls";
  46. //Setup the output
  47. String contentType = "application/vnd.ms-excel";
  48. FacesContext fc = FacesContext.getCurrentInstance();
  49. filename = "list-export-"+ filename;
  50. HttpServletResponse response = (HttpServletResponse)fc.getExternalContext().getResponse();
  51. response.setHeader("Content-disposition", "attachment; filename=" + filename);
  52. response.setContentType(contentType);
  53. //Write the table back out
  54. PrintWriter out = response.getWriter();
  55. out.print(htmlBuffer);
  56. out.close();
  57. fc.responseComplete();
  58. }
  59. @SuppressWarnings("static-access")
  60. public void exportHtmlTableAsExcel() throws IOException{
  61. int rowCount = 0;
  62. int colCount = 0;
  63. //Set the filename
  64. DateTime dt = new DateTime();
  65. DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd_HHmmss");
  66. String filename = dt.toString(fmt);
  67. // Create Excel Workbook and Sheet
  68. HSSFWorkbook wb = new HSSFWorkbook();
  69. HSSFSheet sheet = wb.createSheet(filename);
  70. HSSFHeader header = sheet.getHeader();
  71. header.setCenter(filename);
  72. //Setup the output
  73. String contentType = "application/vnd.ms-excel";
  74. FacesContext fc = FacesContext.getCurrentInstance();
  75. filename = "list-export-"+ filename + ".xls";
  76. HttpServletResponse response = (HttpServletResponse)fc.getExternalContext().getResponse();
  77. response.setHeader("Content-disposition", "attachment; filename=" + filename);
  78. response.setContentType(contentType);
  79. ServletOutputStream out = response.getOutputStream();
  80. try{
  81. htmlBuffer = "<html>" + htmlBuffer + "</html>";
  82. Parser parser = new Parser();
  83. parser.setInputHTML(htmlBuffer);
  84. NodeList nodelist = parser.parse(null);
  85. NodeList tableList = nodelist.extractAllNodesThatMatch(new TagNameFilter("TABLE"), true);
  86. NodeList headList = tableList.extractAllNodesThatMatch(new TagNameFilter("THEAD"), true);
  87. NodeList footList = tableList.extractAllNodesThatMatch(new TagNameFilter("TFOOT"), true);
  88. NodeList rowList = tableList.extractAllNodesThatMatch(new TagNameFilter("TR"), true);
  89. //Create a ParserUtils var
  90. ParserUtils pu = new ParserUtils();
  91. //Set rowCount to size of rowList
  92. rowCount = rowList.size();
  93. HSSFFont boldFont = wb.createFont();
  94. boldFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
  95. HSSFCellStyle boldStyle = wb.createCellStyle();
  96. boldStyle.setFont(boldFont);
  97. boldStyle.setWrapText(true);
  98. //Loop through excel 'Rows'
  99. for ( int i = 0; i < rowList.size(); i++ ) {
  100. HSSFRow row;
  101. String htmlRow = rowList.elementAt(i).toHtml().trim();
  102. String[] splitHtmlRow;
  103. List<String> elements = new ArrayList<String>();
  104. if(i == 0 && headList.size() == 1){
  105. row = sheet.createRow((short) i);
  106. htmlRow = htmlRow.replace("<th></th>","<th> </th>");
  107. htmlRow = htmlRow.replace("<TH></TH>","<th> </th>");
  108. htmlRow = htmlRow.replace("</span>", " </span>");
  109. elements.add("tr");
  110. elements.add("th");
  111. if (htmlRow.indexOf("<a href=") > -1) {
  112. elements.add("a");
  113. }
  114. if (htmlRow.indexOf("<span ") > -1) {
  115. elements.add("span");
  116. }
  117. } else if(i == 1 && footList.size() == 1){
  118. row = sheet.createRow((short) rowList.size() - 1);
  119. htmlRow = pu.trimTags(htmlRow, new String[]{"span"},false,false);
  120. htmlRow = htmlRow.replace("<td></td>","<td> </td>");
  121. htmlRow = htmlRow.replace("<TD></TD>","<td> </td>");
  122. elements.add("tr");
  123. elements.add("td");
  124. } else {
  125. if (footList.size() == 1){
  126. row = sheet.createRow((short) i - 1);
  127. } else {
  128. row = sheet.createRow((short) i);
  129. }
  130. htmlRow = htmlRow.replace("<td></td>","<td> </td>");
  131. htmlRow = htmlRow.replace("<TD></TD>","<td> </td>");
  132. htmlRow = htmlRow.replace("</span>", " </span>");
  133. elements.add("tr");
  134. elements.add("td");
  135. if (htmlRow.indexOf("<span ") > -1) {
  136. elements.add("span");
  137. }
  138. }
  139. String[] splitElements = elements.toArray(new String[elements.size()]);
  140. splitHtmlRow = pu.splitTags(htmlRow, splitElements, true, false);
  141. colCount = splitHtmlRow.length;
  142. //Loop through excel 'Columns'
  143. for (int j = 0; j < splitHtmlRow.length; j++){
  144. HSSFCell cell = row.createCell((short) j);
  145. // Calculate what the column width should be.
  146. // Increase if the current width is samller than
  147. // the calculated width.
  148. int width = splitHtmlRow[j].length() * 325;
  149. if(width > sheet.getColumnWidth((short)j)){
  150. sheet.setColumnWidth((short)j, (short)width);
  151. }
  152. //Wrap Text in the Cell for the Header Row
  153. if(i == 0 && headList.size() == 1){
  154. // Determine the width of the column head
  155. Pattern p = Pattern.compile(" ");
  156. String[] splitHead = p.split(splitHtmlRow[j]);
  157. int wordCnt = splitHead.length + 1; // +1 due to the addition of the new line to the cell below
  158. for (int q = 0; q < splitHead.length; q++){
  159. if(splitHead[q].length() * 325 > width)
  160. width = splitHead[q].length() * 325;
  161. sheet.setColumnWidth((short)j, (short)width);
  162. }
  163. // Determine the height of the column head
  164. int height = wordCnt * 275;
  165. if(row.getHeight() < height){
  166. row.setHeight((short)height);
  167. }
  168. // Add new line to cell content and make the cell
  169. // word wrap
  170. splitHtmlRow[j] = splitHtmlRow[j].replaceAll(" ", " \n");
  171. //Set Cell to boldStyle
  172. cell.setCellStyle(boldStyle);
  173. }
  174. //Populate Cell
  175. if(splitHtmlRow[j] == null){
  176. cell.setCellValue("");
  177. }else{
  178. cell.setCellValue(splitHtmlRow[j]);
  179. }
  180. }
  181. }
  182. }catch(ParserException p){ p.printStackTrace(); }
  183. // Do stuff the Excel SpreaSheet
  184. // Freeze Panes on First Row
  185. sheet.createFreezePane(0,1);
  186. // Row 1 Repeats on each page
  187. wb.setRepeatingRowsAndColumns(0,0,0,0,1);
  188. // Set Print Area, Footer
  189. wb.setPrintArea(0, 0, colCount, 0, rowCount);
  190. HSSFFooter footer = sheet.getFooter();
  191. footer.setCenter("Page " + HSSFFooter.page() + " of " + HSSFFooter.numPages());
  192. // Fit Sheet to 1 page wide but very long
  193. sheet.setAutobreaks(true);
  194. HSSFPrintSetup ps = sheet.getPrintSetup();
  195. ps.setFitWidth((short)1);
  196. ps.setFitHeight((short)9999);
  197. sheet.setGridsPrinted(true);
  198. sheet.setHorizontallyCenter(true);
  199. ps.setPaperSize(HSSFPrintSetup.LETTER_PAPERSIZE);
  200. if(colCount > 5){ps.setLandscape(true);}
  201. if(colCount > 10){ps.setPaperSize(HSSFPrintSetup.LEGAL_PAPERSIZE);}
  202. if(colCount > 14){ps.setPaperSize(HSSFPrintSetup.EXECUTIVE_PAPERSIZE);}
  203. // Set Margins
  204. ps.setHeaderMargin((double) .35);
  205. ps.setFooterMargin((double) .35);
  206. sheet.setMargin(HSSFSheet.TopMargin, (double) .50);
  207. sheet.setMargin(HSSFSheet.BottomMargin, (double) .50);
  208. sheet.setMargin(HSSFSheet.LeftMargin, (double) .50);
  209. sheet.setMargin(HSSFSheet.RightMargin, (double) .50);
  210. //Write out the spreadsheet
  211. wb.write(out);
  212. out.close();
  213. fc.responseComplete();
  214. }
  215. public int getNumRows() {
  216. return numRows;
  217. }
  218. public void setNumRows(int numRows) {
  219. this.numRows = numRows;
  220. }
  221. public synchronized String updateNumRows() {
  222. return null;
  223. }
  224. public synchronized String toggleShowForm() {
  225. showForm = !showForm;
  226. return null;
  227. }
  228. public synchronized String toggleShowListing() {
  229. showListing = !showListing;
  230. return null;
  231. }
  232. public synchronized String toggleShowDetailForm() {
  233. showDetailForm = !showDetailForm;
  234. return null;
  235. }
  236. public synchronized String toggleShowDetailListing() {
  237. showDetailListing = !showDetailListing;
  238. return null;
  239. }
  240. public boolean isShowDetailForm() {
  241. return showDetailForm;
  242. }
  243. public void setShowDetailForm(boolean showDetailForm) {
  244. this.showDetailForm = showDetailForm;
  245. }
  246. public boolean isShowDetailListing() {
  247. return showDetailListing;
  248. }
  249. public void setShowDetailListing(boolean showDetailListing) {
  250. this.showDetailListing = showDetailListing;
  251. }
  252. public boolean isShowForm() {
  253. return showForm;
  254. }
  255. public void setShowForm(boolean showForm) {
  256. this.showForm = showForm;
  257. }
  258. public boolean isShowListing() {
  259. return showListing;
  260. }
  261. public void setShowListing(boolean showListing) {
  262. this.showListing = showListing;
  263. }
  264. public String getHtmlBuffer() {
  265. return htmlBuffer;
  266. }
  267. public void setHtmlBuffer(String htmlBuffer) {
  268. this.htmlBuffer = htmlBuffer;
  269. }
  270. }