java中常用的工具类(三)_java中常用的工具类(三)

packagecom.itjh.javaUtil;

importjava.sql.Connection;

importjava.sql.DriverManager;

importjava.sql.PreparedStatement;

importjava.sql.ResultSet;

importjava.sql.ResultSetMetaData;

importjava.sql.SQLException;

importjava.util.ArrayList;

importjava.util.Collections;

importjava.util.HashMap;

importjava.util.List;

importjava.util.Map;

importorg.apache.commons.dbcp.ConnectionFactory;

importorg.apache.commons.dbcp.DriverManagerConnectionFactory;

importorg.apache.commons.dbcp.PoolableConnectionFactory;

importorg.apache.commons.dbcp.PoolingDriver;

importorg.apache.commons.dbutils.DbUtils;

importorg.apache.commons.dbutils.QueryRunner;

importorg.apache.commons.dbutils.handlers.MapListHandler;

importorg.apache.commons.pool.ObjectPool;

importorg.apache.commons.pool.impl.GenericObjectPool;

/**

* 连接数据库的综合类。

* 依赖jar包:commons.dbcp-1.4,commons.dbutils-1.3,commons.pool-1.5.4包。

*

* @author 宋立君

* @date 2014年07月03日

*/

publicclassDBUtil{

privateStringdri=null;

privateStringurl=null;

privateStringusername=null;

privateStringpassword=null;

privateStringpoolName=null;// 连接池名称

privateObjectPool connectionPool=null;// 连接池

// 对应的定时查询类

privateQueryThread queryThread=null;

/**

* 功能:构造函数

*

* @author 宋立君

* @date 2014年07月03日

* @param dri

*            驱动全类名,例如:com.mysql.jdbc.Driver。

* @param url

*            数据库url连接,例如:

*            "jdbc:mysql://127.0.0.1:3306/test?autoReconnect=true&useUnicode=true&characterEncoding=UTF-8"

* @param userName

*            数据库用户名,例如:root

* @param password

*            数据库密码,例如:abc

* @param poolName

*            创建的数据库连接池的名称,例如mypool,注意一个web容器此名称不能重复。

*/

publicDBUtil(Stringdri,Stringurl,StringuserName,Stringpassword,

StringpoolName){

this.dri=dri;

this.url=url;

this.username=userName;

this.password=password;

this.poolName=poolName;

}

/**

* 执行sql。

*

* @param conn

*            连接

* @param pstm

*            PreparedStatement

* @return int 执行sql对应的影响行。

* @throws SQLException

* @author 宋立君

* @date 2014年07月03日

*/

publicintexecute(Connection conn,PreparedStatement pstm)

throwsSQLException{

try{

returnpstm.executeUpdate();

}finally{

Close(conn);

}

}

/**

* 查询sql。

*

* @param conn

*            连接

* @param pstm

*            PreparedStatement

* @return List> 查询的结果集

* @throws SQLException

* @author 宋立君

* @date 2014年07月03日

*/

publicList>query(Connection conn,

PreparedStatement pstm)throwsSQLException{

try{

returnresultSetToList(pstm.executeQuery());

}finally{

Close(conn);

}

}

/**

* 功能:ResultSet 转为List>

*

*

* @param rs

*            ResultSet 原始数据集

* @return List>

* @throws java.sql.SQLException

* @author 宋立君

* @date 2014年07月03日

*/

privateList>resultSetToList(ResultSet rs)

throwsjava.sql.SQLException{

if(rs==null)

returnCollections.EMPTY_LIST;

ResultSetMetaData md=rs.getMetaData();// 得到结果集(rs)的结构信息,比如字段数、字段名等

intcolumnCount=md.getColumnCount();// 返回此 ResultSet 对象中的列数

List>list=newArrayList>();

MaprowData=newHashMap();

while(rs.next()){

rowData=newHashMap(columnCount);

for(inti=1;i<=columnCount;i++){

rowData.put(md.getColumnName(i),rs.getObject(i));

}

list.add(rowData);

}

returnlist;

}

/**

* 查询sql语句。

*

* @param sql

*            被执行的sql语句

* @return List>

* @throws SQLException

* @author 宋立君

* @date 2014年07月03日

*/

publicList>query(Stringsql)throwsSQLException{

List>results=null;

Connection conn=null;

try{

conn=getConnection();

QueryRunner qr=newQueryRunner();

results=qr.query(conn,sql,newMapListHandler());

}finally{

Close(conn);

}

returnresults;

}

/**

* 根据参数查询sql语句

*

* @param sql

*            sql语句

* @param param

*            参数

* @return List>

* @throws SQLException

* @author 宋立君

* @date 2014年07月03日

*/

publicList>query(Stringsql,Objectparam)

throwsSQLException{

List>results=null;

Connection conn=null;

try{

conn=getConnection();

QueryRunner qr=newQueryRunner();

results=(List>)qr.query(conn,sql,param,

newMapListHandler());

}catch(SQLExceptione){

e.printStackTrace();

}finally{

Close(conn);

}

returnresults;

}

/**

* 执行sql语句

*

* @param sql

*            被执行的sql语句

* @return 受影响的行

* @throws Exception

* @author 宋立君

* @date 2014年07月03日

*/

publicintexecute(Stringsql)throwsException{

Connection conn=getConnection();

introws=0;

try{

QueryRunner qr=newQueryRunner();

rows=qr.update(conn,sql);

}finally{

Close(conn);

}

returnrows;

}

/**

* 执行含参数的sql语句

*

* @param sql

*            被执行的sql语句

* @param params

*            参数

* @return 返回受影响的行

* @throws Exception

* @author 宋立君

* @date 2014年07月03日

*/

publicintexecute(Stringsql,Object[]params)throwsException{

Connection conn=getConnection();

introws=0;

try{

QueryRunner qr=newQueryRunner();

rows=qr.update(conn,sql,params);

}finally{

Close(conn);

}

returnrows;

}

/**

* 关闭连接

*

* @param conn

* @throws SQLException

* @author 宋立君

* @date 2014年07月03日

*/

publicvoidClose(Connection conn)throwsSQLException{

if(conn!=null){

conn.close();

}

DbUtils.closeQuietly(conn);

}

/**

* 启动连接池

*

* @author 宋立君

* @date 2014年07月03日

*/

privatevoidStartPool(){

try{

Class.forName(dri);

}catch(ClassNotFoundException e1){

e1.printStackTrace();

}

if(connectionPool!=null){

ShutdownPool();

}

try{

connectionPool=newGenericObjectPool(null);

ConnectionFactory connectionFactory=newDriverManagerConnectionFactory(

url,username,password);

PoolableConnectionFactory poolableConnectionFactory=newPoolableConnectionFactory(

connectionFactory,connectionPool,null,"SELECT 1",false,

true);

Class.forName("org.apache.commons.dbcp.PoolingDriver");

PoolingDriver driver=(PoolingDriver)DriverManager

.getDriver("jdbc:apache:commons:dbcp:");

driver.registerPool(poolName,poolableConnectionFactory.getPool());

}catch(Exceptione){

e.printStackTrace();

}

// 开启查询程序

queryThread=newQueryThread(this);

queryThread.start();

}

/**

* 关闭连接池

*

* @author 宋立君

* @date 2014年07月03日

*/

privatevoidShutdownPool(){

try{

PoolingDriver driver=(PoolingDriver)DriverManager

.getDriver("jdbc:apache:commons:dbcp:");

driver.closePool(poolName);

// 关闭定时查询

queryThread.setStartQuery(false);

}catch(SQLExceptione){

e.printStackTrace();

}

}

/**

* 得到一个连接

*

* @return

* @author 宋立君

* @date 2014年07月03日

*/

publicsynchronizedConnection getConnection(){

Connection conn=null;

try{

if(connectionPool==null)

StartPool();

conn=DriverManager.getConnection("jdbc:apache:commons:dbcp:"

+poolName);

}catch(Exceptione){

e.printStackTrace();

}

returnconn;

}

}

