最终选择用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 转的更多相关文章

  1. Java操作Excel: POI不能创建xlsm问题的方法(源自StackOverFlow)

    write to xlsm (Excel 2007) using apache poi POI的下载(记得把其中的jar包全部加到工程里哦)http://mirror.bit.edu.cn/apach ...

  2. java 读取excel poi 和cell 方法

    http://poi.apache.org/spreadsheet/quick-guide.html http://www.aspose.com/docs/display/cellsjava/Eval ...

  3. Java开发Excel POI getPhysicalNumberOfCells 与 getLastCellNum的区别

    1.getPhysicalNumberOfCells 与 getLastCellNum的区别 用org.apache.poi的包做excel导入,无意间发明若是excel文件中有空列,空列后面的数据全 ...

  4. java 通过Apache poi导出excel代码demo实例

    package com.zuidaima.excel.util; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutput ...

  5. 使用JAVA导出EXCEL表格(POI)

    一.POI概述 Jakarta POI 是一套用于访问微软格式文档的Java API.POI提供API给Java程序对Microsoft Office格式档案读和写的功能.在许多企业办公系统中,经常会 ...

  6. java中使用poi导入导出excel文件_并自定义日期格式

    Apache POI项目的使命是创造和保持java API操纵各种文件格式基于Office Open XML标准(OOXML)和微软的OLE复合文档格式(OLE2)2.总之,你可以读写Excel文件使 ...

  7. java写入excel文件poi

    java写入excel文件 java写入excel文件poi,支持xlsx与xls,没有文件自动创建 package com.utils; import java.io.File; import ja ...

  8. 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 ...

  9. java使用Apache POI操作excel文件

    官方介绍 HSSF is the POI Project's pure Java implementation of the Excel '97(-2007) file format. XSSF is ...

随机推荐

  1. 几本不错的graphql 电子书

    当前专门讲graphql 的数据不是很多,但是越来越多的graphql 项目的出现以及graphql 自身的 便捷,老外已经有人去写graphql 的设计以及基本使用了. ebooks 地址 http ...

  2. Oracle 10g RAC OCR 和 VotingDisk 的备份与恢复

    Oracle RAC 中OCR 和Voting Disk 备份在我的blog: Oracle RAC 常用维护工具和命令 中已经有说明,现在再次把它单独拿出做一个说明, 因为OCR 和Voting D ...

  3. springboot 知识点

    ---恢复内容开始--- 1springBoot项目引入方式, 1,继承自父 project (需要没有付项目才能用,一般我们的项目都会有 父 项目 所以 这种方式不推荐 ,记住有这种方式 就可以了) ...

  4. 阿里巴巴Java开发手册-并发处理

    1. [强制]获取单例对象需要保证线程安全,其中的方法也要保证线程安全.说明:资源驱动类.工具类.单例工厂类都需要注意. 2. [强制]创建线程或线程池时请指定有意义的线程名称,方便出错时回溯.正例: ...

  5. html 子元素和父元素都监听了 click 事件,点击子元素时为何先触发的是父元素的 click 事件?

    先上一段代码,点击子元素时先触发的是父元素的 click 事件 <html> <head> <script type="text/javascript" ...

  6. json格式字符串处理

    public class InternalClass         {             public int MID;             public string Name;     ...

  7. webSocket支持的浏览器

  8. fckeditor 配置

    因为下载下来的压缩包里面有包含很多在我们使用时,用不到的,不删除也行.看个人喜好下面以PHP为例,进行程序瘦身 删除所有”_”开头的文件和文件夹   删除FCKeditor的目录下:   fckedi ...

  9. RegExp实例

    ECMAScript通过RegExp类型来支持正则表达式,常见的正则表达式为:var expression = /pattern / flags;其中的模式(pattern)部分可以使任何简单或复杂的 ...

  10. ASP.NET Web Pages:页面布局

    ylbtech-.Net-ASP.NET Web Pages:页面布局 1.返回顶部 1. ASP.NET Web Pages - 页面布局 通过 Web Pages ,创建一个布局一致的网站是很容易 ...