数据库导出到excel
项目结构同上一篇
泛型通用的写法
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的更多相关文章
- php将数据库导出成excel的方法
<?php $fname = $_FILES['MyFile']['name']; $do = copy($_FILES['MyFile']['tmp_name'],$fname); if ($ ...
- 【Java EE 学习 17 下】【数据库导出到Excel】【多条件查询方法】
一.导出到Excel 1.使用DatabaseMetaData分析数据库的数据结构和相关信息. (1)测试得到所有数据库名: private static DataSource ds=DataSour ...
- .Net之路(十三)数据库导出到EXCEL
.NET中导出到Office文档(word,excel)有我理解的两种方法.一种是将导出的文件存放在server某个目录以下,利用response输出到浏览器地址栏,直接打开:还有直接利用javasc ...
- ThinkPHP中,运用PHPExcel,将数据库导出到Excel中
1.将PHPExcel插件放在项目中,本人位置是ThinkPHP文件夹下,目录结构如下/ThinkPHP/Library//Vendor/...2.直接根据模型,配置三个变量即可使用./** * Ex ...
- 从数据库导出到excel
在项目 扬中 News shenbaocreateall //选中的id string cc = Request["IDcheck"]; Response.C ...
- 如何使用NPOI 导出到excel和导入excel到数据库
近期一直在做如何将数据库的数据导出到excel和导入excel到数据库. 首先进入官网进行下载NPOI插件(http://npoi.codeplex.com/). 我用的NPOI1.2.5稳定版. 使 ...
- 数据库多张表导出到excel
数据库多张表导出到excel public static void export() throws Exception{ //声明需要导出的数据库 String dbName = "hdcl ...
- java 对excel操作 读取、写入、修改数据;导出数据库数据到excel
============前提加入jar包jxl.jar========================= // 从数据库导出数据到excel public List<Xskh> outPu ...
- 数据库数据用Excel导出的3种方法
将数据库数据用Excel导出主要有3种方法:用Excel.Application接口.用OleDB.用HTML的Tabel标签 方法1——Excel.Application接口: 首先,需要要Exce ...
随机推荐
- SQL Server索引进阶:第十二级,创建,修改,删除
在第十级中我们看到了索引的内部结构,在第十一级中我们看到了平衡树结构潜在的负面影响:索引碎片.有了索引内部结构的知识,我们可以检查在执行数据定义语句和数据操作语句的时候,都发生了什么.在本级中我们介绍 ...
- 获取第下一个兄弟元素 屏蔽浏览器的差异(nextElementsibling)
//获取element下一个兄弟元素 function getNextElementSibling(element){ //能力检测 判断是否支持nextElementSibling if(eleme ...
- JavaScript中NODE操作学习总结
Node: 1.在 HTML DOM (文档对象模型)中,每个部分都是节点: 文档本身是文档节点 所有 HTML 元素是元素节点 所有 HTML 属性是属性节点 HTML ...
- JavaScript值延迟脚本和异步脚本
Html 4.0为<script>标签定义了defer属性,这个属性的用途是表名脚本在执行时,不会影响页面的构造.也就是说,脚本会延迟到整个页面解析完毕之后在运行,因此,在<scri ...
- English - because of,due to ,thanks to ,owing to ,as a result of ,on account of解析
because of,due to ,thanks to ,owing to ,as a result of ,on account of 等都可以用来表示原因,但其用法却各有不同.下面就其用法分述如 ...
- MSSQL数库备份与还原脚本(多个库时很方便)
每次通过 Management Studio 的界面操作备份或还原数据库,对于单个数据库还好,要是一次要做多个.那就还是用脚本快些,下面有两段脚本分享一下. ===================== ...
- 2014.9.25DOM元素操作
2.操作样式class a.className=”block” class样式,代码赋值的方式 (五)找相关元素 a.nextSibling 下一层,下一个同辈元素 a.previousSibling ...
- Linux远程自动输入密码抓取远程资源
#!/usr/bin/expect -fset timeout 3000set sys_date [lindex $argv 0] #要抓取的文件日期spawn scp /data3/xiaorui/ ...
- csapp lab2 bomb 二进制炸弹《深入理解计算机系统》
bomb炸弹实验 首先对bomb这个文件进行反汇编,得到一个1000+的汇编程序,看的头大. phase_1: 0000000000400ef0 <phase_1>: 400ef0: 48 ...
- Hive操作之HQL语句
HQL操作1.Distribute by distribute by col按照col列把数据分散到不同的reduce sort sort by col 按照col列把数据排序 ...