这是最早写的excel工具类,比较简单,比较粗糙:
import java.io.File;
import java.io.IOException;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;
import org.apache.log4j.Logger;
public class ExcelUtils {
static private Logger logger = Logger.getLogger(ExcelUtils.class);
static public int SUCCESS = 0;
static public int ERROR = -1;
/**
* 创建单个sheet的excel文件,自己指定路径,用二维数组来映射相应的单元格
**/
static public int createExcel(String fileRootPath,String fileName,String sheetName,String[][] dataArr){
int result = ERROR;
try {
if(fileRootPath == null || "".equals(fileRootPath) || fileName == null || "".equals(fileName) ){
throw new Exception("创建excel文件错误:createExcel方法参数值为空!");
}
if(dataArr == null || dataArr[0] == null){
throw new Exception("输入的参数dataArr错误!");
}
String filePath = fileRootPath + fileName;
File file = new File(fileRootPath);
if(!file.exists()){
file.mkdirs();
}
WritableWorkbook book = Workbook.createWorkbook(new File(filePath));
if(sheetName == null || "".equals(sheetName)){
sheetName = "第一页";
}
// 生成名为sheetName的工作表,参数0表示这是第一页
WritableSheet sheet = book.createSheet(sheetName , 0);
// 在Label对象的构造子中指名单元格位置是第一列第一行(0,0)
// 以及单元格内容为test
for(int i=0 ;i<dataArr.length;i++){
for(int j=0;j<dataArr[0].length;j++){
Label label = new Label(j, i, dataArr[i][j]);
sheet.addCell(label);// 将定义好的单元格添加到工作表中
}
}
book.write();
book.close();
result = SUCCESS;
} catch (IOException e) {
logger.error("excel文件路径错误!");
logger.error(e.toString());
return result;
} catch (RowsExceededException e) {
logger.error("创建excel时,行超过!");
logger.error(e.toString());
return result;
} catch (WriteException e) {
logger.error("创建excel时,写入错误!");
logger.error(e.toString());
return result;
}catch (Exception e) {
logger.error(e.toString());
return result;
}
return result;
}
public static void main(String args[]) {
String[][] myarr = new String[2][3];
myarr[0][0]="11";
myarr[0][1]="12";
myarr[0][2]="13";
myarr[1][0]="21";
myarr[1][1]="22";
myarr[1][2]="23";
ExcelUtils.createExcel("D:/test/", "test.xls", "代理商账户列表", myarr);
}
}
后面随着业务的扩展,需要在线下载excel文件,之前写的这个工具类,没有合理的分层结构和下载导出输出流.
下面的代码是改进后的工具类,有比较好的扩展性和下载导出的功能,参考自:http://www.blogjava.net/qnjian/archive/2010/11/29/25999.html?opt=admin
excel实体模型:
package com.uid.utils.poi;
import java.util.List;
public class ExcelModel {
/**
* 文件路径,这里是包含文件名的路径
*/
protected String path;
/**
* 工作表名
*/
protected String sheetName;
/**
* 表内数据,保存在二维的ArrayList对象中
*/
protected List<ExcelRowData> data;
/**
* 数据表的标题内容
*/
protected List<String> header;
/**
* 用于设置列宽的整型数组 这个方法在程序中暂未用到 适用于固定列数的表格
*/
protected int[] width;
public ExcelModel(){}
public ExcelModel(String path) {
this.path = path;
}
.....省略get,set方法....
}
package com.uid.utils.poi;
import java.util.List;
/**
* excel行数据模型
* @author gufachongyang02
*/
public class ExcelRowData{
private List<String> data;
private int length;//此行的数量
.....省略get,set方法....</span>
}
excel文件下载导出接口类:
package com.uid.utils.poi;
import java.io.IOException;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
public interface ExcelDownLoad {
/**
* 初始化要生成的Excel的表模型
* @param data 传入的数据,每行数目固定
* @return
* @throws Exception
*/
public abstract ExcelModel createDownLoadExcel
(List<ExcelRowData> data)throws Exception;
/**
* 在文件已存在的情况下,采用读取文件流的方式实现左键点击下载功能,
* 本系统没有采取这个方法,而是直接将数据传往输出流,效率更高。
* @param inPutFileName 读出的文件名
* @param outPutFileName 保存的文件名
* @param HttpServletResponse
* @see HttpServletResponse
* @throws IOException
*/
public void downLoad(String inPutFileName, String outPutFileName,
HttpServletResponse response) throws IOException ;
/**
* 在文件不存在的情况下,采用生成输出流的方式实现左键点击下载功能。
* @param outPutFileName 保存的文件名
* @param out ServletOutputStream对象
* @param downExcel 填充了数据的ExcelModel
* @param HttpServletResponse
* @see HttpServletResponse
* @throws Exception
*/
public void downLoad( ExcelModel downExcel,String outPutFileName,
HttpServletResponse response) throws Exception ;
}
excel文件下载基类:
package com.uid.utils.poi;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import com.uid.common.LogWriter;
public abstract class BaseExcelDownLoad implements ExcelDownLoad{
/**
* 初始化要生成的Excel的表模型
* @param data 传入的数据,每行数目固定
* @return
* @throws Exception
*/
public abstract ExcelModel createDownLoadExcel
(List<ExcelRowData> data)throws Exception;
/**
* 在文件已存在的情况下,采用读取文件流的方式实现左键点击下载功能,
* 本系统没有采取这个方法,而是直接将数据传往输出流,效率更高。
* @param inPutFileName 读出的文件名
* @param outPutFileName 保存的文件名
* @param HttpServletResponse
* @see HttpServletResponse
* @throws IOException
*/
public void downLoad(String inPutFileName, String outPutFileName,
HttpServletResponse response) throws IOException {
InputStream is = null;
OutputStream outputstream = null;
try{
//打开指定文件的流信息
is = new FileInputStream(inPutFileName);
//写出流信息
int data = -1;
outputstream = response.getOutputStream();
//清空输出流
response.reset();
//设置响应头和下载保存的文件名
response.setHeader("content-disposition","attachment;filename="+outPutFileName);
//定义输出类型
response.setContentType("APPLICATION/msexcel");
while ( (data = is.read()) != -1){
outputstream.write(data);
}
}finally{
is.close();
outputstream.close();
}
response.flushBuffer();
}
/**
* 在文件不存在的情况下,采用生成输出流的方式实现左键点击下载功能。
* @param outPutFileName 保存的文件名
* @param out ServletOutputStream对象
* @param downExcel 填充了数据的ExcelModel
* @param HttpServletResponse
* @see HttpServletResponse
* @throws Exception
*/
public void downLoad(ExcelModel downExcel,String outPutFileName,
HttpServletResponse response) throws Exception {
OutputStream out = null;
try{
//取得输出流
out = response.getOutputStream();
//清空输出流
response.reset();
//设置响应头和下载保存的文件名
response.setHeader("content-disposition","attachment;filename="+outPutFileName);
//定义输出类型
response.setContentType("APPLICATION/msexcel");
//out:传入的输出流
ExcelOperator.WriteExcel(downExcel,out);
LogWriter.logInfo("downLoad ...");
}finally{
out.close();
}
//这一行非常关键,否则在实际中有可能出现莫名其妙的问题!!!
response.flushBuffer();//强行将响应缓存中的内容发送到目的地
}
}
使用poi类库对excel进行操作,内含有测试的main方法,生成excel文件:
package com.uid.utils.poi;
import java.io.FileOutputStream;
import java.io.BufferedOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.math.BigDecimal;
import java.io.OutputStream;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
/**
*实现生成Excel文件的操作
*/
public class ExcelOperator{
/**
* 将数据信息写入到Excel表文件,采取自建输出流的方式。
* @param excel ExcelModel Excel表的模型对象
* @throws Exception
*/
static public void WriteExcel(ExcelModel excel)throws Exception{
FileOutputStream fOut = null;
BufferedOutputStream bf = null;
try{
HSSFWorkbook workbook =ExcelOperator.getInitWorkbook(excel);
//新建一输出文件流
fOut = new FileOutputStream(excel.getPath());
bf = new BufferedOutputStream(fOut);
// 把相应的Excel 工作簿存盘
workbook.write(fOut);
fOut.flush();
bf.flush();
}catch(Exception e){
throw new Exception(e.getMessage());
}finally{
// 操作结束,关闭文件
bf.close();
fOut.close();
}
}
/**
* 将数据信息写入到Excel表文件 ,采取传入输出流的方式。
* @param excel Excel表的模型对象
* @param out OutputStream 输出流
* @throws Exception
*/
static public void WriteExcel(ExcelModel excel,OutputStream out)throws Exception{
try{
HSSFWorkbook workbook = ExcelOperator.getInitWorkbook(excel);
workbook.write(out);
}catch(Exception e){
throw new Exception(e.getMessage());
}finally{
out.close();
}
}
/**
* 取得填充了数据的工作簿
* @param excel ExcelModel Excel表的模型对象
* @return HSSFWorkbook 工作簿对象
*/
@SuppressWarnings("deprecation")
static private HSSFWorkbook getInitWorkbook(ExcelModel excel){
// 创建新的Excel 工作簿
HSSFWorkbook workbook = new HSSFWorkbook();
//在Excel工作簿中建一工作表
HSSFSheet sheet = null;
String sheetName = excel.getSheetName();
if(sheetName != null){
sheet = workbook.createSheet(sheetName);
} else{
sheet = workbook.createSheet();
}
//设置表头字体
HSSFFont font_h = workbook.createFont();
font_h.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
//设置格式
HSSFCellStyle cellStyle= workbook.createCellStyle();
cellStyle.setFont(font_h);
//在索引0的位置创建行(最顶端的行)
HSSFRow row = sheet.createRow((short)0);
List<String> header = excel.getHeader();
if(header!=null){
for(int i=0;i<header.size();i++){
//在索引0的位置创建单元格(左上端)
HSSFCell cell = row.createCell((short)i);
// 定义单元格为字符串类型
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
//设置解码方式
cell.setEncoding((short)1);
//设置单元格的格式
cell.setCellStyle(cellStyle);
// 在单元格中写入表头信息
cell.setCellValue((String)header.get(i));
}
}
List<ExcelRowData> cdata = excel.getData();
for (int i=0; i<cdata.size(); i++){
//从第二行开始
HSSFRow row1 = sheet.createRow(i+1);
ExcelRowData rdata =(ExcelRowData)cdata.get(i);
//打印一行数据
for (int j=0;j<rdata.getData().size();j++){
HSSFCell cell = row1.createCell( (short)j);
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
//设置字符编码方式
cell.setEncoding((short)1);
Object o = rdata.getData().get(j);
//造型,使写入到表中的数值型对象恢复为数值型,
//这样就可以进行运算了
if(o instanceof BigDecimal){
BigDecimal b=(BigDecimal)o;
cell.setCellValue(b.doubleValue());
}else if(o instanceof Integer){
Integer it =(Integer)o;
cell.setCellValue(it.intValue());
}else if(o instanceof Long){
Long l =(Long)o;
cell.setCellValue(l.intValue());
}else if(o instanceof Double){
Double d =(Double)o;
cell.setCellValue(d.doubleValue());
}else if(o instanceof Float){
Float f = (Float)o;
cell.setCellValue(f.floatValue());
}else{
cell.setCellValue(o+"");
}
}
}
return workbook;
}
/**
* Just to test
* @param args String[]
*/
public static void main(String[] args){
List<ExcelRowData> data = new ArrayList<ExcelRowData>();
List<String> header = new ArrayList<String>();
header.add("学号");
header.add("姓名");
header.add("成绩");
for (int i=0;i<3;i++){
ExcelRowData rowDataModel = new ExcelRowData();
rowDataModel.setData(new ArrayList<String>());
rowDataModel.getData().add((i+1)+"");
rowDataModel.getData().add("Name"+(i+1));
rowDataModel.getData().add(""+(80+i));
data.add(rowDataModel);
}
ExcelModel model = new ExcelModel();
model.setPath("E:/test.xls");
model.setHeader(header);
model.setData(data);
try{
ExcelOperator.WriteExcel(model);
}catch(Exception e){
System.out.println(e.getMessage());
}
}
}
在线下载导出excel文件的具体业务demo:
package com.uid.web.back.uidcode20.business;
import java.util.ArrayList;
import java.util.List;
import com.uid.utils.poi.BaseExcelDownLoad;
import com.uid.utils.poi.ExcelModel;
import com.uid.utils.poi.ExcelRowData;
public class UidCodeExcelDownLoad extends BaseExcelDownLoad {
static private String path;
static private final List<String> header = new ArrayList<String>(){//固定excel头部数据
private static final long serialVersionUID = 1L;
{add("uid码"); add("类型");add("扫码地址");add("防伪码");}};
static private final String sheetName = "uid信息";
@Override
public ExcelModel createDownLoadExcel(List<ExcelRowData> data)
throws Exception {
ExcelModel udiExcel = null;
if(this.checkData(data)){
udiExcel = new ExcelModel();
udiExcel.setHeader(header);
udiExcel.setPath(path);
udiExcel.setSheetName(sheetName);
udiExcel.setData(data);
}
return udiExcel;
}
private boolean checkData(List<ExcelRowData> data){//可根据具体业务进行数据验证
for(ExcelRowData rowData:data){
if(rowData.getData().size() != header.size()){
return false;
}
}
return true;
}
}