/**

* 当连接池启动后会自动定时查询数据库,防止数据库连接超时。

*

* @author 宋立君

* @date 2014年07月03日

*/

classQueryThreadextendsThread{

privateDBUtil dbUtil=null;

// 是否开启查询

privatebooleanstartQuery=true;

/**

* 功能:对应的数据库连接。

*

* @author 宋立君

* @date 2014年07月03日

* @param dbUtil

*            数据库连接

*/

publicQueryThread(DBUtil dbUtil){

this.dbUtil=dbUtil;

}

publicvoidrun(){

while(true){

try{

if(startQuery){

this.dbUtil.query("select 1");

}

// System.out.println(startQuery+"   123");

}catch(Exceptione){

e.printStackTrace();

}finally{

try{

Thread.sleep(120000);

}catch(InterruptedExceptione){

e.printStackTrace();

}

}

}

}

publicvoidsetStartQuery(booleanstartQuery){

// System.out.println("startQuery shut:"+startQuery);

this.startQuery=startQuery;

}

}

依赖的jar

commons.dbcp-1.4,commons.dbutils-1.3,commons.pool-1.5.4包

二、DES加密和解密

DESUtil.java

packagecom.itjh.javaUtil;

importjava.io.UnsupportedEncodingException;

importjava.security.InvalidKeyException;

