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 ...
随机推荐
- POJ1733 Parity game
题意 Language:Default Parity game Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 13833 Acc ...
- day25 python学习 继承,钻石继承 多态
---恢复内容开始--- 通过一个列子认识父类和子类中,子类的如何实现对父类默认属性调用,同时拥有自己的属性,如何在子类中调用父类的方法,class Ainmal: country='afdas' d ...
- ZH奶酪:Python 中缀表达式转换后缀表达式
实现一个可以处理加减乘数运算的中缀表达式转换后缀表达式的程序: 一个输入中缀表达式inOrder 一个输出池pool 一个缓存栈stack 从前至后逐字读取inOrder 首先看一下不包含括号的: ( ...
- Tensoflw.js - 01 - 安装与入门(中文注释)
Tensoflw.js - 01 - 安装与入门(中文注释) 参考 W3Cschool 文档:https://www.w3cschool.cn/tensorflowjs/ 本文主要翻译一些英文注释,添 ...
- Linux下的Nginx、php、mysql、apache部署
待补充,先搞几个博客链接: https://www.cnblogs.com/Candies/p/8282934.html http://sujianjob.com/2017/12/18/yum%E5% ...
- c#问题(按F1或F2键时触发事件)
this.KeyPreview = true;...private void Form1_KeyDown(object sender, System.Windows.Forms.KeyEventArg ...
- 一组十六进制的字符串每两个转成对应值的byte
/// <summary> /// 一组十六进制的字符串每两个转成对应值的byte,比如4142 会成 AB对应的byte列表 /// </summary> /// <p ...
- Android 禁止系统进入深度休眠
在Linux系统中,wake_lock是一直锁机制,只要有驱动占用这个锁,系统就不会进入深度休眠. 获取此锁的方法有两种: 1.在adb中通过指令获取wake_lock,系统就不会进入深度休眠 ech ...
- GitHub + circleCI 自动构建/自动部署 应用
GitHub + circleCI 自动构建/自动部署, 这里略过了单元测试,以部署 laravel 应用为例子 比起 gitlab + ansible + genkins 操作起来节省了很多硬件资源 ...
- 【jmeter】Jmeter启动GUI界面出错
今天要用Jmeter测试服务器性能,发现GUI界面总是有warning提示: WARNING: Could not open/create prefs root node Software\JavaS ...