报表导出ExcelUtil2

 

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URLEncoder;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.*;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
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.hibernate.Hibernate;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;

import com.sinovatech.shop.order.model.dto.TOrderDTO;


import java.awt.Font;
import java.beans.*;

 
abstract public class ExcelUtil2 {
private   Log log = LogFactory.getLog(ExcelUtil2.class);

private   String shtName = "";
//列属性名
private   String[] cNames = null;
//列显示名
private   String[] cLabels = null;
 
//每页显示行数
private   int rpp = 5000;

private   HSSFCellStyle style = null;
private HSSFWorkbook  wb;
public ExcelUtil2(){
}
public   void exportBySql(HttpServletResponse response,Session session, String querySql,String countSql,
String fileName, String sheetName, String[] colTitle, int rowPerPage)  {

if (rowPerPage <= 10000 && rowPerPage >= 1) {
rpp = rowPerPage;
}
if (!"".equals(sheetName) && null != sheetName) {
shtName = sheetName;
} else {
shtName = "sheet";
}
 
this.cLabels=colTitle;
 wb = new HSSFWorkbook();
style = wb.createCellStyle();
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
//--
SQLQuery query=session.createSQLQuery(querySql);
int curPage=1;
int count =getCount(session,countSql);
int totalPage = ((count + rpp) - 1) / rpp;
for(int i=0;i<totalPage;i++){
curPage=i+1;
int firstResult=(curPage - 1) * rpp;
query.setFirstResult(firstResult);
query.setMaxResults(rpp);
List list= query.list();
HSSFSheet sheet = createSheet(wb, curPage,count);
setSheetColumnTitle(sheet);
for(int rowCnt=0;rowCnt<list.size();rowCnt++){
Object entity=list.get(rowCnt);
HSSFRow row = sheet.createRow(rowCnt + 1);
setCelValue(rowCnt + 1,entity,row,  wb,   sheet); 
}
}
 
try {
OutputStream os = response.getOutputStream();
response.reset();
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-disposition", "attachment; filename="
+ getFileName(fileName));
wb.write(os);
 
} catch (IOException ex) {
log.info("Export Excel file error ! " + ex.getMessage());
}
}
public   void exportBySql(HttpServletResponse response,Session session,Class cls, String querySql,String countSql,
String fileName, String sheetName, String[] colTitle, int rowPerPage)  {

if (rowPerPage <= 10000 && rowPerPage >= 1) {
rpp = rowPerPage;
}
if (!"".equals(sheetName) && null != sheetName) {
shtName = sheetName;
} else {
shtName = "sheet";
}
 
this.cLabels=colTitle;
 wb = new HSSFWorkbook();
style = wb.createCellStyle();
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
//--
SQLQuery query=session.createSQLQuery(querySql).addEntity("order1",cls);
int curPage=1;
int count =getCount(session,countSql);
int totalPage = ((count + rpp) - 1) / rpp;
for(int i=0;i<totalPage;i++){
curPage=i+1;
int firstResult=(curPage - 1) * rpp;
query.setFirstResult(firstResult);
query.setMaxResults(rpp);
List list= query.list();
HSSFSheet sheet = createSheet(wb, curPage,count);
setSheetColumnTitle(sheet);
for(int rowCnt=0;rowCnt<list.size();rowCnt++){
Object entity=list.get(rowCnt);
HSSFRow row = sheet.createRow(rowCnt + 1);
setCelValue(rowCnt + 1,entity,row,wb,sheet); 
}
}
 
try {
OutputStream os = response.getOutputStream();
response.reset();
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-disposition", "attachment; filename="
+ getFileName(fileName));
wb.write(os);
 
} catch (IOException ex) {
log.info("Export Excel file error ! " + ex.getMessage());
}
}
public   List<HSSFRow> insertRow(HSSFWorkbook wb, HSSFSheet sheet,
   int starRow, int rows) {
List<HSSFRow> list=new ArrayList<HSSFRow>();
  sheet.shiftRows(starRow + 1, sheet.getLastRowNum(), rows);

  starRow = starRow - 1;
  
  for (int i = 0; i < rows; i++) {

   HSSFRow sourceRow = null;
   HSSFRow targetRow = null;
   HSSFCell sourceCell = null;
   HSSFCell targetCell = null;
   short m;
   
   starRow = starRow + 1;
   sourceRow = sheet.getRow(starRow);
   targetRow = sheet.createRow(starRow + 1);
   targetRow.setHeight(sourceRow.getHeight());

   for (m = sourceRow.getFirstCellNum(); m < sourceRow.getPhysicalNumberOfCells(); m++) {
    
    sourceCell = sourceRow.getCell(m);
    targetCell = targetRow.createCell(m);
    
    targetCell.setEncoding(sourceCell.getEncoding());
    targetCell.setCellStyle(sourceCell.getCellStyle());
    targetCell.setCellType(sourceCell.getCellType());

   }
   list.add(targetRow);
 }
return list;

}
public int getCount(Session session,String countSql){
 return      ((Long)session.createSQLQuery( countSql )
.addScalar( "count" , Hibernate.LONG)
.uniqueResult()).intValue(); 
}
public   void export(HttpServletResponse response,Session session, String hql,
String fileName, String sheetName, String[] colTitle, int rowPerPage)  {

if (rowPerPage <= 10000 && rowPerPage >= 1) {
rpp = rowPerPage;
}
if (!"".equals(sheetName) && null != sheetName) {
shtName = sheetName;
} else {
shtName = "sheet";
}
 
this.cLabels=colTitle;
 wb = new HSSFWorkbook();
style = wb.createCellStyle();
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
//--
Query query = session.createQuery("select count(*) "
+ hql);
int curPage=1;
int count =Integer.parseInt(String.valueOf(query.uniqueResult()));
int totalPage = ((count + rpp) - 1) / rpp;
for(int i=0;i<totalPage;i++){
curPage=i+1;
int firstResult=(curPage - 1) * rpp;
query = session.createQuery(hql);
query.setFirstResult(firstResult);
query.setMaxResults(rpp);
List list= query.list();
HSSFSheet sheet = createSheet(wb, curPage,count);
setSheetColumnTitle(sheet);
for(int rowCnt=0;rowCnt<list.size();rowCnt++){
Object entity=list.get(rowCnt);
HSSFRow row = sheet.createRow(rowCnt + 1);
setCelValue(rowCnt + 1,entity,row, wb,   sheet); 
}
}
 
try {
OutputStream os = response.getOutputStream();
response.reset();
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-disposition", "attachment; filename="
+ getFileName(fileName));
wb.write(os);
 
} catch (IOException ex) {
log.info("Export Excel file error ! " + ex.getMessage());
}
}
abstract public void setCelValue(int rowIndex,Object entity,HSSFRow row,HSSFWorkbook wb, HSSFSheet sheet);
 
 