importjava.security.NoSuchAlgorithmException;

importjava.security.SecureRandom;

importjava.security.spec.InvalidKeySpecException;

importjavax.crypto.BadPaddingException;

importjavax.crypto.Cipher;

importjavax.crypto.IllegalBlockSizeException;

importjavax.crypto.KeyGenerator;

importjavax.crypto.NoSuchPaddingException;

importjavax.crypto.SecretKey;

importjavax.crypto.SecretKeyFactory;

importjavax.crypto.spec.DESKeySpec;

/**

* DES加密和解密。

*

* @author 宋立君

* @date 2014年07月03日

*/

publicclassDESUtil{

/** 安全密钥 */

privateStringkeyData="ABCDEFGHIJKLMNOPQRSTWXYZabcdefghijklmnopqrstwxyz0123456789-_.";

/**

* 功能:构造

*

* @author 宋立君

* @date 2014年07月03日

*/

publicDESUtil(){

}

/**

* 功能:构造

*

* @author 宋立君

* @date 2014年07月03日

* @param keyData

*            key

*/

publicDESUtil(Stringkey){

this.keyData=key;

}

/**

* 功能:加密 (UTF-8)

*

* @author 宋立君

* @date 2014年07月03日

* @param source

*            源字符串

* @param charSet

*            编码

* @return String

* @throws UnsupportedEncodingException

*             编码异常

*/

publicStringencrypt(Stringsource)throwsUnsupportedEncodingException{

returnencrypt(source,"UTF-8");

}

/**

*

* 功能:解密 (UTF-8)

*

* @author 宋立君

* @date 2014年07月03日

* @param encryptedData

*            被加密后的字符串

* @return String

* @throws UnsupportedEncodingException

*             编码异常

*/

publicStringdecrypt(StringencryptedData)

throwsUnsupportedEncodingException{

returndecrypt(encryptedData,"UTF-8");

}

/**

* 功能:加密

*

* @author 宋立君

* @date 2014年07月03日

* @param source

*            源字符串

* @param charSet

*            编码

* @return String

* @throws UnsupportedEncodingException

*             编码异常

*/

publicStringencrypt(Stringsource,StringcharSet)

throwsUnsupportedEncodingException{

Stringencrypt=null;

byte[]ret=encrypt(source.getBytes(charSet));

encrypt=newString(Base64.encode(ret));

returnencrypt;

}

/**

*

* 功能:解密

*

* @author 宋立君

* @date 2014年07月03日

* @param encryptedData

*            被加密后的字符串

* @param charSet

*            编码

* @return String

* @throws UnsupportedEncodingException

*             编码异常

*/

publicStringdecrypt(StringencryptedData,StringcharSet)

throwsUnsupportedEncodingException{

StringdescryptedData=null;

byte[]ret=descrypt(Base64.decode(encryptedData.toCharArray()));

descryptedData=newString(ret,charSet);

returndescryptedData;

}

/**

* 加密数据 用生成的密钥加密原始数据

*

* @param primaryData

*            原始数据

* @return byte[]

* @author 宋立君

* @date 2014年07月03日

*/

privatebyte[]encrypt(byte[]primaryData){

/** 取得安全密钥 */

byterawKeyData[]=getKey();

/** DES算法要求有一个可信任的随机数源 */

SecureRandom sr=newSecureRandom();

/** 使用原始密钥数据创建DESKeySpec对象 */

DESKeySpec dks=null;

try{

dks=newDESKeySpec(keyData.getBytes());

}catch(InvalidKeyExceptione){

e.printStackTrace();

}

/** 创建一个密钥工厂 */

SecretKeyFactory keyFactory=null;

try{

keyFactory=SecretKeyFactory.getInstance("DES");

}catch(NoSuchAlgorithmExceptione){

e.printStackTrace();

}

/** 用密钥工厂把DESKeySpec转换成一个SecretKey对象 */

SecretKey key=null;

try{

key=keyFactory.generateSecret(dks);

}catch(InvalidKeySpecExceptione){

e.printStackTrace();

}

/** Cipher对象实际完成加密操作 */

Cipher cipher=null;

try{

cipher=Cipher.getInstance("DES");

}catch(NoSuchAlgorithmExceptione){

e.printStackTrace();

}catch(NoSuchPaddingExceptione){

e.printStackTrace();

}

/** 用密钥初始化Cipher对象 */

try{

cipher.init(Cipher.ENCRYPT_MODE,key,sr);

}catch(InvalidKeyExceptione){

e.printStackTrace();

}

/** 正式执行加密操作 */

byteencryptedData[]=null;

try{

encryptedData=cipher.doFinal(primaryData);

}catch(IllegalStateExceptione){

e.printStackTrace();

}catch(IllegalBlockSizeExceptione){

e.printStackTrace();

}catch(BadPaddingExceptione){

e.printStackTrace();

}

/** 返回加密数据 */

returnencryptedData;

}

/**

* 用密钥解密数据

*

* @param encryptedData

*            加密后的数据

* @return byte[]

* @author 宋立君

* @date 2014年07月03日

*/

privatebyte[]descrypt(byte[]encryptedData){

/** DES算法要求有一个可信任的随机数源 */

SecureRandom sr=newSecureRandom();

/** 取得安全密钥 */

byterawKeyData[]=getKey();

/** 使用原始密钥数据创建DESKeySpec对象 */

DESKeySpec dks=null;

try{

dks=newDESKeySpec(keyData.getBytes());

}catch(InvalidKeyExceptione){

e.printStackTrace();

}

/** 创建一个密钥工厂 */

SecretKeyFactory keyFactory=null;

try{

keyFactory=SecretKeyFactory.getInstance("DES");

}catch(NoSuchAlgorithmExceptione){

e.printStackTrace();

}

/** 用密钥工厂把DESKeySpec转换成一个SecretKey对象 */

SecretKey key=null;

try{

key=keyFactory.generateSecret(dks);

}catch(InvalidKeySpecExceptione){

e.printStackTrace();

}

/** Cipher对象实际完成加密操作 */

Cipher cipher=null;

try{

cipher=Cipher.getInstance("DES");

}catch(NoSuchAlgorithmExceptione){

e.printStackTrace();

}catch(NoSuchPaddingExceptione){

e.printStackTrace();

}

/** 用密钥初始化Cipher对象 */

try{

cipher.init(Cipher.DECRYPT_MODE,key,sr);

}catch(InvalidKeyExceptione){

e.printStackTrace();

}

/** 正式执行解密操作 */

bytedecryptedData[]=null;

try{

decryptedData=cipher.doFinal(encryptedData);

}catch(IllegalStateExceptione){

e.printStackTrace();

}catch(IllegalBlockSizeExceptione){

e.printStackTrace();

}catch(BadPaddingExceptione){

e.printStackTrace();

}

returndecryptedData;

}

/**

* 取得安全密钥 此方法作废,因为每次key生成都不一样导致解密加密用的密钥都不一样, 从而导致Given final block not

* properly padded错误.

*

* @return byte数组

* @author 宋立君

* @date 2014年07月03日

*/

privatebyte[]getKey(){

/** DES算法要求有一个可信任的随机数源 */

SecureRandom sr=newSecureRandom();

/** 为我们选择的DES算法生成一个密钥生成器对象 */

KeyGenerator kg=null;

try{

kg=KeyGenerator.getInstance("DES");

}catch(NoSuchAlgorithmExceptione){

e.printStackTrace();

}

kg.init(sr);

/** 生成密钥工具类 */

SecretKey key=kg.generateKey();

/** 生成密钥byte数组 */

byterawKeyData[]=key.getEncoded();

returnrawKeyData;

}

}

