日期:2014-05-19 浏览次数:20744 次
import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * @author 1097877378 * */ @Target(value = ElementType.METHOD) @Retention(value = RetentionPolicy.RUNTIME) public @interface ExportColumn { /** * 列名 */ public String[] name() default {};//为什么用数组,大家想一下 /** * 格式化字符串 */ public String format() default ""; /** * 导出次序 */ public int order() default 0; }
import java.sql.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.SequenceGenerator; import javax.persistence.Table; import =ExportColumn; public class Users { private Long id; private String name; private String password; private Date birthday; public Long getId() { return id; } @ExportColumn(name={"姓名"}) public String getName() { return name; } @ExportColumn(name={"密码"}) public String getPassword() { return password; } @ExportColumn(format="%1$tY-%1$tm-%1$td", name={"生日"}) public Date getBirthday() { return birthday; } ...省略get,set
import java.io.IOException; import java.io.OutputStream; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Arrays; import java.util.Comparator; import java.util.List; import javax.servlet.http.HttpServletResponse; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import ExportColumn; public class ExportExcelUtil { /** * 导出Excel文件到输出流 * @param response * @throws IOException */ public static <T> void exportExcel(List<T> data, String fileName, HttpServletResponse response) throws Exception { response.reset(); //fileName = URLEncoder.encode(fileName, "UTF-8");//only IE fileName = new String(fileName.getBytes("GBK"), "ISO-8859-1");//IE and FireFox response.setHeader("Content-disposition", "attachment; filename=" + fileName + ".xls");// 设定输出文件头 response.setContentType("application/msexcel");// 定义输出类型 HSSFWorkbook workbook = createWorkbook(data); OutputStream os = response.getOutputStream();// 取得输出流 workbook.write(os); os.flush(); os.close(); } private static <T> HSSFWorkbook createWorkbook(List<T> data) throws SecurityException, IllegalArgumentException, NoSuchMethodException, IllegalAccessException, InvocationTargetException { HSSFWorkbook workbook = new HSSFWorkbook(); Sheet sheet = workbook.createSheet("sheet1"); { createHeader(sheet, data.get(0)); createBody(sheet, data); } return workbook; } private static <T> void createHeader(Sheet sheet, T dataRow) { Row header = sheet.createRow(0); Method[] methods = dataRow.getClass().getMethods(); Arrays.sort(methods, new Com