/**
 * 创建一个Sheet页并返回该对象
 * 
 * @param wb
 *            HSSFWorkbook
 * @param seq
 *            int
 * @return HSSFSheet
 */
private   HSSFSheet createSheet(HSSFWorkbook wb, int seq) {
int sup = seq * rpp;
int sub = (seq - 1) * rpp + 1;
if (sub < 1) {
sub = 1;
}
HSSFSheet sheet=wb.createSheet( );
shtName=shtName + "(" + sub + "-" + sup + ")";
 
wb.setSheetName(seq-1,shtName,HSSFWorkbook.ENCODING_UTF_16);   
 
return sheet;
}
/**
 * 设置Sheet页的列属性 123. *
 * 
 * @param sht
 *            HSSFSheet 124.
 */
private   void setSheetColumnTitle(HSSFSheet sht) {
HSSFRow row = sht.createRow(0);
for (int i = 0; i < cLabels.length; i++) {
HSSFCell cell = row.createCell((short) (i));
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
cell.setCellValue(cLabels[i]);
cell.setCellStyle(style);
//sht.autoSizeColumn(i,true);
}
}
private   HSSFSheet createSheet(HSSFWorkbook wb, int seq,int totalSize) {
int sup = seq * rpp < totalSize ? seq * rpp : totalSize;
int sub = (seq - 1) * rpp + 1;
if (sub < 1) {
sub = 1;
}
HSSFSheet sheet=wb.createSheet( );
 
wb.setSheetName(seq-1,shtName + "(" + sub + "-" + sup + ")",HSSFWorkbook.ENCODING_UTF_16);   
 
return sheet;
}
/**
 * 获得导出的文件全名
 * 
 * @param tableName
 *            String
 * @return String
 */