Base64.java

packagecom.itjh.javaUtil;

importjava.io.*;

/**

* Base64 编码和解码。

*

* @author 宋立君

* @date 2014年07月03日

*/

publicclassBase64{

publicBase64(){

}

/**

* 功能:编码字符串

*

* @author 宋立君

* @date 2014年07月03日

* @param data

*            源字符串

* @return String

*/

publicstaticStringencode(Stringdata){

returnnewString(encode(data.getBytes()));

}

/**

* 功能:解码字符串

*

* @author 宋立君

* @date 2014年07月03日

* @param data

*            源字符串

* @return String

*/

publicstaticStringdecode(Stringdata){

returnnewString(decode(data.toCharArray()));

}

/**

* 功能:编码byte[]

*

* @author 宋立君

* @date 2014年07月03日

* @param data

*            源

* @return char[]

*/

publicstaticchar[]encode(byte[]data){

char[]out=newchar[((data.length+2)/3)*4];

for(inti=0,index=0;i

booleanquad=false;

booleantrip=false;

intval=(0xFF&(int)data[i]);

val<<=8;

if((i+1)

val|=(0xFF&(int)data[i+1]);

trip=true;

}

val<<=8;

if((i+2)

val|=(0xFF&(int)data[i+2]);

quad=true;

}

out[index+3]=alphabet[(quad?(val&0x3F):64)];

val>>=6;

out[index+2]=alphabet[(trip?(val&0x3F):64)];

val>>=6;

out[index+1]=alphabet[val&0x3F];

val>>=6;

out[index+0]=alphabet[val&0x3F];

}

returnout;

}

/**

* 功能:解码

*

* @author 宋立君

* @date 2014年07月03日

* @param data

*            编码后的字符数组

* @return byte[]

*/

publicstaticbyte[]decode(char[]data){

inttempLen=data.length;

for(intix=0;ix

if((data[ix]>255)||codes[data[ix]]<0){

--tempLen;// ignore non-valid chars and padding

}

}

// calculate required length:

// -- 3 bytes for every 4 valid base64 chars

// -- plus 2 bytes if there are 3 extra base64 chars,

// or plus 1 byte if there are 2 extra.

intlen=(tempLen/4)*3;

if((tempLen%4)==3){

len+=2;

}

if((tempLen%4)==2){

len+=1;

}

byte[]out=newbyte[len];

intshift=0;// # of excess bits stored in accum

intaccum=0;// excess bits

intindex=0;

// we now go through the entire array (NOT using the 'tempLen' value)

for(intix=0;ix

intvalue=(data[ix]>255)?-1:codes[data[ix]];

if(value>=0){// skip over non-code

accum<<=6;// bits shift up by 6 each time thru

shift+=6;// loop, with new bits being put in

accum|=value;// at the bottom.

if(shift>=8){// whenever there are 8 or more shifted in,

shift-=8;// write them out (from the top, leaving any

out[index++]=// excess at the bottom for next iteration.

(byte)((accum>>shift)&0xff);

}

}

}

// if there is STILL something wrong we just have to throw up now!

if(index!=out.length){

thrownewError("Miscalculated data length (wrote "+index

+" instead of "+out.length+")");

}

returnout;

}

/**

* 功能:编码文件

*

* @author 宋立君

* @date 2014年07月03日

* @param file

*            源文件

*/

publicstaticvoidencode(File file)throwsIOException{

if(!file.exists()){

System.exit(0);

}

else{

byte[]decoded=readBytes(file);

char[]encoded=encode(decoded);

writeChars(file,encoded);

}

file=null;

}

/**

* 功能:解码文件。

*

* @author 宋立君

* @date 2014年07月03日

* @param file

*            源文件

* @throws IOException

*/

publicstaticvoiddecode(File file)throwsIOException{

if(!file.exists()){

System.exit(0);

}else{

char[]encoded=readChars(file);

byte[]decoded=decode(encoded);

writeBytes(file,decoded);

}

file=null;

}

//

// code characters for values 0..63

//

privatestaticchar[]alphabet="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="

.toCharArray();

//

// lookup table for converting base64 characters to value in range 0..63

//

privatestaticbyte[]codes=newbyte[256];

static{

for(inti=0;i<256;i++){

codes[i]=-1;

// LoggerUtil.debug(i + "&" + codes[i] + " ");

}

for(inti='A';i<='Z';i++){

codes[i]=(byte)(i-'A');

// LoggerUtil.debug(i + "&" + codes[i] + " ");

}

for(inti='a';i<='z';i++){

codes[i]=(byte)(26+i-'a');

// LoggerUtil.debug(i + "&" + codes[i] + " ");

}

for(inti='0';i<='9';i++){

codes[i]=(byte)(52+i-'0');

// LoggerUtil.debug(i + "&" + codes[i] + " ");

}

codes['+']=62;

codes['/']=63;

}

privatestaticbyte[]readBytes(File file)throwsIOException{

ByteArrayOutputStream baos=newByteArrayOutputStream();

byte[]b=null;

InputStream fis=null;

InputStream is=null;

try{

fis=newFileInputStream(file);

is=newBufferedInputStream(fis);

intcount=0;

byte[]buf=newbyte[16384];

while((count=is.read(buf))!=-1){

if(count>0){

baos.write(buf,0,count);

}

}

b=baos.toByteArray();

}finally{

try{

if(fis!=null)

fis.close();

if(is!=null)

is.close();

if(baos!=null)

baos.close();

}catch(Exceptione){

System.out.println(e);

}

}

returnb;

}

privatestaticchar[]readChars(File file)throwsIOException{

CharArrayWriter caw=newCharArrayWriter();

Reader fr=null;

Reader in=null;

try{

fr=newFileReader(file);

in=newBufferedReader(fr);

intcount=0;

char[]buf=newchar[16384];

while((count=in.read(buf))!=-1){

if(count>0){

caw.write(buf,0,count);

}

}

}finally{

try{

if(caw!=null)

caw.close();

if(in!=null)

in.close();

if(fr!=null)

fr.close();

}catch(Exceptione){

System.out.println(e);

}

}

returncaw.toCharArray();

}

privatestaticvoidwriteBytes(File file,byte[]data)throwsIOException{

OutputStream fos=null;

OutputStream os=null;

try{

fos=newFileOutputStream(file);

os=newBufferedOutputStream(fos);

os.write(data);

}finally{

try{

if(os!=null)

os.close();

if(fos!=null)

fos.close();

}catch(Exceptione){

System.out.println(e);

}

}

}

privatestaticvoidwriteChars(File file,char[]data)throwsIOException{

Writer fos=null;

Writer os=null;

try{

fos=newFileWriter(file);

os=newBufferedWriter(fos);

os.write(data);

}finally{

try{

if(os!=null)

os.close();

if(fos!=null)

fos.close();

}catch(Exceptione){

e.printStackTrace();

}

}

}

// /

// end of test code.

// /

}

