Java和poi导出excel报表

一:poi jar下载地址:点击打开链接:


二:工程截图:


三:运行效果截图:


四:源代码:

Student.java:

package com.poi.bean;import java.util.Date;public class Student {private long id;// 学号private String name;// 姓名private int age;// 年龄private boolean sex;// 性别private Date birthday;// 出生日期public Student() {super();}public Student(long id, String name, int age, boolean sex, Date birthday) {super();this.id = id;this.name = name;this.age = age;this.sex = sex;this.birthday = birthday;}public long getId() {return id;}public void setId(long id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public boolean getSex() {return sex;}public void setSex(boolean sex) {this.sex = sex;}public Date getBirthday() {return birthday;}public void setBirthday(Date birthday) {this.birthday = birthday;}}

Book.java

package com.poi.bean;public class Book {private int bookId;// 图书编号private String name;// 图书名称private String author;// 图书作者private float price;// 图书价格private String isbn;// 图书ISBNprivate String pubName;// 图书出版社private byte[] preface;// 封面图片public Book() {super();}public Book(int bookId, String name, String author, float price,String isbn, String pubName, byte[] preface) {super();this.bookId = bookId;this.name = name;this.author = author;this.price = price;this.isbn = isbn;this.pubName = pubName;this.preface = preface;}public int getBookId() {return bookId;}public void setBookId(int bookId) {this.bookId = bookId;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getAuthor() {return author;}public void setAuthor(String author) {this.author = author;}public float getPrice() {return price;}public void setPrice(float price) {this.price = price;}public String getIsbn() {return isbn;}public void setIsbn(String isbn) {this.isbn = isbn;}public String getPubName() {return pubName;}public void setPubName(String pubName) {this.pubName = pubName;}public byte[] getPreface() {return preface;}public void setPreface(byte[] preface) {this.preface = preface;}}

ExportExcel.java

package com.poi.util;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.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;import javax.swing.JOptionPane;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.HSSFComment;
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 com.poi.bean.Student;/*** 利用开源组件POI3.0.2动态导出EXCEL文档 转载时请保留以下信息,注明出处!* * @author zhaoxinguo* @version v1.0* @param <T>应用泛型,代表任意一个符合javabean风格的类*        注意这里为了简单起见,boolean型的属性xxx的get器方式为getXxx(),而不是isXxx() byte[]表jpg格式的图片数据*/
public class ExportExcel<T> {public void exportExcel(Collection<T> dataset, OutputStream out){exportExcel("测试POI导出EXCEL文档", null, dataset, out, "yyyy-MM-dd");}public void exportExcel(String[] headers, Collection<T> dataset,OutputStream out) {exportExcel("测试POI导出EXCEL文档", headers, dataset, out, "yyyy-MM-dd");}public void exportExcel(String[] headers, Collection<T> dataset,OutputStream out, String pattern) {exportExcel("测试POI导出EXCEL文档", headers, dataset, out, pattern);}/*** 这是一个通用的方法,利用了JAVA的反射机制,可以将放置在JAVA集合中并且符号一定条件的数据以EXCEL 的形式输出到指定IO设备上* * @param title*            表格标题名* @param headers表格属性列名数组* @param dataset需要显示的数据集合*            ,集合中一定要放置符合javabean风格的类的对象。此方法支持的javabean属性的数据类型有基本数据类型及String*            ,Date,byte[](图片数据)* @param out与输出设备关联的流对象*            ,可以将EXCEL文档导出到本地文件或者网络中* @param pattern如果有时间数据*            ,设定输出格式。默认为"yyy-MM-dd"*/public void exportExcel(String title, String[] headers, Collection<T> dataset, OutputStream out, String pattern){//声明一个工作薄HSSFWorkbook workbook = new HSSFWorkbook();//生成一个表格HSSFSheet sheet = workbook.createSheet(title);//设置表格默认列宽为15个字节sheet.setDefaultColumnWidth((short) 15);//生成一个样式HSSFCellStyle style = workbook.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 = workbook.createFont();font.setColor(HSSFColor.VIOLET.index);font.setFontHeightInPoints((short) 12);font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);//把字体应用到当前的样式style.setFont(font);//生成并设置另一样式HSSFCellStyle style2 = workbook.createCellStyle();style2.setFillForegroundColor(HSSFColor.LIGHT_YELLOW.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);//声明一个画图的顶级管理器HSSFPatriarch patriarch = sheet.createDrawingPatriarch();//定义注释的大小和位置,详见文档HSSFComment comment = patriarch.createComment(new HSSFClientAnchor(0, 0, 0, 0, (short) 4, 2, (short) 6, 5));//设置注释内容comment.setString(new HSSFRichTextString("可以在POI中添加注释!"));//设置注释作者,当鼠标移动到单元格上是可以在状态栏中看到该内容.comment.setAuthor("zhaoxinguo");//产生表格标题行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 Boolean){boolean bValue = (Boolean) value;textValue = "男";if(!bValue){textValue = "女";}}else if(value instanceof Date){Date date = (Date) value;SimpleDateFormat sdf = new SimpleDateFormat(pattern);textValue = sdf.format(date);}else if(value instanceof byte[]){// 有图片时,设置行高为60px;row.setHeightInPoints(60);// 设置图片所在列宽度为80px,注意这里单位的一个换算sheet.setColumnWidth(i, (short)(35.7*80));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 (Exception e) {e.printStackTrace();} finally{//清理资源}}}try {workbook.write(out);} catch (IOException e) {e.printStackTrace();}}public static void main(String[] args) throws Exception{//测试学生ExportExcel<Student> exportExcel = new ExportExcel<Student>();String[] headers = {"学号","姓名","年龄","性别","出生日期"};List<Student> dataset = new ArrayList<Student>();dataset.add(new Student(10000001, "张三", 20, true, new Date()));dataset.add(new Student(20000002, "李四", 24, false, new Date()));dataset.add(new Student(30000003, "王五", 22, true, new Date()));OutputStream out = new FileOutputStream("E://Student.xls");exportExcel.exportExcel(headers, dataset, out);out.close();JOptionPane.showMessageDialog(null, "导出成功");//测试图书/*ExportExcel<Book> exportExcel2 = new ExportExcel<Book>();String[] headers2 = {"图书编号", "图书名称", "图书作者", "图书价格", "图书ISBN","图书出版社", "封面图片" };List<Book> dataset2 = new ArrayList<Book>();BufferedInputStream bis = new 	BufferedInputStream(new FileInputStream("D://book.jpg"));byte[] buf = new byte[bis.available()];while((bis.read(buf)) != -1){}dataset2.add(new Book(1, "jsp", "leno", 300.33f, "1234567", "清华出版社",buf));dataset2.add(new Book(2, "java编程思想", "brucl", 300.33f, "1234567","阳光出版社", buf));dataset2.add(new Book(3, "DOM艺术", "lenotang", 300.33f, "1234567","清华出版社", buf));dataset2.add(new Book(4, "c++经典", "leno", 400.33f, "1234567", "清华出版社",buf));dataset2.add(new Book(5, "c#入门", "leno", 300.33f, "1234567", "汤春秀出版社",buf));OutputStream out2 = new FileOutputStream("E://Book.xls");exportExcel2.exportExcel(headers2, dataset2, out2);out2.close();JOptionPane.showMessageDialog(null, "导出成功");*/}
}

ExportServlet.java

package com.poi.servlet;import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;import org.apache.log4j.Logger;import com.poi.bean.Book;
import com.poi.util.ExportExcel;
/*** * @author zhaoxinguo* 使用servlet导出动态生成的excel文件,数据可以来源于数据库* 这样,浏览器客户端就可以访问该servlet得到一份用java代码动态生成的excel文件**/
public class ExportServlet extends HttpServlet {private static final long serialVersionUID = 1L;private Logger logger = Logger.getLogger(ExportServlet.class);public ExportServlet() {super();}protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {File file = new File(getServletContext().getRealPath("WEB-INF/book.jpg"));response.setContentType("octets/stream");response.addHeader("Content-Disposition", "attachment;filename=test.xls");//测试图书ExportExcel<Book> ex = new ExportExcel<Book>();String[] headers = { "图书编号", "图书名称", "图书作者", "图书价格", "图书ISBN","图书出版社", "封面图片" };List<Book> dataset = new ArrayList<Book>();BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));byte[] buf = new byte[bis.available()];while ((bis.read(buf)) != -1) {// 将图片数据存放到缓冲数组中}dataset.add(new Book(1, "jsp", "leno", 300.33f, "1234567", "清华出版社", buf));dataset.add(new Book(2, "java编程思想", "brucl", 300.33f, "1234567","阳光出版社", buf));dataset.add(new Book(3, "DOM艺术", "lenotang", 300.33f, "1234567","清华出版社", buf));dataset.add(new Book(4, "c++经典", "leno", 400.33f, "1234567", "清华出版社",buf));dataset.add(new Book(5, "c#入门", "leno", 300.33f, "1234567", "汤春秀出版社",buf));OutputStream out = response.getOutputStream();ex.exportExcel(headers, dataset, out);out.close();logger.info("excel导出成功!");}protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {doGet(request, response);}}

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"><display-name>poi</display-name><welcome-file-list><welcome-file>index.html</welcome-file><welcome-file>index.htm</welcome-file><welcome-file>index.jsp</welcome-file><welcome-file>default.html</welcome-file><welcome-file>default.htm</welcome-file><welcome-file>default.jsp</welcome-file></welcome-file-list><servlet><description></description><display-name>ExportServlet</display-name><servlet-name>ExportServlet</servlet-name><servlet-class>com.poi.servlet.ExportServlet</servlet-class></servlet><servlet-mapping><servlet-name>ExportServlet</servlet-name><url-pattern>/ExportServlet</url-pattern></servlet-mapping>
</web-app>


本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/443546.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

matlab汉明码psk,设计一个汉明码编码的2PSK调制的数字通信系统

汉明码信道编码的2psk调制数字通信系统设计一个采用2PSK调制的数字通信系统设计系统整体框图及数学模型&#xff1b;产生离散二进制信源&#xff0c;进行信道编码(汉明码)&#xff0c;产生BPSK信号&#xff1b; 加入信道噪声(高斯白噪声)&#xff1b;BPSK信号相干解调&#xff…

sh.k7p.work/index.php,Laowang's Blogs

OpenDayLight(硼Boron版本)实战开发入门OpenDayLight[1](简写为ODL)的硼Boron(0.5.0)版本于2016-09-16 这几天刚刚发布。作为一款开源SDN网络控制器&#xff0c;依托于强大的社区支持以及丰富的功能特性&#xff0c;ODL成为了目前主流的SDN网络控制器开发平台。不仅为开发者提供…

php接收不到ios值,php设置标签后,ios收不到,安卓可以收到

通过下面代码设置的标签&#xff1a;$client->device()->addTags($registration_id, test);通过下面代码推送的消息$result self::getClient()->push()->setPlatform([ios, android])->addTag([test])->setNotificationAlert($content)->options([time_t…

0+到10+随机数+java,java代码--实现随机输出10个随机数,并显示最大值,最小值

总结;对于length()属性&#xff0c;还不是很熟悉。不会用它。package com.s.x;//随机产生10个随机数&#xff0c;并且显示出最大值&#xff0c;最小值public class Love {public static void main(String[] args) {int a[] new int[10];int max, min;for (int i 0; i < 10…

oracle推送短信,ORACLE 10G如何实现发短信的服务?

CREATE OR REPLACE PROCEDURE SEND_MAIL(SUBJECT IN VARCHAR2,CONTENTSED IN VARCHAR2) ISEMAIL_SERVER VARCHAR2(30) : 10.1.200.6;SENDER_ADDRESS VARCHAR2(50) : testcz.com.cn;--发件地址RECEIVER_ADDRESS VARCHAR2(30); …

Java和iText导出pdf文档

一&#xff1a;工程截图&#xff1a; 二&#xff1a;项目运行截图&#xff1a; 三&#xff1a;源代码&#xff1a; Book.java package com.iText.bean;public class Book {private int bookId;// 图书编号private String name;// 图书名称private String author;// 图书作者pr…

oracle 12 ORA-01262,oracle物理dg安装:方法二

本文记录了物理dg的第二种安装方法&#xff0c;使用rman duplicate from active database&#xff0c;不需要做备份文件。准备工作&#xff1a;1.两台虚拟机&#xff0c;主机名&#xff1a;n1, n2&#xff0c;操作系统&#xff1a;centos6.7&#xff0c;建好信任关系2.oracle d…

linux多进程原理,Linux进程调度

极简模式假设我的系统只有一种调度算法cfs那么有个调度的队列 cfs_rq所有running的进程都会 进入这个队列&#xff0c;不在running 或者其他情况会出队列&#xff0c;ok。则假设队列控制的算法有以下。cfs_rq_enqueuecfs_rq_dequeuecfs_rq_pick所操作的是进程描述符 task_struc…

openwrt使用linux内核版本,降低OpenWRT的Linux内核版本

不久前&#xff0c;为了移植某驱动程序&#xff0c;笔者可谓绞尽脑汁&#xff0c;在4.1内核版本上&#xff0c;尝试了很多次都没能成功&#xff0c;后来仔细分析&#xff0c;才知道是内核版本过高导致的&#xff0c;本文给出降低内核版本的方法&#xff0c;具体编译环境的搭建&…

Hibernate3.x,hibernate3.x,Hibernate3.x整合Spring3.x不能实现自动创建表结构的解决办法:...

一&#xff1a;今天遇到一个诡异的问题&#xff0c;就是关于hibernate3.x实现表结构自动创建&#xff0c;一般我们在用Struts2&#xff0c;Hibernate3.x&#xff0c;Spring3.x搭建框架&#xff0c;尤其在开发阶段都希望在启动Web容器时就可以根据Bean实体自动创建数据表结构&am…

linux s t i a权限,关于Linux下s、t、i、a权限

关于Linux下s、t、i、a权限文件权限除了r、w、x外还有s、t、i、a权限&#xff1a;s&#xff1a;文件属主和组设置SUID和GUID&#xff0c;文件在被设置了s权限后将以root身份执行。在设置s权限时文件属主、属组必须先设置相应的x权限&#xff0c;否则s权限并不能正真生效(c h m …

linux ssh禁止用户访问任何目录,怎么限制远程ssh用户访问特定的文件

比如我要实现以下目标&#xff0c;通过配置linux限制SSH用户指定目录user 1 只可以访问 /Media, /Documents以及它的家目录User 2 只可以访问/Folder21, 以及它的家目录,User 3 只可以访问 /Documents, /Folder21 以及他的家目录,ssh如何限制指定目录2. 通过配置Linux权限限制S…

linux配置定时删除日志文件,Linux使用shell脚本定时删除历史日志文件

Linux使用shell脚本定时删除历史日志文件,文件,小时,时间,目录,脚本Linux使用shell脚本定时删除历史日志文件易采站长站&#xff0c;站长之家为您整理了Linux使用shell脚本定时删除历史日志文件的相关内容。1、tools目录文件结构[rootwww tools]# tree tools/tools/├── bin│…

linux awk执行shell命令,awk调用shell命令

在awk内部可利用管道和getline函数来调用shell命令&#xff0c;并可得到返回的具体结果&#xff0c;进行相应处理。例子如下&#xff1a;1) {while ( ("ls" | getline) >0 )print}输出当前目录下的所有文件&#xff0c;并打印到标准输出上。| 是管道&#xff0c;g…

linux添加启动脚本文件夹,linux – 将脚本中的符号链接添加到rc.d文件夹中以在系统启动期间启动进程...

我正在使用fedora 15.我试图添加MYSql守护进程在系统strtup期间启动.我已经明白我必须将它添加到rc5.d,因为它是默认目标&是graphical.target.来自inittab&#xff1a;systemd uses ‘targets’ instead of runlevels. By default, there are two main targets:multi-user.…

org.apache.commons.fileupload.FileUploadBase$SizeLimitExceededException:

一&#xff1a;今天在使用struts2做文件上传时出现了该异常&#xff1a; 警告: Unable to parse request org.apache.commons.fileupload.FileUploadBase$SizeLimitExceededException: the request was rejected because its size (5897994) exceeds the configured maximum (2…

linux天气软件,类似智能手机!Linux中安装Conky天气插件

如今&#xff0c;智能手机中很多都安装相匹配外观的天气小插件&#xff0c;而对于喜欢操作系统平台的用户而言&#xff0c;可以在你的Linux桌面中拥有像智能手机一样的天气外观。通过Flair Weather Conky可以将使用一个GUI工具Conky Manager在Linux中轻松地管理Conky。这里介绍…

linux go 安装路径,在Alpine Linux D的路径中找不到已安装的Go二进制文件

我有一个Go二进制文件&#xff0c;试图在Alpine Docker映像上运行。这对于Docker Go二进制文件很好用。docker run -it alpine:3.3 shapk add --no-cache curlDOCKER_BUCKETget.docker.comDOCKER_VERSION1.9.1curl -fSL "https://${DOCKER_BUCKET}/builds/Linux/x86_64/do…

linux安装下载中文包,linux下安装中文包和字体

在虚拟机中使用中文输入法和中文显示使用的是rhel5的镜像我把其镜像挂载在/mnt/cdrom中&#xff0c;然后切换到/Server目录下&#xff0c;安装支持中文字体Mount /dev/cdrom /mnt/cdromCd /mnt/cdrom/serverrpm -ivh fonts-chinese-3.02-9.6.el5.noarch.rpmrpm -ivh fonts-ISO8…

Java-Jdbc,JDBC连接Oracle11g实例:

很长时间没用Oracle数据库了&#xff0c;今天在公司的电脑上装了一个Oracle11g&#xff0c;安装完成后&#xff0c;顺便写了个简单的Jdbc连接Oracle的例子&#xff0c;现在记录一下&#xff0c;方便以后查看&#xff1a; 例子很简单&#xff0c;直接上代码&#xff1a; (注意&…