欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java导出Excel通用工具类实例代码

程序员文章站 2022-06-23 08:36:55
一、概述相信大家在工作过程中,都会遇到这样一个需求,就是将相关的数据列表导出成excel,那么,有没有通用的导出方式呢,这里,就带着大家一起来用java实现一个通用的导出excel的工具。二、项目实现...

一、概述

相信大家在工作过程中,都会遇到这样一个需求,就是将相关的数据列表导出成excel,那么,有没有通用的导出方式呢,这里,就带着大家一起来用java实现一个通用的导出excel的工具。

二、项目实现

1、构建pom.xml

我们的工程是利用maven来构建的,项目具体搭建过程大家可以参见网上其他资料,这里我们仅给出最核心的maven配置

<dependency>
	<groupid>org.apache.poi</groupid>
	<artifactid>poi-scratchpad</artifactid>
	<version>3.11-beta2</version>
</dependency>
<dependency>
	<groupid>org.apache.poi</groupid>
	<artifactid>poi-ooxml</artifactid>
	<version>3.11-beta2</version>
</dependency>
<dependency>
	<groupid>org.apache.poi</groupid>
	<artifactid>poi-ooxml-schemas</artifactid>
	<version>3.11-beta2</version>
</dependency>
<dependency>
	<groupid>org.apache.poi</groupid>
	<artifactid>poi-excelant</artifactid>
	<version>3.11-beta2</version>
</dependency>

2、编写exportexcelutil类

这个类使我们整个工具的核心,它实现了excel文件的导出功能,具体代码如下:

package com.lyz.utils.excel.poi;
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.text.simpledateformat;
import java.util.collection;
import java.util.date;
import java.util.iterator;
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.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.apache.poi.xssf.usermodel.xssfcell;
import org.apache.poi.xssf.usermodel.xssfcellstyle;
import org.apache.poi.xssf.usermodel.xssfcolor;
import org.apache.poi.xssf.usermodel.xssffont;
import org.apache.poi.xssf.usermodel.xssfrichtextstring;
import org.apache.poi.xssf.usermodel.xssfrow;
import org.apache.poi.xssf.usermodel.xssfsheet;
import org.apache.poi.xssf.usermodel.xssfworkbook;
 
 
/**
 * 导出excel
 * @author liuyazhuang
 *
 * @param <t>
 */
public class exportexcelutil<t>{
	
	// 2007 版本以上 最大支持1048576行
	public final static string excel_file_2007 = "2007";
	// 2003 版本 最大支持65536 行
	public final static string excel_file_2003 = "2003";
	
	/**
	 * <p>
	 * 导出无头部标题行excel <br>
	 * 时间格式默认:yyyy-mm-dd hh:mm:ss <br>
	 * </p>
	 * 
	 * @param title 表格标题
	 * @param dataset 数据集合
	 * @param out 输出流
	 * @param version 2003 或者 2007,不传时默认生成2003版本
	 */
	public void exportexcel(string title, collection<t> dataset, outputstream out, string version) {
		if(stringutils.isempty(version) || excel_file_2003.equals(version.trim())){
			exportexcel2003(title, null, dataset, out, "yyyy-mm-dd hh:mm:ss");
		}else{
			exportexcel2007(title, null, dataset, out, "yyyy-mm-dd hh:mm:ss");
		}
	}
 
	/**
	 * <p>
	 * 导出带有头部标题行的excel <br>
	 * 时间格式默认:yyyy-mm-dd hh:mm:ss <br>
	 * </p>
	 * 
	 * @param title 表格标题
	 * @param headers 头部标题集合
	 * @param dataset 数据集合
	 * @param out 输出流
	 * @param version 2003 或者 2007,不传时默认生成2003版本
	 */
	public void exportexcel(string title,string[] headers, collection<t> dataset, outputstream out,string version) {
		if(stringutils.isblank(version) || excel_file_2003.equals(version.trim())){
			exportexcel2003(title, headers, dataset, out, "yyyy-mm-dd hh:mm:ss");
		}else{
			exportexcel2007(title, headers, dataset, out, "yyyy-mm-dd hh:mm:ss");
		}
	}
 
