Excel导出组件

来源:互联网 发布:淘宝差评 编辑:程序博客网 时间:2024/05/16 08:25

      

        在浙江移动的一个项目中开发的用于EXCEL导出的组件。由于时间仓促,功能并不是很齐全,希望大指给于指正。

       Excel-export1.0是用于将JAVA中的数据结构导出为excel文件的工具组件,该组件目前版本为1.0,基于POI3.6,支持office2007office2003,调用该组件将会在服务端生成两个文件,一个是office2007xls,一个是office2003.xls ,由于开发时间仓促,该组件目前功能并不强大,希望广大程序员朋友都能加入到这一组件的开发团队中来。    

    目前Excel解析组件(EPE1.0)由于视图查询功能开发未完备,所以暂不加入到该平台中。

 Excel-export组件目前主要优点为:

 一、  使用简单

 二、  稳定

 三、  速度较快

缺点为:

               生成的列头顺序需要手工调整model或者是dto中的字段,对列头顺序的支持不是很好。

     Excel-export1.0依懒以下JAR包,使用时请将以下JAR拷贝到lib目前中,另外将excel-export1.0.jar包拷入lib

 

下面贴上关键代码

package com.zjmcc.excel.comm;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.LoggerFactory;

/**
 * Excel导出类 该类用于导出List数据集中的数据,list中的对象可由用户自行定义。
 * 在List<HeadCell>类中定义打印的列。可以EXCEL中输出。
 *
 * @author 李声波
 *
 * @param <T>
 *            泛型
 */
public class OutPutExcel {

 private org.slf4j.Logger log=LoggerFactory.getLogger(this.getClass());
 public OutPutExcel() {
  super();
 }
    private short headBackgroundColor;
 /**
  * 读取数据源
  *
  * @param serverPath
  *            服务器路径
  * @param dataList
  *            数据源
  * @param headCellList
  *            列头
  * @return
  */
 public <T extends Object> boolean readyDataSource(String serverPath,
   List<T> dataList, List<HeadCell> headCellList) {
  
  boolean b=false;
  Workbook[] wbs = new Workbook[] { new HSSFWorkbook(),
    new XSSFWorkbook() };
  for (int i = 0; i < wbs.length; i++) {
   Workbook wb = wbs[i];
   
   dataProcessFactory(dataList, wb, headCellList);
   
   String filename = serverPath;
   if (wb instanceof XSSFWorkbook) {
    filename = filename + "x";
   }

   FileOutputStream out;
   try {
    out = new FileOutputStream(filename);
    log.info("创建Excel文件");
    wb.write(out);
    out.flush();
    out.close();
    b=true;
   } catch (FileNotFoundException e) {
    e.printStackTrace();
    b=false;
   } catch (IOException e) {
    e.printStackTrace();
    b=false;
   }
  }

  return b;
 }