三、ExcelUtil工具类

packagecom.itjh.javaUtil;

importjava.io.File;

importjava.io.FileInputStream;

importjava.io.FileNotFoundException;

importjava.io.FileOutputStream;

importjava.io.IOException;

importjava.io.OutputStream;

importjava.text.DecimalFormat;

importjava.util.LinkedList;

importjava.util.List;

importjavax.servlet.http.HttpServletResponse;

importorg.apache.poi.hssf.usermodel.HSSFCell;

importorg.apache.poi.hssf.usermodel.HSSFRichTextString;

importorg.apache.poi.hssf.usermodel.HSSFRow;

importorg.apache.poi.hssf.usermodel.HSSFSheet;

importorg.apache.poi.hssf.usermodel.HSSFWorkbook;

importorg.apache.poi.openxml4j.exceptions.InvalidFormatException;

importorg.apache.poi.ss.usermodel.Cell;

importorg.apache.poi.ss.usermodel.DateUtil;

importorg.apache.poi.ss.usermodel.Row;

importorg.apache.poi.ss.usermodel.Sheet;

importorg.apache.poi.ss.usermodel.Workbook;

importorg.apache.poi.ss.usermodel.WorkbookFactory;

/**

* 封装对excel的操作,包括本地读写excel和流中输出excel,支持office 2007。

* 依赖于poi-3.9-20121203.jar,poi-ooxml-3.9-20121203.jar,poi-ooxml-schemas-3.9-

* 20121203.jar,dom4j-1.6.1.jar

* 有参构造函数参数为excel的全路径

*

* @author 宋立君

* @date 2014年07月03日

*/