	/**
	 * <p>
	 * 通用excel导出方法,利用反射机制遍历对象的所有字段,将数据写入excel文件中 <br>
	 * 此版本生成2007以上版本的文件 (文件后缀:xlsx)
	 * </p>
	 * 
	 * @param title
	 *   表格标题名
	 * @param headers
	 *   表格头部标题集合
	 * @param dataset
	 *   需要显示的数据集合,集合中一定要放置符合javabean风格的类的对象。此方法支持的
	 *   javabean属性的数据类型有基本数据类型及string,date
	 * @param out
	 *   与输出设备关联的流对象,可以将excel文档导出到本地文件或者网络中
	 * @param pattern
	 *   如果有时间数据,设定输出格式。默认为"yyyy-mm-dd hh:mm:ss"
	 */
	@suppresswarnings({ "unchecked", "rawtypes" })
	public void exportexcel2007(string title, string[] headers, collection<t> dataset, outputstream out, string pattern) {
		// 声明一个工作薄
		xssfworkbook workbook = new xssfworkbook();
		// 生成一个表格
		xssfsheet sheet = workbook.createsheet(title);
		// 设置表格默认列宽度为15个字节
		sheet.setdefaultcolumnwidth(20);
		// 生成一个样式
		xssfcellstyle style = workbook.createcellstyle();
		// 设置这些样式
		style.setfillforegroundcolor(new xssfcolor(java.awt.color.gray));
		style.setfillpattern(xssfcellstyle.solid_foreground);
		style.setborderbottom(xssfcellstyle.border_thin);
		style.setborderleft(xssfcellstyle.border_thin);
		style.setborderright(xssfcellstyle.border_thin);
		style.setbordertop(xssfcellstyle.border_thin);
		style.setalignment(xssfcellstyle.align_center);
		// 生成一个字体
		xssffont font = workbook.createfont();
		font.setboldweight(xssffont.boldweight_bold);
		font.setfontname("宋体"); 
		font.setcolor(new xssfcolor(java.awt.color.black));
		font.setfontheightinpoints((short) 11);
		// 把字体应用到当前的样式
		style.setfont(font);
		// 生成并设置另一个样式
		xssfcellstyle style2 = workbook.createcellstyle();
		style2.setfillforegroundcolor(new xssfcolor(java.awt.color.white));
		style2.setfillpattern(xssfcellstyle.solid_foreground);
		style2.setborderbottom(xssfcellstyle.border_thin);
		style2.setborderleft(xssfcellstyle.border_thin);
		style2.setborderright(xssfcellstyle.border_thin);
		style2.setbordertop(xssfcellstyle.border_thin);
		style2.setalignment(xssfcellstyle.align_center);
		style2.setverticalalignment(xssfcellstyle.vertical_center);
		// 生成另一个字体
		xssffont font2 = workbook.createfont();
		font2.setboldweight(xssffont.boldweight_normal);
		// 把字体应用到当前的样式
		style2.setfont(font2);
 
		// 产生表格标题行
		xssfrow row = sheet.createrow(0);
		xssfcell cellheader;
		for (int i = 0; i < headers.length; i++) {
			cellheader = row.createcell(i);
			cellheader.setcellstyle(style);
			cellheader.setcellvalue(new xssfrichtextstring(headers[i]));
		}
 
		// 遍历集合数据,产生数据行
		iterator<t> it = dataset.iterator();
		int index = 0;
		t t;
		field[] fields;
		field field;
		xssfrichtextstring richstring;
		pattern p = pattern.compile("^//d+(//.//d+)?$");
		matcher matcher;
		string fieldname;
		string getmethodname;
		xssfcell cell;
		class tcls;
		method getmethod;
		object value;
		string textvalue;
		simpledateformat sdf = new simpledateformat(pattern);
		while (it.hasnext()) {
			index++;
			row = sheet.createrow(index);
			t = (t) it.next();
			// 利用反射,根据javabean属性的先后顺序,动态调用getxxx()方法得到属性值
			fields = t.getclass().getdeclaredfields();
			for (int i = 0; i < fields.length; i++) {
				cell = row.createcell(i);
				cell.setcellstyle(style2);
				field = fields[i];
				fieldname = field.getname();
				getmethodname = "get" + fieldname.substring(0, 1).touppercase()
						+ fieldname.substring(1);
				try {
					tcls = t.getclass();
					getmethod = tcls.getmethod(getmethodname, new class[] {});
					value = getmethod.invoke(t, new object[] {});
					// 判断值的类型后进行强制类型转换
					textvalue = null;
					if (value instanceof integer) {
						cell.setcellvalue((integer) value);
					} else if (value instanceof float) {
						textvalue = string.valueof((float) value);
						cell.setcellvalue(textvalue);
					} else if (value instanceof double) {
						textvalue = string.valueof((double) value);
						cell.setcellvalue(textvalue);
					} else if (value instanceof long) {
						cell.setcellvalue((long) value);
					}
					if (value instanceof boolean) {
						textvalue = "是";
						if (!(boolean) value) {
							textvalue = "否";
						}
					} else if (value instanceof date) {
						textvalue = sdf.format((date) value);
					} else {
						// 其它数据类型都当作字符串简单处理
						if (value != null) {
							textvalue = value.tostring();
						}
					}
					if (textvalue != null) {
						matcher = p.matcher(textvalue);
						if (matcher.matches()) {
							// 是数字当作double处理
							cell.setcellvalue(double.parsedouble(textvalue));
						} else {
							richstring = new xssfrichtextstring(textvalue);
							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();
		}
	}
	
	
	
	/**
	 * <p>
	 * 通用excel导出方法,利用反射机制遍历对象的所有字段,将数据写入excel文件中 <br>
	 * 此方法生成2003版本的excel,文件名后缀:xls <br>
	 * </p>
	 * 
	 * @param title
	 *   表格标题名
	 * @param headers
	 *   表格头部标题集合
	 * @param dataset
	 *   需要显示的数据集合,集合中一定要放置符合javabean风格的类的对象。此方法支持的
	 *   javabean属性的数据类型有基本数据类型及string,date
	 * @param out
	 *   与输出设备关联的流对象,可以将excel文档导出到本地文件或者网络中
	 * @param pattern
	 *   如果有时间数据,设定输出格式。默认为"yyyy-mm-dd hh:mm:ss"
	 */
	@suppresswarnings({ "unchecked", "rawtypes" })
	public void exportexcel2003(string title, string[] headers, collection<t> dataset, outputstream out, string pattern) {
		// 声明一个工作薄
		hssfworkbook workbook = new hssfworkbook();
		// 生成一个表格
		hssfsheet sheet = workbook.createsheet(title);
		// 设置表格默认列宽度为15个字节
		sheet.setdefaultcolumnwidth(20);
		// 生成一个样式
		hssfcellstyle style = workbook.createcellstyle();
		// 设置这些样式
		style.setfillforegroundcolor(hssfcolor.grey_50_percent.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 = workbook.createfont();
		font.setboldweight(hssffont.boldweight_bold);
		font.setfontname("宋体"); 
		font.setcolor(hssfcolor.white.index);
		font.setfontheightinpoints((short) 11);
		// 把字体应用到当前的样式
		style.setfont(font);
		// 生成并设置另一个样式
		hssfcellstyle style2 = workbook.createcellstyle();
		style2.setfillforegroundcolor(hssfcolor.white.index);
		style2.setfillpattern(hssfcellstyle.solid_foreground);
		style2.setborderbottom(hssfcellstyle.border_thin);
		style2.setborderleft(hssfcellstyle.border_thin);
		style2.setborderright(hssfcellstyle.border_thin);
		style2.setbordertop(hssfcellstyle.border_thin);
		style2.setalignment(hssfcellstyle.align_center);
		style2.setverticalalignment(hssfcellstyle.vertical_center);
		// 生成另一个字体
		hssffont font2 = workbook.createfont();
		font2.setboldweight(hssffont.boldweight_normal);
		// 把字体应用到当前的样式
		style2.setfont(font2);
 
		// 产生表格标题行
		hssfrow row = sheet.createrow(0);
		hssfcell cellheader;
		for (int i = 0; i < headers.length; i++) {
			cellheader = row.createcell(i);
			cellheader.setcellstyle(style);
			cellheader.setcellvalue(new hssfrichtextstring(headers[i]));
		}
 
		// 遍历集合数据,产生数据行
		iterator<t> it = dataset.iterator();
		int index = 0;
		t t;
		field[] fields;
		field field;
		hssfrichtextstring richstring;
		pattern p = pattern.compile("^//d+(//.//d+)?$");
		matcher matcher;
		string fieldname;
		string getmethodname;
		hssfcell cell;
		class tcls;
		method getmethod;
		object value;
		string textvalue;
		simpledateformat sdf = new simpledateformat(pattern);
		while (it.hasnext()) {
			index++;
			row = sheet.createrow(index);
			t = (t) it.next();
			// 利用反射,根据javabean属性的先后顺序,动态调用getxxx()方法得到属性值
			fields = t.getclass().getdeclaredfields();
			for (int i = 0; i < fields.length; i++) {
				cell = row.createcell(i);
				cell.setcellstyle(style2);
				field = fields[i];
				fieldname = field.getname();
				getmethodname = "get" + fieldname.substring(0, 1).touppercase()
						+ fieldname.substring(1);
				try {
					tcls = t.getclass();
					getmethod = tcls.getmethod(getmethodname, new class[] {});
					value = getmethod.invoke(t, new object[] {});
					// 判断值的类型后进行强制类型转换
					textvalue = null;
					if (value instanceof integer) {
						cell.setcellvalue((integer) value);
					} else if (value instanceof float) {
						textvalue = string.valueof((float) value);
						cell.setcellvalue(textvalue);
					} else if (value instanceof double) {
						textvalue = string.valueof((double) value);
						cell.setcellvalue(textvalue);
					} else if (value instanceof long) {
						cell.setcellvalue((long) value);
					}
					if (value instanceof boolean) {
						textvalue = "是";
						if (!(boolean) value) {
							textvalue = "否";
						}
					} else if (value instanceof date) {
						textvalue = sdf.format((date) value);
					} else {
						// 其它数据类型都当作字符串简单处理
						if (value != null) {
							textvalue = value.tostring();
						}
					}
					if (textvalue != null) {
						matcher = p.matcher(textvalue);
						if (matcher.matches()) {
							// 是数字当作double处理
							cell.setcellvalue(double.parsedouble(textvalue));
						} else {
							richstring = new hssfrichtextstring(textvalue);
							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();
		}
	}
}

为了演示导出功能,这里我们创建了一个student学生类。

3、创建student类

package com.lyz.utils.excel.poi;
 
/**
 * 例子javabean
 * @author liuyazhuang
 *
 */
public class student {
 private int id;
 private string name;
 private string sex;
 
 public student(int id, string name, string sex) {
  this.id = id;
  this.name = name;
  this.sex = sex;
 }
 
 public int getid() {
  return id;
 }
 
 public void setid(int id) {
  this.id = id;
 }
 
 public string getname() {
  return name;
 }
 
 public void setname(string name) {
  this.name = name;
 }
 
 public string getsex() {
  return sex;
 }
 
 public void setsex(string sex) {
  this.sex = sex;
 }
}

4、创建测试类testexportexcelutil

这个类,主要是用来测试我们的工具类。具体代码如下:

package com.lyz.test;
 
import java.io.fileoutputstream;
import java.util.arraylist;
import java.util.list;
 
import com.lyz.utils.excel.poi.exportexcelutil;
import com.lyz.utils.excel.poi.student;
 
/**
 * 测试文件导出
 * @author liuyazhuang
 *
 */
public class testexportexcelutil {
	
	public static void main(string[] args) throws exception{
		exportexcelutil<student> util = new exportexcelutil<student>();
		 // 准备数据
  list<student> list = new arraylist<>();
  for (int i = 0; i < 10; i++) {
  	 list.add(new student(111,"张三asdf","男"));
    list.add(new student(111,"李四asd","男"));
    list.add(new student(111,"王五","女"));
  }
  string[] columnnames = { "id", "姓名", "性别" };
  util.exportexcel("用户导出", columnnames, list, new fileoutputstream("e:/test.xls"), exportexcelutil.excel_file_2003);
	}
}

5、测试

我们运行testexportexcelutil类,会发现在我们的e盘下生成了test.xls文件,具体如下:

Java导出Excel通用工具类实例代码

三、项目扩展

以上实现均是在本地磁盘生成excel文件,但更多的时候,我们需要通过点击网页上的某个按钮来自动生成并下载excel文档,那么,这又如何实现呢?下面我们就一起来实现这个功能。

1、扩展exportexcelutil类

根据java的继承思想,我们不在exportexcelutil类上修改添加,我们创建一个exportexcelutil类的子类exportexcelwrapper,这个类继承exportexcelutil的所有功能,同时,扩展了网页生成excel的功能。具体代码如下:

package com.lyz.utils.excel.poi;
 
import java.net.urlencoder;
import java.util.collection;
 
import javax.servlet.http.httpservletresponse;
 
import org.apache.commons.lang3.stringutils;
 
/**
 * 包装类
 * @author liuyazhuang
 *
 * @param <t>
 */
public class exportexcelwrapper<t> extends exportexcelutil<t> {
	/**
	 * <p>
	 * 导出带有头部标题行的excel <br>
	 * 时间格式默认:yyyy-mm-dd hh:mm:ss <br>
	 * </p>
	 * 
	 * @param title 表格标题
	 * @param headers 头部标题集合
	 * @param dataset 数据集合
	 * @param out 输出流
	 * @param version 2003 或者 2007,不传时默认生成2003版本
	 */
	public void exportexcel(string filename, string title, string[] headers, collection<t> dataset, httpservletresponse response,string version) {
		try {
			response.setcontenttype("application/vnd.ms-excel"); 
 		response.addheader("content-disposition", "attachment;filename="+ urlencoder.encode(filename, "utf-8") + ".xls");
			if(stringutils.isblank(version) || excel_file_2003.equals(version.trim())){
				exportexcel2003(title, headers, dataset, response.getoutputstream(), "yyyy-mm-dd hh:mm:ss");
			}else{
				exportexcel2007(title, headers, dataset, response.getoutputstream(), "yyyy-mm-dd hh:mm:ss");
			}
		} catch (exception e) {
			e.printstacktrace();
		}
	}
}

这样,我们可以在controller层调用exportexcelwrapper将相关的数据和httpservletresponse传递进来,即可实现通过网页生生并下载excel文档了。

2、编写controller类

@controller("test")
@requestmapping("/test")
public class testcontroller {
	@requestmapping("/get/excel")
	public void getexcel(httpservletrequest request, httpservletresponse response) throws exception {
		// 准备数据
		list<student> list = new arraylist<>();
		for (int i = 0; i < 10; i++) {
			 list.add(new student(111,"张三asdf","男"));
		  list.add(new student(111,"李四asd","男"));
		  list.add(new student(111,"王五","女"));
		}
		string[] columnnames = { "id", "姓名", " 性别"};
		string filename = "excel1";
		exportexcelwrapper<student> util = new exportexcelwrapper<student>();
		util.exportexcel(filename, filename, columnnames, list, response, exportexcelutil.excel_file_2003);
	}
}

3、编写index.html

这个网页很简单,具体实现如下:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>导出excel</title>
</head>
<body>
<form id="form_login" action="http://127.0.0.1:8080/test/get/excel" method="post">
 
</form>
<button id="btn-submit" onclick="beforesubmit()">submit</button>
<script type="text/javascript">
 var loginform = document.getelementbyid('form_login');
 function beforesubmit() {
  loginform.submit();
 }
</script>
</body>
</html>

4、测试

我们将程序发布到tomcat,并点击网上的按钮,效果如下:

Java导出Excel通用工具类实例代码

我们打开excel1.xls文件如下:

Java导出Excel通用工具类实例代码

至此,我们的工具就编写完成了。

总结

到此这篇关于java导出excel通用工具类的文章就介绍到这了,更多相关java导出excel内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

相关标签: java 导出 excel