项目结构同上一篇

泛型通用的写法

ExportExcel.java

package excel;

import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List; 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.apache.poi.hssf.util.HSSFColor; public class ExportExcel<T> {
public void exportExcel(String title, String[] headers, List<T> list, OutputStream out){
//声明一个工作薄
HSSFWorkbook hssfWorkbook = new HSSFWorkbook();
//生成一个表格
HSSFSheet sheet = hssfWorkbook.createSheet(title);
//设置表格默认列宽度
sheet.setDefaultColumnWidth(15);
//生成一个样式
HSSFCellStyle style = hssfWorkbook.createCellStyle();
//设置样式
style.setFillForegroundColor(HSSFColor.SKY_BLUE.index);
style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
//生成字体
HSSFFont font = hssfWorkbook.createFont();
font.setColor(HSSFColor.VIOLET.index);
font.setFontHeightInPoints((short) 12);
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
// 把字体应用到当前的样式
style.setFont(font);
//产生表格标题行
HSSFRow row = sheet.createRow(0);
for(int i = 0; i < headers.length; i++){
HSSFCell cell = row.createCell(i);
cell.setCellStyle(style);
HSSFRichTextString text = new HSSFRichTextString(headers[i]);
cell.setCellValue(text);
}
int index = 0;
for(T t: list){
index++;
row = sheet.createRow(index);
Field[] fields = t.getClass().getDeclaredFields();
for(int i = 0; i < fields.length; i++){
HSSFCell cell = row.createCell(i);
cell.setCellStyle(style);
Field field = fields[i];
String fieldName = field.getName();
String getMethodName = "get"
+ fieldName.substring(0, 1).toUpperCase()
+ fieldName.substring(1);
try{
Class tCls = t.getClass();
Method getMethod = tCls.getMethod(getMethodName,
new Class[] {});
Object value = getMethod.invoke(t, new Object[] {});
String textValue = value.toString();
HSSFRichTextString richString = new HSSFRichTextString(textValue);
HSSFFont font3 = hssfWorkbook.createFont();
font3.setColor(HSSFColor.BLUE.index);
richString.applyFont(font3);
cell.setCellValue(richString);
}catch (Exception e) {
e.printStackTrace();
}
}
}
try{
hssfWorkbook.write(out);
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
} public void exportExcels(List<T> list, OutputStream out){
//声明一个工作薄
HSSFWorkbook hssfWorkbook = new HSSFWorkbook();
//生成一个表格
HSSFSheet sheet = hssfWorkbook.createSheet();
//设置表格默认列宽度
sheet.setDefaultColumnWidth(20);
//生成一个样式
HSSFCellStyle style = hssfWorkbook.createCellStyle();
//设置样式
style.setFillForegroundColor(HSSFColor.SKY_BLUE.index);
style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
//生成字体
HSSFFont font = hssfWorkbook.createFont();
font.setColor(HSSFColor.VIOLET.index);
font.setFontHeightInPoints((short) 12);
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
// 把字体应用到当前的样式
style.setFont(font);
//产生表格标题行
HSSFRow row = sheet.createRow(0);
T x = list.get(0);
for(int i = 0; i < x.getClass().getDeclaredFields().length; i++){
HSSFCell cell = row.createCell(i);
cell.setCellStyle(style);
HSSFRichTextString text = new HSSFRichTextString(x.getClass().getDeclaredFields()[i].getName());
cell.setCellValue(text);
}
int index = 0;
for(T t: list){
index++;
row = sheet.createRow(index);
Field[] fields = t.getClass().getDeclaredFields();
for(int i = 0; i < fields.length; i++){
HSSFCell cell = row.createCell(i);
cell.setCellStyle(style);
Field field = fields[i];
String fieldName = field.getName();
String getMethodName = "get"
+ fieldName.substring(0, 1).toUpperCase()
+ fieldName.substring(1);
try{
Class tCls = t.getClass();
Method getMethod = tCls.getMethod(getMethodName,
new Class[] {});
Object value = getMethod.invoke(t, new Object[] {});
String textValue;
if(value == null){
continue;
}
if(value instanceof Date){
Date date = (Date) value;
SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd");
textValue = sdf.format(date);
}else{
textValue = value.toString();
}
HSSFRichTextString richString = new HSSFRichTextString(textValue);
HSSFFont font3 = hssfWorkbook.createFont();
font3.setColor(HSSFColor.BLUE.index);
richString.applyFont(font3);
cell.setCellValue(richString);
}catch (Exception e) {
// e.printStackTrace();
}
}
}
try{
hssfWorkbook.write(out);
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}

非泛型硬编码的写法:

package client;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List; import mysql.mapper.StudentMapper; 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.apache.poi.hssf.util.HSSFColor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; import station.mapper.StationApplyMapper; import excel.ExportExcel; import Student.StationApply;
import Student.StationApplyExample;
import Student.Student;
import Student.StudentExample; public class PoiDemo { public static void main(String[] args) throws IOException{
long t1 = System.currentTimeMillis();
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext-dao.xml");
StationApplyMapper stationApplyMapper = (StationApplyMapper) ctx.getBean("stationApplyMapper");
StationApplyExample stationApplyExample = new StationApplyExample();
List<StationApply> list = stationApplyMapper.selectByExample(stationApplyExample);
OutputStream out = new FileOutputStream("D://a.xls");
// new ExportExcel<Student>().exportExcel("test", headers, list, out);
// new ExportExcel<StationApply>().exportExcels(list, out);
exportExcels(list, out);
out.close();
System.out.println("success!");
long t2 = System.currentTimeMillis();
System.out.println(t2 - t1);
} public static void exportExcels(List<StationApply> list, OutputStream out){
//声明一个工作薄
HSSFWorkbook hssfWorkbook = new HSSFWorkbook();
//生成一个表格
HSSFSheet sheet = hssfWorkbook.createSheet();
//设置表格默认列宽度
sheet.setDefaultColumnWidth(20);
//生成一个样式
HSSFCellStyle style = hssfWorkbook.createCellStyle();
//设置样式
style.setFillForegroundColor(HSSFColor.SKY_BLUE.index);
style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
//生成字体
HSSFFont font = hssfWorkbook.createFont();
font.setColor(HSSFColor.VIOLET.index);
font.setFontHeightInPoints((short) 12);
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
// 把字体应用到当前的样式
style.setFont(font);
//产生表格标题行
HSSFRow row = sheet.createRow(0);
StationApply x = list.get(0);
for(int i = 0; i < x.getClass().getDeclaredFields().length; i++){
HSSFCell cell = row.createCell(i);
cell.setCellStyle(style);
HSSFRichTextString text = new HSSFRichTextString(x.getClass().getDeclaredFields()[i].getName());
cell.setCellValue(text);
}
int index = 0;
for(StationApply t: list){
if(t == null){
continue;
}
index++;
row = sheet.createRow(index);
HSSFCell cell = row.createCell(0);
// SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd");
try{
HSSFRichTextString richString = new HSSFRichTextString(String.valueOf(t.getId()));
cell.setCellValue(richString);
cell = row.createCell(1);
richString = new HSSFRichTextString(String.valueOf(t.getGmtCreate()));
cell.setCellValue(richString);
cell = row.createCell(2);
richString = new HSSFRichTextString(String.valueOf(t.getGmtModified()));
cell.setCellValue(richString);
cell = row.createCell(3);
richString = new HSSFRichTextString(t.getCreator());
cell.setCellValue(richString);
cell = row.createCell(4);
richString = new HSSFRichTextString(t.getModifier());
cell.setCellValue(richString);
cell = row.createCell(5);
richString = new HSSFRichTextString(t.getIsDeleted());
cell.setCellValue(richString);
cell = row.createCell(6);
richString = new HSSFRichTextString(t.getIsDeleted());
cell.setCellValue(richString);
cell = row.createCell(7);
richString = new HSSFRichTextString(t.getName());
cell.setCellValue(richString);
cell = row.createCell(8);
richString = new HSSFRichTextString(t.getState());
cell.setCellValue(richString);
cell = row.createCell(9);
richString = new HSSFRichTextString(t.getApplierName());
cell.setCellValue(richString);
cell = row.createCell(10);
richString = new HSSFRichTextString(t.getIdenNum());
cell.setCellValue(richString);
cell = row.createCell(11);
richString = new HSSFRichTextString(t.getMobile());
cell.setCellValue(richString);
cell = row.createCell(12);
richString = new HSSFRichTextString(t.getCovered());
cell.setCellValue(richString);
cell = row.createCell(13);
richString = new HSSFRichTextString(t.getProducts());
cell.setCellValue(richString);
cell = row.createCell(14);
richString = new HSSFRichTextString(t.getLogisticsState());
cell.setCellValue(richString);
cell = row.createCell(15);
richString = new HSSFRichTextString(t.getDescription());
cell.setCellValue(richString);
cell = row.createCell(16);
richString = new HSSFRichTextString(t.getFormat());
cell.setCellValue(richString);
cell = row.createCell(17);
richString = new HSSFRichTextString(t.getAlipayAccount());
cell.setCellValue(richString);
cell = row.createCell(18);
richString = new HSSFRichTextString(t.getTaobaoNick());
cell.setCellValue(richString);
cell = row.createCell(19);
richString = new HSSFRichTextString(String.valueOf(t.getStationId()));
cell.setCellValue(richString);
cell = row.createCell(20);
richString = new HSSFRichTextString(String.valueOf(t.getOwnOrgId()));
cell.setCellValue(richString);
}catch (Exception e) {
e.printStackTrace();
}
}
try{
hssfWorkbook.write(out);
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}

测试耗时2s左右 测试数据10000条记录 每条记录20个字段

web实例http://www.cnblogs.com/xwdreamer/archive/2011/07/20/2296975.html

数据库导出到excel的更多相关文章

  1. php将数据库导出成excel的方法

    <?php $fname = $_FILES['MyFile']['name']; $do = copy($_FILES['MyFile']['tmp_name'],$fname); if ($ ...

  2. 【Java EE 学习 17 下】【数据库导出到Excel】【多条件查询方法】

    一.导出到Excel 1.使用DatabaseMetaData分析数据库的数据结构和相关信息. (1)测试得到所有数据库名: private static DataSource ds=DataSour ...

  3. .Net之路(十三)数据库导出到EXCEL

    .NET中导出到Office文档(word,excel)有我理解的两种方法.一种是将导出的文件存放在server某个目录以下,利用response输出到浏览器地址栏,直接打开:还有直接利用javasc ...

  4. ThinkPHP中,运用PHPExcel,将数据库导出到Excel中

    1.将PHPExcel插件放在项目中,本人位置是ThinkPHP文件夹下,目录结构如下/ThinkPHP/Library//Vendor/...2.直接根据模型,配置三个变量即可使用./** * Ex ...

  5. 从数据库导出到excel

    在项目 扬中 News shenbaocreateall //选中的id string cc = Request["IDcheck"];            Response.C ...

  6. 如何使用NPOI 导出到excel和导入excel到数据库

    近期一直在做如何将数据库的数据导出到excel和导入excel到数据库. 首先进入官网进行下载NPOI插件(http://npoi.codeplex.com/). 我用的NPOI1.2.5稳定版. 使 ...

  7. 数据库多张表导出到excel

    数据库多张表导出到excel public static void export() throws Exception{ //声明需要导出的数据库 String dbName = "hdcl ...

  8. java 对excel操作 读取、写入、修改数据;导出数据库数据到excel

    ============前提加入jar包jxl.jar========================= // 从数据库导出数据到excel public List<Xskh> outPu ...

  9. 数据库数据用Excel导出的3种方法

    将数据库数据用Excel导出主要有3种方法:用Excel.Application接口.用OleDB.用HTML的Tabel标签 方法1——Excel.Application接口: 首先,需要要Exce ...

随机推荐

  1. 如何在eclipse中修改jsp默认编码

    在使用eclipse编程的时候,很多默认的编码都是iso-8859-1我们经常使用的,在eclipse中怎么修改jsp页面的默认编码呢. 第一步:打开eclipse,找到windows-->pr ...

  2. IOS 技术层概览

    IOS 技术层 Cocoa Touch 框架 ui 等 帮助开发者搭建程序 UIKit 它负责启动和关闭应用程序 控制界面和多点触摸事件,并让你能访问常见毒数据试图(比如网页以及word.execl文 ...

  3. Unity5UGUI 官方教程学习笔记(二)Rect Transform

    Rect Transform Posx    Posy   Posz  :  ui相对于父级的位置 Anchors :锚点  定义了与父体之间的位置关系    一个锚点由四个锚组成  四个锚分别代表了 ...

  4. vim常用命令总结 (转)

      在命令状态下对当前行用== (连按=两次), 或对多行用n==(n是自然数)表示自动缩进从当前行起的下面n行.你可以试试把代码缩进任意打乱再用n==排版,相当于一般IDE里的code format ...

  5. linux杂记(⑨)vi使用说明

    基本上vi共分为三种模式,分别是[一般模式]].[编辑模式]与[指令列命令模式].这三种模式的作用是: 一般模式:以vi处理一个档案的时候,一进来该档案就是一般模式.在这个模式中,你可以使用[上下左右 ...

  6. 算法学习笔记(LeetCode OJ)

    ================================== LeetCode的一些算法题,都是自己做的,欢迎提出改进~~ LeetCode:http://oj.leetcode.com == ...

  7. 关于strcpy的实现.

    #include <stdio.h> #include <stdlib.h> int strlen(const char *str) { ; while(*str++!='\0 ...

  8. Open开发平台,认证,授权,计费

    1.申请appid和appkeyhttp://wiki.connect.qq.com/%E5%87%86%E5%A4%87%E5%B7%A5%E4%BD%9C_oauth2-0 appid:应用的唯一 ...

  9. SQL Server 数据库备份到域中别的机器上

    backup database dbName to disk = '\\SV2\D\dbbackup\dbName.bak' with init,compression;

  10. java核心技术学习笔记之一程序设计概述

    Java 核心技术之一程序设计概述 一.   Java语言的特点 简单行 :取经于C++,排除了C++不常用的指针.结构等,增加垃圾回收. 面向对象:与C++不同是单继承,但是可以继承多接口.完全面向 ...