首页 > 代码库 > 把数据库数据导出excel
把数据库数据导出excel
本文解决了excel容量的问题,当它工作区达到最大值的时候回重新开启新的工作区,以及导出到excel的数据都是相应的数据类型,以往的导出都是字符串类型,所以当要进行计算的时候就很麻烦,下面的这个例子我大概导了20万数据做测试,没有出现问题,次类可支持百万级数据导出,有兴趣的可以试试。util类可直接复制使用。我一般倡导,能给源码的尽量别BB。
util类相关代码:
package com.sxt.util;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Iterator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFClientAnchor;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFPatriarch;
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> {
private final static Logger log = Logger.getLogger(ExportExcel.class);
// 声明一个工作簿
private static HSSFWorkbook workbook = null;
// 生成一个表格
private static HSSFSheet sheet = null;
// 产生表格标题行
private static HSSFRow row = null;
// 声明一个画图的顶级管理器
private static HSSFPatriarch patriarch = null;
// 定义一个excel所容纳的初始数据量(防止数据过多,因为一个excel表格最多只能存65535行记录(excel2003的)),所以这里取40000
private static Integer initial_data = http://www.mamicode.com/40000;
// 累计遍历的数量,用来判断是否超过初始数据,如果超过则新建一个sheet
private int length = 0;
public void exportExcel(String headerName, Collection<T> dataset, OutputStream out) {
try {
exportExcel(headerName, null, dataset, out, "yyyy-MM-dd");
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public void exportExcel(String headerName, String[] headers, Collection<T> dataset, OutputStream out) {
try {
exportExcel(headerName, headers, dataset, out, "yyyy-MM-dd");
} catch (Exception e) {
e.printStackTrace();
}
}
@SuppressWarnings("unchecked")
public void exportExcel(String title, String[] headers, Collection<T> dataset, OutputStream out, String pattern)
throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException,
InvocationTargetException {
workbook = new HSSFWorkbook();
sheet = workbook.createSheet(title);
sheet.autoSizeColumn(1, true);// 自适应列宽度
HSSFFont font = workbook.createFont();
font.setFontName("黑体");
font.setFontHeightInPoints((short)16);
row = sheet.createRow(0);
for (int i = 0; i < headers.length; i++) {
HSSFCell cell = row.createCell(i);
HSSFRichTextString text = new HSSFRichTextString(headers[i]);
cell.setCellValue(text);
}
patriarch = sheet.createDrawingPatriarch();
// 遍历集合数据,产生数据行
Iterator<T> it = dataset.iterator();
int index = 0;
while (it.hasNext()) {
index++;
length++;
row = sheet.createRow(index);
T t = (T) it.next();
// 利用反射,根据javabean属性的先后顺序,动态调用getXxx()方法得到属性值
Field[] fields = t.getClass().getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
HSSFCell cell = row.createCell(i);
Field field = fields[i];
String fieldName = field.getName();
String getMethodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
System.out.println("我执行到了!!!" + getMethodName);
Class cts = t.getClass();
System.out.println("我执行到了" + cts.toString());
Method getMethod = cts.getMethod(getMethodName, new Class[] {});
Object value = http://www.mamicode.com/getMethod.invoke(t, new Object[] {});
String textValue = http://www.mamicode.com/null;
if (null != value) {
if (value instanceof Integer) {
int intValue = http://www.mamicode.com/(Integer) value;
cell.setCellValue(intValue);
} else if (value instanceof Float) {
float fValue = http://www.mamicode.com/(float) value;
textValue = http://www.mamicode.com/Float.toString(fValue);
cell.setCellValue(textValue);
} else if (value instanceof Double) {
double dValue = http://www.mamicode.com/(double) value;
cell.setCellValue(dValue);
} else if (value instanceof Long) {
long lValue = http://www.mamicode.com/(long) value;
cell.setCellValue(lValue);
} else if (value instanceof byte[]) {
byte[] bValue = http://www.mamicode.com/(byte[]) value;
// 有图片时设置行高为60px
row.setHeightInPoints(60);
HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 1023, 255, (short) 6, index, (short) 6,
index);
anchor.setAnchorType(2);
patriarch.createPicture(anchor, workbook.addPicture(bValue, HSSFWorkbook.PICTURE_TYPE_JPEG));
} else {
textValue = http://www.mamicode.com/value.toString();
}
} else {
textValuehttp://www.mamicode.com/= "";
}
if (textValue != null) {
Pattern p = Pattern.compile("^//d+(//.//d+)?$");
Matcher matcher = p.matcher(textValue);
if (matcher.matches()) {
// 是数字当做double处理
cell.setCellValue(Double.parseDouble(textValue));
} else {
HSSFRichTextString richString = new HSSFRichTextString(textValue);
cell.setCellValue(richString);
}
}
}
if (length % initial_data =http://www.mamicode.com/= 0) {
sheet = workbook.createSheet(title + length);
// 设置表格默认宽度为15个字节
sheet.setDefaultColumnWidth(15);
row = sheet.createRow(0);
for (int i = 0; i < headers.length; i++) {
HSSFCell cell = row.createCell(i);
HSSFRichTextString text = new HSSFRichTextString(headers[i]);
cell.setCellValue(text);
index = 0;
}
}
}
try {
workbook.write(out);
} catch (IOException e) {
log.error(ExceptionUtils.getStackTrace(e));
log.error("导出数据失败!!");
}
}
}
上面呢就是我们全部的核心代码,我们把他做成了一个工具类,这样的写法看似很复杂,但是百万级的数据导出都是没有任何问题的,而且是能够直接导出图片的,功能强大,只是数据量大的话查询可能计较慢,。我这个测试时基于spring+mybatis+spring mvc架构实现的,大家可以看我的整个结构。
这是我的包结构:
调用代码 :
@RequestMapping("/excel")
public void excel() throws FileNotFoundException{
ExportExcel<Student> stuExcel = new ExportExcel<Student>();
String[] headers = {"编号","姓名","年龄","性别"};
List<Student> dataset = stu.query();
System.out.println("Student="+dataset);
Long date = new Date().getTime();
System.out.println("当前时间:"+date);
OutputStream os = new FileOutputStream("C:/Users/邓富奎/Desktop/1.xls");
stuExcel.exportExcel("Student信息表", headers, dataset, os);
Long end = new Date().getTime();
System.out.println("耗时:"+(end-date));
}
当我们调用这个方法后就会开始查询你要导出的数据,然后通过IO流把信息写入文件
执行完近20万条数据的导出,耗时:
最后在桌面生成excel文件:
把数据库数据导出excel