 /**
  * 数据处理方法,修改请注明
  *
  * @param obj
  *            目标数据
  * @param wb
  *            工作薄
  * @param headCellList
  *            表头
  */
 private final void dataProcessFactory(Object obj, Workbook wb,
   List<HeadCell> headCellList) {
  Sheet s = wb.createSheet();

  if (obj.getClass() == ArrayList.class) {
   Field[] fields = null;
   ArrayList<?> list = (ArrayList<?>) obj;
   List<Excel> listExcel = new ArrayList<Excel>();
   // 获取数据总行数
   for (int i = 0; i < list.size(); i++) {
    Class<?> classObj = list.get(i).getClass();
    fields = classObj.getDeclaredFields();
    // 获取字段总数
    for (int cellnum = 0; cellnum < fields.length; cellnum++) {

     // 获取表头总数
     for (int j = 0; j < headCellList.size(); j++) {
      
      Excel excel = new Excel();
      try {

       fields[cellnum].setAccessible(true);
       String fieldName = fields[cellnum].getName();
       HeadCell headcell = headCellList.get(j);
       String colunmname = headcell.getColumnName();

       // 判断需要使用的列头
       if (fieldName.equals(colunmname)) {

        // 得到需要使用头的值,表头中配置的值对应每列的数据
        Object valueObj = fields[cellnum].get(list
          .get(i));
        excel.setCellName(headcell.getName());
        excel.setFieldName(fieldName);
        excel.setCellIndex(cellnum);
        excel.setRowIndex(i + 1);
        if (valueObj != null) {
         //设置列宽
         s.autoSizeColumn(j, true);  
         s.setColumnWidth(j, (valueObj.toString()
           .length() * 1000));
         Class<?> cellType = valueObj.getClass();
         excel.setFieldValue(valueObj.toString());
         excel.setCellType(String.class);
         if (cellType == String.class) {
          excel
          .setFieldValue(valueObj
            .toString());
          excel.setCellType(String.class);
         }
         if (cellType == Integer.class) {
          excel
            .setFieldValue(valueObj
              .toString());
          excel.setCellType(Integer.class);
         }
         if (cellType == Double.class) {
          excel
            .setFieldValue(valueObj
              .toString());
          excel.setCellType(Double.class);
         }
         if (cellType == Date.class) {
          excel
            .setFieldValue(valueObj
              .toString());
          excel.setCellType(Double.class);
         }
         if (cellType == Float.class) {
          excel
            .setFieldValue(valueObj
              .toString());
          excel.setCellType(Float.class);
         }
         if (cellType == int.class) {
          excel
            .setFieldValue(valueObj
              .toString());
          excel.setCellType(int.class);
         }
        }
           else {
         excel.setFieldValue("");
         excel.setCellType(Object.class);
        }
        listExcel.add(excel);
       }
      } catch (IllegalArgumentException e) {
       e.printStackTrace();
      } catch (IllegalAccessException e) {
       e.printStackTrace();
      }
     }
    }
   }
   /************************* 打印二维表 **************************************/
   // 打印表头
   Row r0 = s.createRow(0);
   int x = 0;
   
   try
   {
    
    // 获取总行数
    for (int j = 1; j <= list.size(); j++) {
     Row r1 = s.createRow(j);
     // 获取列头
     
     for (int h = 0; h < headCellList.size(); h++) {
      Excel excel = listExcel.get(x);
      
      // 创建表头单元格,并打印
      CellStyle cs = wb.createCellStyle();
      Cell cell = r0.createCell(h);
      
      cs.setFillForegroundColor(IndexedColors.BLUE.getIndex());
      cs.setFillPattern(CellStyle.SOLID_FOREGROUND);
      // cs.setBorderBottom((short) 1);
      cell.setCellStyle(cs);
      cell.setCellValue(excel.getCellName());
      Class<?> cellType=excel.getCellType();
      // 创建单元格数据
      Cell c = r1.createCell(h);
      if (cellType == String.class) {
       c.setCellValue(excel.getFieldValue());
      }
      if (cellType == Integer.class) {
       c.setCellValue(Integer.parseInt(excel.getFieldValue()));  
      }
      if (cellType == Double.class) {
       c.setCellValue(Double.parseDouble(excel.getFieldValue()));
      }
      if (cellType == Date.class) {
       c.setCellValue(Date.parse(excel.getFieldValue()));
      }
      if (cellType == Float.class) {
       c.setCellValue(Float.parseFloat(excel.getFieldValue()));
      }
      if (cellType == int.class) {
       c.setCellValue((int)Integer.parseInt(excel.getFieldValue()));
      }
      ++x;
     }
    }
    log.info("打印了"+listExcel.size()+"单元格");
    log.info("打印了"+list.size()+"行数据");
    log.info("每行打印了"+headCellList.size()+"列");
   }
   catch (Exception e) {
    e.printStackTrace();
    log.info("没有生成EXCEL");
    log.info(e.getMessage().toString());
   }
  }
 }

 private Class<?> isType(Class<?> obj) {
  if (obj == String.class) {
   return String.class;
  }
  if (obj == Integer.class) {
   return Integer.class;
  }
  if (obj == Double.class) {
   return Double.class;
  }
  if (obj == Date.class) {
   return Date.class;
  }
  if (obj == Float.class) {
   return Float.class;
  }
  if (obj == int.class) {
   return int.class;
  } else {
   return Object.class;
  }

 }

 /**
  * 得到表头背景色
  * @return
  */
 public short getHeadBackgroundColor() {
  return headBackgroundColor;
 }

 /**
  * 设置表头背景色
  * @param headBackgroundColor
  */
 public void setHeadBackgroundColor(short headBackgroundColor) {
  this.headBackgroundColor = headBackgroundColor;
 }

 

 
 
 
}
 

原创粉丝点击