在java开发当中,我们免不了要有数据导出,最常见的莫过于Excel和csv了。笔者写下此案例供大家参考。
1. maven依赖包
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.train</groupId>
<artifactId>Rz</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<poi.version>3.9</poi.version>
</properties>
<dependencies>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>${poi.version}</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-excelant</artifactId>
<version>${poi.version}</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>${poi.version}</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>${poi.version}</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-scratchpad</artifactId>
<version>${poi.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.3.2</version>
</dependency>
<dependency>
<groupId>org.apache.xmlbeans</groupId>
<artifactId>xmlbeans</artifactId>
<version>2.6.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.40</version>
</dependency>
</dependencies>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.0.0</version>
<configuration>
<warSourceDirectory>WebContent</warSourceDirectory>
</configuration>
</plugin>
</plugins>
</build>
</project>
2. 工具类
package com.rz.util;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
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;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
/**
* 利用开源组件POI3.9动态导出EXCEL文档
* @param <T>
* 应用泛型,代表任意一个符合javabean风格的类
* 注意这里为了简单起见,boolean型的属性xxx的get器方式为getXxx(),而不是isXxx()
* byte[]表jpg格式的图片数据
*/
public class ExportExcelUtil {
private static final int FLUSH_COUNT=50;
/**
* 把结果集导入excel
* @param title
* @param resultSet
* @param out
* @throws Exception
*/
public int exportExcelForResultSet(ResultSet resultSet, File file) throws Exception {
if(resultSet == null){
return 0;
}
OutputStream out = new FileOutputStream(file);
int rowaccess=100;
// 声明一个工作薄
SXSSFWorkbook workbook = new SXSSFWorkbook(rowaccess);
//获取头部
String[] headers = getHeaders(resultSet);
Sheet sheet = null;
Row row = null;
// 遍历集合数据,产生数据行
int index = 0;
int sheetIndex = 0;
int sheetCount = 0;
while (resultSet.next()) {
if(index%1048575 == 0){
sheetCount++;
sheet = createSheet("第"+sheetCount+"页", workbook, headers);
sheetIndex = 0;
}
sheetIndex++;
index++;
row = sheet.createRow(sheetIndex);
for (int i = 1; i <= headers.length; i++) {
Cell cell = row.createCell(i-1);
cell.setCellValue(resultSet.getString(i));
}
if(index%FLUSH_COUNT == 0){
((SXSSFSheet)sheet).flushRows();
}
}
workbook.write(out);
out.close();
return index;
}
/**
* 获取结果集列信息
* @param resultSet
* @return
* @throws SQLException
*/
private String[] getHeaders(ResultSet resultSet) throws SQLException{
ResultSetMetaData m=null;//获取 列信息
m=resultSet.getMetaData();
int columns=m.getColumnCount();
String[] headers = new String[columns];
//显示列,表格的表头
for(int i=1;i<=columns;i++){
headers[i-1] = getColumnName(m.getColumnName(i));
}
return headers;
}
/**
* 获取列名 去除列名前的多余字符(_u1.在线楼盘数-->在线楼盘数)
* @param columnName
* @return
*/
private String getColumnName(String columnName){
if(StringUtils.isNotBlank(columnName)){
if(columnName.indexOf(".") != -1){
return StringUtils.split(columnName, ".")[1];
}
return columnName;
}
return null;
}
private Sheet createSheet(String title, SXSSFWorkbook workbook,String[] headers) throws SQLException{
// 生成一个表格
Sheet sheet = workbook.createSheet(title);
// 设置表格默认列宽度为15个字节
sheet.setDefaultColumnWidth(30);
// 生成一个样式
CellStyle style = workbook.createCellStyle();
style.setAlignment(CellStyle.ALIGN_CENTER);
// 设置单元格字体
Font headerFont = workbook.createFont(); // 字体
headerFont.setFontHeightInPoints((short)14);
headerFont.setColor(HSSFColor.BLACK.index);
headerFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
headerFont.setFontName("宋体");
style.setFont(headerFont);
style.setWrapText(false);
// 产生表格标题行
Row row = sheet.createRow(0);
for (int i = 0; i < headers.length; i++) {
Cell cell = row.createCell(i);
cell.setCellStyle(style);
cell.setCellValue(headers[i]);
}
return sheet;
}
/**
* 把结果集导出为csv文件并返回结果记录数
* @param resultSet
* @param file
* @return
* @throws Exception
*/
public int exportCsv(ResultSet resultSet, File file) throws Exception{
BufferedWriter bw =new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "GBK")) ;// 附加
// 添加头部
String[] headers = getHeaders(resultSet);
bw.write(StringUtils.join(headers, ","));
bw.newLine();
//添加数据
int index = 0;
StringBuffer sb = new StringBuffer();
while (resultSet.next()) {
index++;
for(int i=1;i<=headers.length;i++){
String value = resultSet.getString(i);
if(value != null && !"".equals(value)){
value = value.replaceAll("\\,", ",");
}
if(i == headers.length){
sb.append(value);
}else{
sb.append(value+",");
}
}
bw.write(sb.toString());
sb.setLength(0);
bw.newLine();
if(index%FLUSH_COUNT == 0){
bw.flush();
}
}
bw.close();
return index;
}
public <T> void exportExcel(String title, String[] headers, List<T> dataset , OutputStream out) {
// 声明一个工作薄
HSSFWorkbook workbook = new HSSFWorkbook();
// 生成一个表格
HSSFSheet sheet = workbook.createSheet(title);
// 设置表格默认列宽度为15个字节
sheet.setDefaultColumnWidth(30);
// 生成一个样式
HSSFCellStyle style = workbook.createCellStyle();
setHeaderCellStyle(style, workbook);
// 生成并设置另一个样式
HSSFCellStyle style2 = workbook.createCellStyle();
setBodyCellStyle(style2, workbook);
// 声明一个画图的顶级管理器
HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
// 产生表格标题行
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);
}
// 遍历集合数据,产生数据行
Iterator<T> it = dataset.iterator();
int index = 0;
while (it.hasNext()) {
index++;
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);
cell.setCellStyle(style2);
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 = null;
if (value instanceof Integer) {
int intValue = (Integer) value;
cell.setCellValue(intValue);
} else if (value instanceof Float) {
float fValue = (Float) value;
textValue = String.valueOf(fValue);
cell.setCellValue(textValue);
} else if (value instanceof Double) {
double dValue = (Double) value;
textValue = String.valueOf(dValue);
cell.setCellValue(textValue);
} else if (value instanceof Long) {
long longValue = (Long) value;
cell.setCellValue(longValue);
}
if (value instanceof Boolean) {
boolean bValue = (Boolean) value;
//需自定义显示数据
textValue = "";
if (!bValue) {
textValue = "";
}
} else if (value instanceof Date) {
Date date = (Date) value;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
textValue = sdf.format(date);
} else if (value instanceof byte[]) {
// 有图片时,设置行高为60px;
row.setHeightInPoints(60);
// 设置图片所在列宽度为80px,注意这里单位的一个换算
sheet.setColumnWidth(i, (short) (35.7 * 80));
// sheet.autoSizeColumn(i);
byte[] bsValue = (byte[]) value;
HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 1023, 255, (short) 6, index, (short) 6,index);
anchor.setAnchorType(2);
patriarch.createPicture(anchor, workbook.addPicture(bsValue, HSSFWorkbook.PICTURE_TYPE_JPEG));
} else {
// 其它数据类型都当作字符串简单处理
textValue = value.toString();
}
// 如果不是图片数据,就利用正则表达式判断textValue是否全部由数字组成
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);
HSSFFont font3 = workbook.createFont();
font3.setColor(HSSFColor.BLUE.index);
richString.applyFont(font3);
cell.setCellValue(richString);
}
}
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} finally {
// 清理资源
}
}
}
try {
workbook.write(out);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 设置内容样式
* @param style
*/
private void setBodyCellStyle(HSSFCellStyle style,HSSFWorkbook workbook){
style.setFillForegroundColor(HSSFColor.LIGHT_YELLOW.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);
style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
// 生成另一个字体
HSSFFont font = workbook.createFont();
font.setFontName("Courier New");
font.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
// 把字体应用到当前的样式
style.setFont(font);
}
/**
* 设置标题样式
* @param style
*/
private void setHeaderCellStyle(HSSFCellStyle style,HSSFWorkbook workbook){
style.setFillForegroundColor(HSSFColor.GREY_40_PERCENT.index);
style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
// 设置边框
style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
// 设置边框颜色
style.setTopBorderColor(HSSFColor.BLACK.index); // 设置顶边框颜色;
style.setBottomBorderColor(HSSFColor.BLACK.index); // 设置底边框颜色;
style.setLeftBorderColor(HSSFColor.BLACK.index);// 设置左边框颜色;
style.setRightBorderColor(HSSFColor.BLACK.index);// 设置右边框颜色;
//设置自动换行
style.setWrapText(false);
// 生成一个字体
HSSFFont font = workbook.createFont();
font.setFontName("Courier New");
font.setColor(HSSFColor.WHITE.index);
font.setFontHeightInPoints((short) 12);
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
// 把字体应用到当前的样式
style.setFont(font);
}
}
3 . 测试类
package com.rz.util;
import java.io.File;
import java.sql.*;
public class MySQLDemo {
// JDBC 驱动名及数据库 URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/xxx";
// 数据库的用户名与密码,需要根据自己的设置
static final String USER = "root";
static final String PASS = "root";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
File file=new File("C:\\work\\export.xlsx");
File csvfile=new File("C:\\work\\export.csv");
try{
// 注册 JDBC 驱动
Class.forName(JDBC_DRIVER);
// 打开链接
System.out.println("连接数据库...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
// 执行查询
System.out.println(" 实例化Statement对象...");
stmt = conn.createStatement();
String sql = "select login_name, name, password, age,phone FROM user";;
ResultSet rs = stmt.executeQuery(sql);
// System.out.println("totalCount:->"+new ExportExcelUtil().exportExcelForResultSet(rs, file));
System.out.println("totalCount:->"+new ExportExcelUtil().exportCsv(rs, csvfile));
// 展开结果集数据库
// while(rs.next()){
// // 通过字段检索
// String login_name = rs.getString("login_name");
// String name = rs.getString("name");
// String password = rs.getString("password");
// String age = rs.getString("age");
// String phone = rs.getString("phone");
// }
// 完成后关闭
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
// 处理 JDBC 错误
se.printStackTrace();
}catch(Exception e){
// 处理 Class.forName 错误
e.printStackTrace();
}finally{
// 关闭资源
try{
if(stmt!=null) stmt.close();
}catch(SQLException se2){
}// 什么都不做
try{
if(conn!=null) conn.close();
}catch(SQLException se){
se.printStackTrace();
}
}
System.out.println("Goodbye!");
}
}
ok,看完上面的例子,相信你对数据的导出已经有了一定的学习了,想要学习更多,请移步这里。