发表时间:2009-02-25
最后修改:2009-02-26
最近经常使用java操作excel,我选择的是Jxl,感觉比较方便,先分享下我封装的操作类:
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.List;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableCell;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;
/**
* Excel文件创建工厂类
*
*/
public class ExportInfoExcelFactory
{
/**
* List 对应不同的sheet,String[]内包含 一个sheet内的一行记录
*/
private List<String[]> headList;
/**
* 外层的list 对应不同的sheet,内部的list 包含一个sheet内所有行的记录, String[]内包含 一个sheet内的一行记录
*/
private List<List<String[]>> bodyList;
private ExportInfoExcelFactory()
{
// TODO Auto-generated constructor stub
}
public static ExportInfoExcelFactory getInstance()
{
return new ExportInfoExcelFactory();
}
/**
* 创建sheet的body体,支持多个sheet
* @param sheets
* @param bodyList
* @throws RowsExceededException
* @throws WriteException
*/
protected void creatBody(WritableSheet[] sheets,List<List<String[]>> bodyList) throws RowsExceededException, WriteException
{
for(int s=0;s<sheets.length;s++)
{
List<String[]> blist = bodyList.get(s);
int row = 1;
for(String[] strArray : blist)
{
String[] temp = strArray;
for(int col=0;col<temp.length;col++)
{
WritableCell bodyCell = new Label(col,row,temp[col]);
sheets[s].addCell(bodyCell);
}
row++;
}
}
}
/**
* 创建sheet的head支持多个sheet的创建
* @param sheets 需要创建的sheet
* @param headList 表头列表
* @throws RowsExceededException
* @throws WriteException
*/
protected void creatHead(WritableSheet[] sheets,List<String[]> headList) throws RowsExceededException, WriteException
{
for(int s=0;s<sheets.length;s++)
{
String[] heads = headList.get(s);
for(int col=0;col<heads.length;col++)
{
WritableCell headCell = new Label(col,0,heads[col]);
sheets[s].addCell(headCell);
}
}
}
/**
* 创建Excel文件
* @param exportfilePath 路径
* @param name sheet name数组
* @param index 数组
* @param sheetNumbers 要创建多少个sheet
* @throws Exception
*/
public void produceExportFile(String exportfilePath,String[] names,int[] indexs,int sheetNumbers)throws Exception
{
OutputStream os = new FileOutputStream(exportfilePath);
WritableWorkbook wb = Workbook.createWorkbook(os);
WritableSheet[] sheets = new WritableSheet[sheetNumbers];
for(int s=0;s<sheets.length;s++)
{
sheets[s]=wb.createSheet(names[s],indexs[s]);
}
creatHead(sheets, headList);
creatBody(sheets, bodyList);
wb.write();
wb.close();
os.close();
}
public List<String[]> getHeadList()
{
return headList;
}
public void setHeadList(List<String[]> headList)
{
this.headList = headList;
}
public List<List<String[]>> getBodyList()
{
return bodyList;
}
public void setBodyList(List<List<String[]>> bodyList)
{
this.bodyList = bodyList;
}
}