自己写的java用jxl导出到excel工具
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工具的更多相关文章
- JAVA利用JXL导出/生成 EXCEL
/** * 导出导出采暖市场部收入.成本.利润明细表 * @author JIA-G-Y */ public String exporExcel(String str) { String str=Se ...
- java利用JXL导出/生成 EXCEL【my】
一.创建一个excel文件 package test;// 生成Excel的类 import java.io.File; import jxl.Workbook;import jxl.write.La ...
- Java中用JXL导出Excel代码详解
jxl是一个韩国人写的java操作excel的工具, 在开源世界中,有两套比较有影响的API可供使用,一个是POI,一个是jExcelAPI.其中功能相对POI比较弱一点.但jExcelAPI对中文支 ...
- JAVA利用JXL导出 EXCEL (在原有的excel模板上把数据导到excel上)
添加依赖 <dependency> <groupId>net.sourceforge.jexcelapi</groupId> <artifactId>j ...
- JAVA利用JXL导出/生成 EXCEL1
/** * 导出导出采暖市场部收入.成本.利润明细表 * @author JIA-G-Y */ public String exporExcel(String str) { String str=Se ...
- JXL 读取 Excel java中jxl导出数据到excel的例子 上传文件
2010-10-14 19:17:06 com.opensymphony.xwork2.util.logging.commons.CommonsLogger info 信息: Entferne Dat ...
- java使用jxl,poi解析excel文件
public interface JavaExcel { /** * 使用jxl写excel文件 */ public void writeJxlExcel(); /** * 使用jxl读excel文件 ...
- java的jxl技术导入Excel
项目结构: http://www.cnblogs.com/hongten/gallery/image/112177.html 在项目中我们看到Reference Libraries中的jxl.jar包 ...
- java 使用jxl poi 操作excel
java操作excel 创建.修改 xls 文件 JAVA操作Excel文件 Java生成和操作Excel文件 java导出Excel通用方法 Java 实现导出excel表 POI Java PO ...
随机推荐
- 织梦5.7 TAG、标题、栏目以及keywords长度字符数限制修改
织梦5.7 TAG.标题.栏目以及keywords长度字符数限制修改[图文] 标签: 织梦关键词长度修改 织梦tag长度修改 织梦标题长度修改 织梦栏目长度限制修改 织梦修改 分类: 技术操作 ...
- steps animation
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- HTML中禁用表单控件的两种方法readonly与disabled
时候我们会希望表单上的控件是不可修改的,比如在修改密码的网页中,显示用户名的文本框就应该是不可修改状态的,下面与大家分享下禁用表中控件的两种方法 在网页的制作过程中,我们会经常使用到表单.但是有时候我 ...
- ThinkPHP 3.2.3 中设置和使用 Session
Session 的配置 可以在 config.php(可以是应用公用的 config.php 或模块的 config.php)中对 Session 进行配置,例如: config.php <?p ...
- Google Chrome浏览器中如何使用命令
Google Chrome浏览器中如何使用命令 | 浏览:2974 | 更新:2014-02-23 23:12 | 标签:chrome 1 2 3 分步阅读 Google Chrome浏览器有很多的特 ...
- linux多核cpu下的负载查看
linux下使用top命令或uptime命令 单核cpu下,负载超过0.7即意味着瓶颈,多核cpu下按核数*0.7计算负载 如2核,1.4可能即意味着负载较吃力了 查看核数 grep 'model n ...
- jQuery获取一般处理程序(ashx)的JSON数据
昨天有在开发的软件生产线生产流程,RFID扫描IC卡的数据,当中有用到jQuery获取一般处理程序(ashx)的JSON数据.今有把它写成一个小例子,望需要的网友能参考. 在网站中,创建一个一般应用程 ...
- 使用CSS将图片转换成黑白(灰色、置灰)z转
小tip: 使用CSS将图片转换成黑白(灰色.置灰) by zhangxinxu from http://www.zhangxinxu.com 本文地址:http://www.zhangxinxu.c ...
- win7下用mklink命令解决delphiXE系列占用C盘空间的问题
DelphiXE从2010以后, 安装程序安装完成后都会在ProgramData目录里复制一份安装程序的备份, 随着版本升级安装包越来越大, 占用C盘的空间也就越来越大 虽然可以通过删除的方式删掉, ...
- gets(),fgets()的作用机制探究
gets(),fgets() scanf("%d",&a)若接受形如 2 这样的输入后,缓冲区内会留一个\n,此后若调用gets等函数时会读出这个换行出现错误,需注意 fg ...