java Export Excel POI 转
最终选择用POI成功导出excel。总之很有用。
http://www.cnblogs.com/xwdreamer/archive/2011/07/20/2296975.html
http://poi.apache.org/download.html
Student.java
package org.leno.export.util;
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();
// TODO Auto-generated constructor stub
}
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;
}
}
ExportExcel.java
package myExcel; import java.awt.List;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
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.*;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.regex.Matcher;
import java.util.regex.Pattern; import javax.mail.Header;
import javax.swing.JOptionPane;
import javax.swing.plaf.synth.Region; import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.formula.functions.T; import classman.class_operation;
import util.stringUtil; public class myExcelExcel<T> {
public void exportExcel(Collection<T> dataset, OutputStream out) {
exportExcel("testPOI", null, dataset, out, "yyyy-MM-dd");
} public void exportExcel(String[] headers, Collection<T> dataset,
OutputStream out) {
exportExcel("testPOI", headers, dataset, out, "yyyy-MM-dd");
} public void exportExcel(String[] headers, Collection<T> dataset,
OutputStream out, String pattern) {
exportExcel("testPOI", headers, dataset, out, pattern); } public void exportExcel(String title, String[] headers,
Collection<T> dataset, OutputStream out, String pattern) {
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet(title);
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("leno"); // 产生表格标题行
HSSFRow row = sheet.createRow(0);
for (short 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 (short i = 0; i < fields.length; i++) {
HSSFCell cell = row.createCell(i);
cell.setCellStyle(style2);
Field field = fields[i];
String fileName = field.getName();
String getMethodName = "get"
+ fileName.substring(0, 1).toUpperCase()
+ fileName.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[]) { } else {
textValue=value.toString(); }
System.out.println(textValue);
if (textValue != null) {
Pattern p = Pattern.compile("^//d+(//.//d+)?$");
Matcher matcher = p.matcher(textValue);
if (matcher.matches()) {
cell.setCellValue(Double.parseDouble(textValue));
} else {
HSSFRichTextString richTextString = new HSSFRichTextString(
textValue);
HSSFFont font3 = workbook.createFont();
font3.setColor(HSSFColor.BLUE.index);
richTextString.applyFont(font3);
cell.setCellValue(richTextString);
}
} } catch (SecurityException e) {
// TODO: handle exception
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO: handle exception
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO: handle exception
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO: handle exception
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO: handle exception
e.printStackTrace();
} finally {
// 清理资源
}
}
} try {
workbook.write(out); } catch (IOException e) {
// TODO: handle exception
e.printStackTrace();
}
} public void testMain() { String[] headers = { "学号", "姓名", "年龄", "性别", "出生日期" };
myExcelExcel<Student> ex=new myExcelExcel<Student>();
java.util.List<Student> dataset = new ArrayList<Student>();
dataset.add(new Student(100001, "aa", 20, true, new java.util.Date()));
dataset.add(new Student(2002, "bbb", 24, false, new java.util.Date()));
dataset.add(new Student(3003, "ccc", 22, true, new java.util.Date()));
try { OutputStream out = new FileOutputStream("c://a.xls");
ex.exportExcel(headers, dataset,out);
out.close();
JOptionPane.showMessageDialog(null, "export OK!");
System.out.println("export OK");
} catch (FileNotFoundException e) {
e.printStackTrace();
// TODO: handle exception
}
catch (IOException e) {
e.printStackTrace();
// TODO: handle exception
} }
}
这样写完已经可以导出了。
明天弄一个导出到浏览器客户端电脑上的功能。
写了个Servlet,果然在客户端用浏览器可以导出了。
Servlet
package brda; import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; public class ExportSvlt extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//File file = new File(getServletContext().getRealPath(""));
response.setContentType("octets/stream");
response.addHeader("Content-Disposition",
"attachment;filename=test.xls"); String[] headers = { "学号", "姓名", "年龄", "性别", "出生日期" };
brdaExcel<Student> ex=new brdaExcel<Student>();
java.util.List<Student> dataset = new ArrayList<Student>();
dataset.add(new Student(100001, "aa", 20, true, new java.util.Date()));
dataset.add(new Student(2002, "bbb", 24, false, new java.util.Date()));
dataset.add(new Student(3003, "ccc", 22, true, new java.util.Date())); OutputStream out = response.getOutputStream();
ex.exportExcel(headers, dataset, out);
out.close();
System.out.println("excel Export success!");
}
public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException {
doGet(request, response);
} }
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="ExportSvlt" method="post">
<input type="submit" value="ExportExcel">
</form>
</body>
</html>
java Export Excel POI 转的更多相关文章
- Java操作Excel: POI不能创建xlsm问题的方法(源自StackOverFlow)
write to xlsm (Excel 2007) using apache poi POI的下载(记得把其中的jar包全部加到工程里哦)http://mirror.bit.edu.cn/apach ...
- java 读取excel poi 和cell 方法
http://poi.apache.org/spreadsheet/quick-guide.html http://www.aspose.com/docs/display/cellsjava/Eval ...
- Java开发Excel POI getPhysicalNumberOfCells 与 getLastCellNum的区别
1.getPhysicalNumberOfCells 与 getLastCellNum的区别 用org.apache.poi的包做excel导入,无意间发明若是excel文件中有空列,空列后面的数据全 ...
- java 通过Apache poi导出excel代码demo实例
package com.zuidaima.excel.util; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutput ...
- 使用JAVA导出EXCEL表格(POI)
一.POI概述 Jakarta POI 是一套用于访问微软格式文档的Java API.POI提供API给Java程序对Microsoft Office格式档案读和写的功能.在许多企业办公系统中,经常会 ...
- java中使用poi导入导出excel文件_并自定义日期格式
Apache POI项目的使命是创造和保持java API操纵各种文件格式基于Office Open XML标准(OOXML)和微软的OLE复合文档格式(OLE2)2.总之,你可以读写Excel文件使 ...
- java写入excel文件poi
java写入excel文件 java写入excel文件poi,支持xlsx与xls,没有文件自动创建 package com.utils; import java.io.File; import ja ...
- Read / Write Excel file in Java using Apache POI
Read / Write Excel file in Java using Apache POI 2014-04-18 BY DINESH LEAVE A COMMENT About a year o ...
- java使用Apache POI操作excel文件
官方介绍 HSSF is the POI Project's pure Java implementation of the Excel '97(-2007) file format. XSSF is ...
随机推荐
- 【spring源码分析】spring AspectJ的Execution表达式
在使用spring框架配置AOP的时候,不管是通过XML配置文件还是注解的方式都需要定义pointcut"切入点" 例如定义切入点表达式 execution (* com.sam ...
- window.open()与window.showModalDialog
弹出窗口两种方式: 1.window.showModalDialog: var feature = "dialogWidth:615px;dialogHeight:505px ...
- 如何生成SPFILE文件
1.spfile是Oracle9i之后引入的,目的是提高系统安全性.在Oracle8i下初始化参数文件为文本文件,可以使用文本编辑器进行编辑,当需要修改初始化参数时,需要在init.ora文件中修改, ...
- 在浏览器中输入一个URL后都发生了什么
这道题目没有所谓的完全的正确答案,这个题目可以让你在任意的一个点深入下去, 只要你对这个点是熟悉的.以下是一个大概流程: 浏览器向DNS服务器查找输入URL对应的IP地址. DNS服务器返回网站的IP ...
- gitlab安装教程、gitlab官网、英文文档
gitlab官网 https://about.gitlab.com/ gitlab安装和官网英文文档 https://about.gitlab.com/downloads/ 清华大学tuna镜像源 G ...
- 温习《PHP 核心技术与最佳实践》这本书
再次看这本书,顺手提炼了一下大致目录,以便后续看见目录就知道大概讲的些什么内容 PHP 核心技术与最佳实践 1.面向对象思想的核心概念 1.1 面向对象的『形』与『本』 1.2 魔术方法的应用 1.2 ...
- [转]Nginx负载均衡原理初解
什么是负载均衡 我们知道单台服务器的性能是有上限的,当流量很大时,就需要使用多台服务器来共同提供服务,这就是所谓的集群. 负载均衡服务器,就是用来把经过它的流量,按照某种方法,分配到集群中的各台服务器 ...
- Oracle查看及修改Oracle最大连接数
Oracle查看及修改Oracle最大连接数 .查询oracle的最大连接数: select * from v$parameter where name='processes'; .oracle 11 ...
- 终于完成了 源码 编译lnmp环境
经过了大概一个星期的努力,终于按照海生的编译流程将lnmp环境源码安装出来了 nginx 和php 主要参考 http://hessian.cn/p/1273.html mysql 主要参考 http ...
- php 生成.csv的文件
$data = array( "title" => array("服务器", "链接", "对应ID"), &qu ...