package com;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List; import javax.servlet.http.HttpServletResponse; import jxl.Workbook;
import jxl.WorkbookSettings;
import jxl.format.Alignment;
import jxl.format.Border;
import jxl.format.BorderLineStyle;
import jxl.format.Colour;
import jxl.format.UnderlineStyle;
import jxl.write.Label;
import jxl.write.Number;
import jxl.write.WritableCell;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableFont.FontName;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException; public class ExcelUtil {
private static String defaultEncoding = "gbk"; /**
* 1创建工作簿,用于response的输出流返回
* @param response HttpServletResponse
* @param fileName 文件名
* @return
*/
public static WritableWorkbook createWorkBook(HttpServletResponse response,String fileName){ OutputStream os = null;
BufferedOutputStream bos = null;
WritableWorkbook wwb = null;
try {
os = response.getOutputStream();
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment; filename=".concat(fileName)); bos = new BufferedOutputStream(os);
wwb = createWorkBook(bos); } catch (IOException e) {
e.printStackTrace();
} finally{
try {
if(bos!=null){
bos.flush();
bos.close();
bos = null;
}
if(os!=null){
os.close();
os = null;
}
} catch (IOException e) {
e.printStackTrace();
}
} return wwb;
} /**
* 1创建工作簿,用于导出文件到某个路径
* @param exportPath
* @return
*/
public static WritableWorkbook createWorkBook(String exportPath){
File file = new File(exportPath);
if(!file.exists()||file.isDirectory()){
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
} WritableWorkbook wwb = createWorkBook(file);
return wwb;
} /**
* 创建WritableWorkbook
* @param obj
* @return
*/
private static WritableWorkbook createWorkBook(Object obj){
if(obj==null){
return null;
} System.out.println("创建工作簿WritableWorkbook开始..."); WorkbookSettings setting = new WorkbookSettings();
setting.setEncoding(defaultEncoding); WritableWorkbook wwb = null;
try { if(obj instanceof File){
File file = (File)obj;
wwb = Workbook.createWorkbook(file,setting);
}else if(obj instanceof BufferedOutputStream){
BufferedOutputStream bos = (BufferedOutputStream)obj;
wwb = Workbook.createWorkbook(bos,setting);
} } catch (IOException e) {
e.printStackTrace();
} System.out.println("创建工作簿WritableWorkbook结束..."); return wwb;
} /**
* 根据SheetNames数量创建对应数量的sheet
* @param sheetNames
* @param wwb
* @return
*/
public static List<WritableSheet> createSheet(String[] sheetNames,WritableWorkbook wwb){
if(sheetNames==null||sheetNames.length==0){
return null;
}
if(wwb==null){
return null;
}
int sheetNum = sheetNames.length;
System.out.println("Excel创建sheet数量:"+sheetNum); List<WritableSheet> list = new ArrayList<WritableSheet>(sheetNum); for(int i= 0; i<sheetNum ; i++){
WritableSheet ws = wwb.createSheet(sheetNames[i], i);
list.add(ws);
} return list; } /**
* 创建title格式
* @return
*/
public static WritableCellFormat getTitleFormat(){ System.out.println("创建title格式..."); FontName fontName = WritableFont.createFont("宋体");
int fontSize = 15;
boolean isItalic = false;//是否斜体 //参数依次是:字体设置/字体大小/字体粗细/是否是斜体/下划线类型/颜色
WritableFont titleFont = new WritableFont(fontName, fontSize, WritableFont.BOLD, isItalic, UnderlineStyle.NO_UNDERLINE, Colour.BLACK);
WritableCellFormat titleFormat = new WritableCellFormat(titleFont); return titleFormat;
} /**
* 获取内容格式
* @return
*/
public static WritableCellFormat getContentFormat(){ System.out.println("创建内容格式..."); WritableCellFormat contentFormat = new WritableCellFormat();
try {
contentFormat.setWrap(true);//是否换行
contentFormat.setBorder(Border.ALL, BorderLineStyle.THIN, Colour.BLACK);//全框/细线/黑色
contentFormat.setAlignment(Alignment.LEFT);//水平居左
} catch (WriteException e) {
e.printStackTrace();
} return contentFormat;
} /**
* 单元格插入内容
* @param sheet 表单对象
* @param columnIndex 列
* @param rowIndex 行
* @param content 内容
* @param format 格式
*/
public static void addCell(WritableSheet sheet,int columnIndex,int rowIndex,Object content,WritableCellFormat format){ WritableCell cell = null; if(content instanceof Double){
if(format!=null){
cell = new Number(columnIndex, rowIndex, (Double)content, format);
}else{
cell = new Number(columnIndex, rowIndex, (Double)content);
} }else{
if(content==null){
content = "";
}
if(format!=null){
cell = new Label(columnIndex, rowIndex, (String)content, format);
}else{
cell = new Label(columnIndex, rowIndex, (String)content);
}
} try {
sheet.addCell(cell);
} catch (RowsExceededException e) {
e.printStackTrace();
} catch (WriteException e) {
e.printStackTrace();
}
} /**
* 解析一个list对象插入到sheet
* @param sheet
* @param list
* @param titles 列名 空列填""
* @param clazzFields class类的属性名:"getXXX"格式 空列填""
*/
public static void parseClass(WritableSheet sheet,List list,String[] titles,String[] clazzFields){
if(sheet==null||list==null||titles==null||clazzFields==null){
return;
} WritableCellFormat format = getContentFormat(); int rowIndex = 1;//默认第一行还有个大标题~,如果不需要那个大标题,此处改成0
//先将列名插入sheet
for(int columnIndex=0;columnIndex<titles.length;columnIndex++){
addCell(sheet, columnIndex, rowIndex, titles[columnIndex], format);
} rowIndex++; System.out.println("遍历传入的list对象,并写入sheet表单开始...");
for(int i=0;i<list.size();i++){ int startColumn = 0;
if("序号".equals(titles[0])){
addCell(sheet, startColumn, rowIndex, (i+1)+"", format);
startColumn++;
}
Object obj = list.get(i);
//将传入的clazzFields从clazz取出来
for(int columnIndex=startColumn;columnIndex<clazzFields.length;columnIndex++){ if("".equals(clazzFields[columnIndex])){//如果属性没写,默认填一空行
addCell(sheet, columnIndex, rowIndex, "", format);
continue;
} //属性不为空,反射出类的属性,取值
try {
Method method = obj.getClass().getDeclaredMethod(clazzFields[columnIndex], null);
Object field = method.invoke(obj, null);
// Class returnType = method.getReturnType();
addCell(sheet, columnIndex, rowIndex, field, format); } 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();
}
} rowIndex++;
} System.out.println("遍历传入的list对象,并写入sheet表单结束..."); } public static void main(String[] args) {
//模拟数据
List<TestClass> testList = new ArrayList<TestClass>();
double num = 1000d;
for(int i=0;i<6;i++){
TestClass t = new TestClass();
t.setA("testA"+i);
t.setB("testB"+i);
t.setC(num-i); testList.add(t);
} //导出开始
WritableWorkbook wwb = null;
try {
wwb = createWorkBook("D:\\测试1121.xls");
String[] names = {"张三","李四"};
List<WritableSheet> sheets = createSheet(names, wwb); WritableCellFormat titleFormat = getTitleFormat();
WritableCellFormat contentFormat = getContentFormat(); for(WritableSheet sheet :sheets){ addCell(sheet, 0, 0, "大标题123123654654", titleFormat); String[] titles = {"序号","","A","C","B"};
String[] methods = {"","","getA","getC","getB"};
parseClass(sheet, testList, titles, methods); addCell(sheet, 3, testList.size()+3, "审核:", null); } wwb.write();
} catch (IOException e) {
e.printStackTrace();
} finally{
if(wwb!=null){
try {
wwb.close();
wwb = null;
} catch (WriteException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} }
//结束 }
}

测试类:

package com;

public class TestClass {
private String a;
private String b;
private Double c; public TestClass(){ } public String getA() {
return a;
} public void setA(String a) {
this.a = a;
} public String getB() {
return b;
} public void setB(String b) {
this.b = b;
} public Double getC() {
return c;
} public void setC(Double c) {
this.c = c;
} }

自己写的java用jxl导出到excel工具的更多相关文章

  1. JAVA利用JXL导出/生成 EXCEL

    /** * 导出导出采暖市场部收入.成本.利润明细表 * @author JIA-G-Y */ public String exporExcel(String str) { String str=Se ...

  2. java利用JXL导出/生成 EXCEL【my】

    一.创建一个excel文件 package test;// 生成Excel的类 import java.io.File; import jxl.Workbook;import jxl.write.La ...

  3. Java中用JXL导出Excel代码详解

    jxl是一个韩国人写的java操作excel的工具, 在开源世界中,有两套比较有影响的API可供使用,一个是POI,一个是jExcelAPI.其中功能相对POI比较弱一点.但jExcelAPI对中文支 ...

  4. JAVA利用JXL导出 EXCEL (在原有的excel模板上把数据导到excel上)

    添加依赖 <dependency> <groupId>net.sourceforge.jexcelapi</groupId> <artifactId>j ...

  5. JAVA利用JXL导出/生成 EXCEL1

    /** * 导出导出采暖市场部收入.成本.利润明细表 * @author JIA-G-Y */ public String exporExcel(String str) { String str=Se ...

  6. JXL 读取 Excel java中jxl导出数据到excel的例子 上传文件

    2010-10-14 19:17:06 com.opensymphony.xwork2.util.logging.commons.CommonsLogger info 信息: Entferne Dat ...

  7. java使用jxl,poi解析excel文件

    public interface JavaExcel { /** * 使用jxl写excel文件 */ public void writeJxlExcel(); /** * 使用jxl读excel文件 ...

  8. java的jxl技术导入Excel

    项目结构: http://www.cnblogs.com/hongten/gallery/image/112177.html 在项目中我们看到Reference Libraries中的jxl.jar包 ...

  9. java 使用jxl poi 操作excel

    java操作excel  创建.修改 xls 文件 JAVA操作Excel文件 Java生成和操作Excel文件 java导出Excel通用方法 Java 实现导出excel表 POI Java PO ...

随机推荐

  1. bzoj3991: [SDOI2015]寻宝游戏--DFS序+LCA+set动态维护

    之前貌似在hdu还是poj上写过这道题. #include<stdio.h> #include<string.h> #include<algorithm> #inc ...

  2. div自定义的滚动条 (竖直导航条)

    <style type="text/css"> .scrollBar { width: 10px; background-color: #daa520; positio ...

  3. mysql view(视图)

    一,什么是视图 视图是存放数据的一个接口,也可以说是虚拟的表.这些数据可以是从一个或几个基本表(或视图)的数据.也可以是用户自已定义的数据.其实视图里面不存放数据的,数据还是放在基本表里面,基本表里面 ...

  4. WxInput模块则比较彻底的解决了这个问题

    基于wxpython的GUI输入对话框2 在程序输入中,有时会要求同时改变多个参数值,而且类型也不尽相同, 这时TextEntryDialog就显得不适用了.WxInput模块则比较彻底的解决了这个问 ...

  5. java编程思想恶心的enum状态机示例

    下面是一个包装输入的类 package test; import java.util.Random; public enum Input { NICKEL(5) , DIME(10) , QUARTE ...

  6. BizTalk动手实验(九)业务规则引擎使用

    1 课程简介 通过本课程熟悉业务规则引擎(BRE)的使用(本环境为Windows 2008 32位操作系统环境 + Visual Studio 2010 + BizTalk 210) 2 准备工作 1 ...

  7. js官网判断是否手机跳转到手机页面

    <script src="http://siteapp.baidu.com/static/webappservice/uaredirect.js" type="te ...

  8. centos桌面使用

    firefox添加flash插件 [root@bogon home]# cp libflashplayer.so /usr/lib64/mozilla/pl pl plugins/ plugins-w ...

  9. GFS文件系统和在RedHat Linux下的配置

    GFS的全称是Google file System,为了满足Google迅速增长的数据处理要求,Google设计并实现的Google文件系统(GFS).Google文件系统是一个可扩展的分布式文件系统 ...

  10. 并发队列ConcurrentLinkedQueue和阻塞队列LinkedBlockingQueue用法

    在Java多线程应用中,队列的使用率很高,多数生产消费模型的首选数据结构就是队列(先进先出).Java提供的线程安全的Queue可以分为阻塞队列和非阻塞队列,其中阻塞队列的典型例子是BlockingQ ...