需引入jxl.jar这个包.
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
public class ExcelUtils {
private WritableWorkbook rwb =null;
private WritableSheet ws = null;
private WritableCellFormat format1 = null;
private int currentRow=-1;
private Map<Integer, String> map = new HashMap<Integer,String>();
public ExcelUtils(String filePath)
{
try {
rwb = Workbook.createWorkbook(new File(filePath));
ws = rwb.createSheet("查询结果", 0);
format1=new WritableCellFormat();
format1.setAlignment(jxl.format.Alignment.CENTRE);
format1.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void addCell(int C,int R,String str)
{
try{
ws.setRowView(0,300);
Label labelC = new Label(C,R,str,format1);
ws.addCell(labelC);
}catch(Exception e){
e.printStackTrace();
}
}
public void addTitle(List<?> titleList) throws Exception
{
if(titleList!=null && titleList.size()!=0)
{
currentRow++;
for (int i = 0; i < titleList.size(); i++) {
Object obj = titleList.get(i);
addCell(i,currentRow,String.valueOf(obj));
}
}
}
public void addOneColumn(int num,Object obj)
{
map.put(num-1, String.valueOf(obj));
}
public void addContext(List<?> contextList)
{
if(contextList!=null && contextList.size()!=0)
{
for (int i = 0; i < contextList.size(); i++) {
List<?> list = (List<?>)contextList.get(i);
if(list!=null&&list.size()!=0)
{
currentRow++;
Object obj[] = list.toArray();
for (int j = 0; j < obj.length; j++) {
addCell(j,currentRow,String.valueOf(obj[j]));
}
}
}
}
}
public void writeFile()
{
if(rwb!=null)
{
try {
rwb.write();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void closeFile()
{
if(rwb!=null)
{
try {
rwb.close();
} catch (WriteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
在其它地方调用
ExcelUtils excelUtil = new ExcelUtils(path);
excelUtil.addContext(contentList);
excelUtil.writeFile();
excelUtil.closeFile();