publicclassExcelUtil{

// excel文件路径

privateStringpath="";

// 写入excel时,是否自动扩展列宽度来符合内容。

privatebooleanautoColumnWidth=false;

/**

* 无参构造函数 默认

*/

publicExcelUtil(){

}

/**

* 有参构造函数

*

* @param path

*            excel路径

*/

publicExcelUtil(Stringpath){

this.path=path;

}

/**

* 读取某个工作簿上的所有单元格的值。

*

* @param sheetOrder

*            工作簿序号,从0开始。

* @return List 所有单元格的值。

* @throws IOException

*             加载excel文件IO异常。

* @throws FileNotFoundException

*             excel文件没有找到异常。

* @throws InvalidFormatException

* @author 宋立君

* @date 2014年07月03日

*/

publicListread(intsheetOrder)throwsFileNotFoundException,

IOException,InvalidFormatException{

FileInputStream fis=newFileInputStream(path);

Workbook workbook=WorkbookFactory.create(fis);

if(fis!=null){

fis.close();

}

Sheet sheet=workbook.getSheetAt(sheetOrder);

// 用来记录excel值

ListvalueList=newLinkedList();

// 循环遍历每一行、每一列。

for(Row row:sheet){

// 每一行

Object[]rowObject=null;

for(Cell cell:row){

// cell.getCellType是获得cell里面保存的值的type

switch(cell.getCellType()){

caseCell.CELL_TYPE_BOOLEAN:

// 得到Boolean对象的方法

rowObject=CollectionUtil.addObjectToArray(rowObject,

cell.getBooleanCellValue());

break;

caseCell.CELL_TYPE_NUMERIC:

// 先看是否是日期格式

if(DateUtil.isCellDateFormatted(cell)){

// 读取日期格式

rowObject=CollectionUtil.addObjectToArray(rowObject,

cell.getDateCellValue());

}else{

DecimalFormat df=newDecimalFormat();

// 单元格的值,替换掉,

Stringvalue=df.format(cell.getNumericCellValue())

.replace(",","");

// 读取数字

rowObject=CollectionUtil.addObjectToArray(rowObject,

value);

}

break;

caseCell.CELL_TYPE_FORMULA:

// 读取公式

rowObject=CollectionUtil.addObjectToArray(rowObject,

cell.getCellFormula());

break;

caseCell.CELL_TYPE_STRING:

// 读取String

rowObject=CollectionUtil.addObjectToArray(rowObject,cell

.getRichStringCellValue().toString());

break;

}

}

// 将这行添加到list。

valueList.add(rowObject);

}

returnvalueList;

}

/**

* 读取某个工作簿上的某个单元格的值。

*

* @param sheetOrder

*            工作簿序号,从0开始。

* @param colum

*            列数 从1开始

* @param row

*            行数 从1开始

* @return 单元格的值。

* @throws Exception

*             加载excel异常。

* @author 宋立君

* @date 2014年07月03日

*/

publicStringread(intsheetOrder,intcolum,introw)throwsException{

FileInputStream fis=newFileInputStream(path);

Workbook workbook=WorkbookFactory.create(fis);

if(fis!=null){

fis.close();

}

Sheet sheet=workbook.getSheetAt(sheetOrder);

Row rows=sheet.getRow(row-1);

Cell cell=rows.getCell(colum-1);

Stringcontent=cell.getStringCellValue();

returncontent;

}

/**

* 在指定的工作簿、行、列书写值。

*

* @param sheetOrder

*            工作簿序号,基于0.

* @param colum

*            列 基于1

* @param row

*            行 基于1

* @param content

*            将要被书写的内容。

* @throws Exception

*             书写后保存异常。

* @author 宋立君

* @date 2014年07月03日

*/

publicvoidwrite(intsheetOrder,intcolum,introw,Stringcontent)

throwsException{

FileInputStream fis=newFileInputStream(path);

Workbook workbook=WorkbookFactory.create(fis);

if(fis!=null){

fis.close();

}

Sheet sheet=workbook.getSheetAt(sheetOrder);

Row rows=sheet.createRow(row-1);

Cell cell=rows.createCell(colum-1);

cell.setCellValue(content);

FileOutputStream fileOut=newFileOutputStream(path);

workbook.write(fileOut);

fileOut.close();

}

/**

* 得到一个工作区最后一条记录的序号,相当于这个工作簿共多少行数据。

*

* @param sheetOrder

*            工作区序号

* @return int 序号。

* @throws IOException

*             根据excel路径加载excel异常。

* @throws InvalidFormatException

* @author 宋立君

* @date 2014年07月03日

*/

publicintgetSheetLastRowNum(intsheetOrder)throwsIOException,

InvalidFormatException{

FileInputStream fis=newFileInputStream(path);

Workbook workbook=WorkbookFactory.create(fis);

if(fis!=null){

fis.close();

}

Sheet sheet=workbook.getSheetAt(sheetOrder);

returnsheet.getLastRowNum();

}

/**

* 在磁盘生成一个含有内容的excel,路径为path属性

*

* @param sheetName

*            导出的sheet名称

* @param fieldName

*            列名数组

* @param data

*            数据组

* @throws IOException

* @author 宋立君

* @date 2014年07月03日

*/

publicvoidmakeExcel(StringsheetName,String[]fieldName,

Listdata)throwsIOException{

// 在内存中生成工作薄

HSSFWorkbook workbook=makeWorkBook(sheetName,fieldName,data);

// 截取文件夹路径

StringfilePath=path.substring(0,path.lastIndexOf("\\"));

// 如果路径不存在,创建路径

File file=newFile(filePath);

// System.out.println(path+"-----------"+file.exists());

if(!file.exists())

file.mkdirs();

FileOutputStream fileOut=newFileOutputStream(path);

workbook.write(fileOut);

fileOut.close();

}

/**

* 在输出流中导出excel。

*

* @param excelName

*            导出的excel名称 包括扩展名

* @param sheetName

*            导出的sheet名称

* @param fieldName

*            列名数组

* @param data

*            数据组

* @param response

*            response

* @throws IOException

*             转换流时IO错误

* @author 宋立君

* @date 2014年07月03日

*/

publicvoidmakeStreamExcel(StringexcelName,StringsheetName,

String[]fieldName,Listdata,

HttpServletResponse response)throwsIOException{

OutputStream os=null;

response.reset();// 清空输出流

os=response.getOutputStream();// 取得输出流

response.setHeader("Content-disposition","attachment; filename="

+newString(excelName.getBytes(),"ISO-8859-1"));// 设定输出文件头

response.setContentType("application/msexcel");// 定义输出类型

// 在内存中生成工作薄

HSSFWorkbook workbook=makeWorkBook(sheetName,fieldName,data);

os.flush();

workbook.write(os);

}

/**

* 根据条件,生成工作薄对象到内存。

*

* @param sheetName

*            工作表对象名称

* @param fieldName

*            首列列名称

* @param data

*            数据

* @return HSSFWorkbook

* @author 宋立君

* @date 2014年07月03日

*/

privateHSSFWorkbook makeWorkBook(StringsheetName,String[]fieldName,

Listdata){

// 用来记录最大列宽,自动调整列宽。

Integercollength[]=newInteger[fieldName.length];

// 产生工作薄对象

HSSFWorkbook workbook=newHSSFWorkbook();

// 产生工作表对象

HSSFSheet sheet=workbook.createSheet();

// 为了工作表能支持中文,设置字符集为UTF_16

workbook.setSheetName(0,sheetName);

// 产生一行

HSSFRow row=sheet.createRow(0);

// 产生单元格

HSSFCell cell;

// 写入各个字段的名称

for(inti=0;i

// 创建第一行各个字段名称的单元格

cell=row.createCell((short)i);

// 设置单元格内容为字符串型

cell.setCellType(HSSFCell.CELL_TYPE_STRING);

// 为了能在单元格中输入中文,设置字符集为UTF_16

// cell.setEncoding(HSSFCell.ENCODING_UTF_16);

// 给单元格内容赋值

cell.setCellValue(newHSSFRichTextString(fieldName[i]));

// 初始化列宽

collength[i]=fieldName[i].getBytes().length;

}

// 临时单元格内容

StringtempCellContent="";

// 写入各条记录,每条记录对应excel表中的一行

for(inti=0;i

Object[]tmp=data.get(i);

// 生成一行

row=sheet.createRow(i+1);

for(intj=0;j

cell=row.createCell((short)j);

// 设置单元格字符类型为String

cell.setCellType(HSSFCell.CELL_TYPE_STRING);

tempCellContent=(tmp[j]==null)?"":tmp[j].toString();

cell.setCellValue(newHSSFRichTextString(tempCellContent));

// 如果自动调整列宽度。

if(autoColumnWidth){

if(j>=collength.length){// 标题列数小于数据列数时。

collength=CollectionUtil.addObjectToArray(collength,

tempCellContent.getBytes().length);

}else{

// 如果这个内容的宽度大于之前最大的,就按照这个设置宽度。

if(collength[j]

collength[j]=tempCellContent.getBytes().length;

}

}

}

}

}

// 自动调整列宽度。

if(autoColumnWidth){

// 调整列为这列文字对应的最大宽度。

for(inti=0;i

sheet.setColumnWidth(i,collength[i]*2*256);

}

}

returnworkbook;

}

/**

* 功能:设置写入excel时,是否自动扩展列宽度来符合内容,默认为false。

*

* @author 宋立君

* @date 2014年07月03日

* @param autoColumnWidth

*            true或者false

*/

publicvoidsetAutoColumnWidth(booleanautoColumnWidth){

this.autoColumnWidth=autoColumnWidth;

}

}

依赖包下载地址:链接:http://pan.baidu.com/s/1ntof9pv 密码:6j5s

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值