private static String getFileName(String fileName) {
 fileName+= new Date().getTime() + ".xls";
try {
return URLEncoder.encode(fileName, "UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
 
}
public void setCellValue(HSSFCell cell, Object value) {
setCellValue(cell, value, null, (short) -1);
}
public void setCellRichTextString(HSSFCell cell, Object valueObj,
Object specialValueObj, short fontColor) {
if (valueObj == null) {
return;
}
String value = String.valueOf(valueObj);
String specialValue = String.valueOf(specialValueObj);
HSSFRichTextString richString = new HSSFRichTextString(String
.valueOf(value));
if (specialValue != null && value.contains(specialValue)) {
HSSFCellStyle cellStyle = cell.getCellStyle();
HSSFFont font = wb.createFont();
font.setColor(fontColor);
richString.applyFont(value.indexOf(specialValue), value
.indexOf(specialValue)
+ specialValue.length(), font);
}

cell.setCellValue(richString.getString());
// System.out.println("我执行了---");
}
public void setCellRichTextString(HSSFCell cell, Object valueObj,short fontColor) {

if (valueObj != null) {
String value = String.valueOf(valueObj);
HSSFRichTextString richString = new HSSFRichTextString(String
.valueOf(value));
HSSFFont font = wb.createFont();
font.setColor(fontColor);
richString.applyFont(font);
cell.setCellValue(richString.getString());
}

}

public void setCellValue(HSSFCell cell, Object value, Object specialValue,
short fontColor) {
// 设置页编码格式,可选.
// targetCell.set(sourceCell.ENCODING_COMPRESSED_UNICODE);
// System.out.println("cell===="+cell);
int cType = cell.getCellType();

switch (cType) {
case HSSFCell.CELL_TYPE_BOOLEAN:
cell.setCellValue(Boolean.valueOf(String.valueOf(value)));
break;
case HSSFCell.CELL_TYPE_ERROR:
cell.setCellErrorValue(Byte.valueOf(value.toString()));

break;
case HSSFCell.CELL_TYPE_FORMULA:
cell.setCellFormula(parseFormula(String.valueOf(value.toString())));

// parseFormula这个函数的用途在后面说明
break;
case HSSFCell.CELL_TYPE_NUMERIC:
cell.setCellValue(Double.valueOf(value.toString()));

break;
case HSSFCell.CELL_TYPE_STRING:
setCellRichTextString(cell, value, specialValue, fontColor);
// cell.setCellValue(new HSSFRichTextString(String.valueOf(value)));
break;
case HSSFCell.CELL_TYPE_BLANK:
if (value != null)
cell.setCellValue(value.toString());
break;
default:
System.out.println("cType=" + cType + "  setCellValue 没有匹配项");
break;
}
}

public Object getCellValue(HSSFCell cell) {

int cType = cell.getCellType();

switch (cType) {
case HSSFCell.CELL_TYPE_BOOLEAN:

return cell.getBooleanCellValue();

case HSSFCell.CELL_TYPE_ERROR:

return cell.getErrorCellValue();

case HSSFCell.CELL_TYPE_FORMULA:
return parseFormula(cell.getCellFormula());
// parseFormula这个函数的用途在后面说明

case HSSFCell.CELL_TYPE_NUMERIC:

return cell.getNumericCellValue();

case HSSFCell.CELL_TYPE_STRING:

//return cell.getRichStringCellValue();
return cell.getStringCellValue();
case HSSFCell.CELL_TYPE_BLANK:
return cell.getStringCellValue();
default:
System.out.println("cType=" + cType + "  getCellValue 没有匹配项");
return null;

}

}

private String parseFormula(String pPOIFormula) {
final String cstReplaceString = "ATTR(semiVolatile)";
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();
}
}



---调用方式
//导出号码订单
public void exportExcelNum(HttpServletResponse response,  String querySql,String countSql,
String fileName, String sheetName, final String[] colTitle, int rowPerPage,final String AccMoney,final String ty){
ExcelUtil2 excelUtil=new ExcelUtil2(){
@Override
public void setCelValue(int rowIndex,Object entity,HSSFRow row,HSSFWorkbook wb, HSSFSheet sheet) {
// TODO Auto-generated method stub
TOrderDTO dto=(TOrderDTO) entity;
List<TItemDTO> items=dto.getItems();
int i=0;
for(TItemDTO item:items){
if(item==null)
continue;
if(!(item.getSubType()).equals(ty))
continue;
System.out.println("--------"+i);
if(i>0){
  row=this.insertRow(wb, sheet, rowIndex+i-1, 1).get(0);
}
for(int col=0;col<colTitle.length;col++){
HSSFCell cell = row.createCell((short) col);
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
String title=colTitle[col].trim();
sheet.setColumnWidth((short) col,  (short )5000);
if(title.equals("下单日期")||title.equals("下单时间")){
cell.setCellValue(dto.getOrderTime()==null?"":DateUtil.getFormatDate(dto.getOrderTime(),"yyyy-MM-dd hh:mm:ss"));
continue;
}
else if(title.equals("持有人")){
cell.setCellValue(dto.getConsignee()==null?"":item.getItemInfo().getOwnerName());
continue;
}
else if(title.equals("支付状态") ){
cell.setCellValue(dto.getPayStateChar()  );
continue;
}
else if(title.equals("子订单")||title.equals("子订单编号")||title.equals("子订单号")){
cell.setCellValue(item.getId());
continue;
}
else if(title.equals("状态")||title.equals("物流状态")){
cell.setCellValue( item.getWlstatusChar() );
continue;
}
else if(title.equals("金额(/元)") ){
cell.setCellValue( item.getSubtotal()+"" );
continue;
}
else if(title.equals("订单状态") ){
if("0".equals(dto.getState())){
cell.setCellValue("生成订单");
}else if("1".equals(dto.getState())){
cell.setCellValue("已结单");
}else if("2".equals(dto.getState())){
cell.setCellValue("作废");
}else{
cell.setCellValue("");
}
continue;
}
else if(title.equals("商品名称") ){
cell.setCellValue( item.getProduct()==null?"":item.getProduct().getName()+"" );
continue;
}
else if(title.equals("所在地") ){
Map<String, String> cityMap = OrderUtil.putAreaToMap();
cell.setCellValue(cityMap.get(item.getProduct().getUndefine1())+"");
continue;
}
else if(title.equals("截止日期")||title.equals("截止时间")){
cell.setCellValue(dto.getOrderEndTime()==null?"":DateUtil.getFormatDate(dto.getOrderEndTime(),"yyyy-MM-dd hh:mm:ss"));
continue;
}
else if(title.equals("营业厅")){
cell.setCellValue(item.getItemInfo()==null?"":item.getItemInfo().getOFFICENAME()+"");
continue;
}
else{
cell.setCellValue( title+" ,没有对应的列" );
}
 
}
i++;
}
row=this.insertRow(wb, sheet, rowIndex+i-1, 1).get(0);
for(int col=0;col<colTitle.length;col++){
if(col==colTitle.length-1){
 HSSFCell cell = row.createCell((short) col);
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
 sheet.setColumnWidth((short) col,  (short )5000);
 cell.setCellValue("已收金额:"+AccMoney);
}else{
HSSFCell cell = row.createCell((short) col);
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
sheet.setColumnWidth((short) col,  (short )5000);
cell.setCellValue("");
}
}
 
}
};
 
excelUtil.exportBySql(    response,  this.getSession(),  TOrderDTO.class,   querySql,  countSql,fileName,   sheetName,   colTitle,   rowPerPage);
  
}

We're headache on making web report all long. ExcelUtils is a helper to export excel report in java web project. It's like velocity, has own tags, but these tags is written in excel file. By these tags, you can custom your excel report format freely, not edit any your source, just ExcelUtils parses your excel template and fills values to export your report. It is based POI project and beanutils project. It uses excel and template language's profit to make web reports easily. After my hardwork, the parser is finished finally, in which report is exported by Excel Template. It's funtions include: 1、${model.name} means getting property of the name from the model object. 2、${!model.name} means that last cell and this cell merge if model.name value equals last cell value. 3、#foreach model in ${list},means that iterate list,modelId is implied index of the list. 4、#each ${model} ${width1},${width2},model can be a Map,JavaBean,Collection or Array object, #each key will show all property of the model.${width?} means merge ${width?} cells. If only one width, all property use the same width. If more than one, use the witdh in order, not set will use "1". 5、${list[0].name} means get the first object from list, then read the property of name. 6、${map(key)} get the value from the map by the key name. 7、${list[${index}].name} [] can be a variable. 8、${map(${key})} () can be a vriable. 9、#sum qty on ${list} where name like/=str sum qty on ${list} collection by where condition. 10、In net.sf.excelutils.tags Package, you can implement ITag to exentd Tag key. eg, FooTag will parse #foo. 11、ExcelResult for webwork. 12、${model${index}} support. 13、#call service.method("str", ${name}) call a method 14、#formual SUM(C${currentRowNo}:F${currentRowNo}) means output excel formula SUM(C?:F?) ? means currentRowNo.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值