1 23 24 package org.dbforms.servlets; 25 26 import javax.servlet.http.HttpServletRequest ; 27 import javax.servlet.http.HttpServletResponse ; 28 import org.dbforms.servlets.reports.LineReportServletAbstract; 29 import org.dbforms.util.ParseUtil; 30 import org.dbforms.util.MessageResourcesInternal; 31 import org.dbforms.util.MessageResources; 32 import java.io.OutputStream ; 33 import java.util.Calendar ; 34 import java.util.Date ; 35 36 import org.apache.poi.hssf.usermodel.HSSFCell; 37 import org.apache.poi.hssf.usermodel.HSSFRow; 38 import org.apache.poi.hssf.usermodel.HSSFSheet; 39 import org.apache.poi.hssf.usermodel.HSSFWorkbook; 40 41 66 public class ExcelReportServlet extends LineReportServletAbstract { 67 68 private static final String SHEETNAMEPARAM = "sheetname"; 69 70 private HSSFWorkbook wb; 71 72 private HSSFSheet sheet; 73 74 private short rowCnt = 0; 75 76 protected String getMimeType() { 77 return "application/msexcel"; 78 } 79 80 protected String getFileExtension() { 81 return ".csv"; 82 } 83 84 protected void openStream(OutputStream out) throws Exception { 85 } 86 87 protected void closeStream(OutputStream out) throws Exception { 88 wb.write(out); 89 } 90 91 92 protected void writeHeader(String [] header) throws Exception { 93 HSSFRow row = sheet.createRow(rowCnt++); 94 for (int i = 0; i < header.length; i++) { 95 HSSFCell cell = row.createCell((short) i); 96 cell.setEncoding(HSSFCell.ENCODING_UTF_16); 97 cell.setCellValue(header[i]); 98 } 99 } 100 101 protected void writeData(Object [] data) throws Exception { 102 HSSFRow row = sheet.createRow( rowCnt++); 103 for (int i = 0; i < data.length; i++) { 104 if (data[i] != null) { 105 HSSFCell cell = row.createCell((short) i); 107 if (data[i] instanceof Number ) { 108 cell.setCellValue(((Number ) data[i]).doubleValue()); 109 } else if (data[i] instanceof Date ) { 110 cell.setCellValue((Date ) data[i]); 111 } else if (data[i] instanceof Calendar ) { 112 cell.setCellValue((Calendar ) data[i]); 113 } else { 114 cell.setEncoding(HSSFCell.ENCODING_UTF_16); 115 cell.setCellValue(data[i].toString()); 116 } 117 } 118 } 119 } 120 121 protected void process(HttpServletRequest request, 122 HttpServletResponse response) { 123 String sheetname = ParseUtil.getParameter(request, SHEETNAMEPARAM, 124 MessageResourcesInternal.getMessage("dbforms.new_worksheet", 125 MessageResources.getLocale(request))); 126 wb = new HSSFWorkbook(); 127 sheet = wb.createSheet(sheetname); 128 rowCnt = 0; 129 super.process(request, response); 130 } 131 132 } 133 | Popular Tags |