一个简单的类用于JAVA输出EXCEL文…

来源:互联网 发布:js 按轨迹移动 编辑:程序博客网 时间:2024/06/02 02:57
1.参数传入及如何调用:
List data= //这里的list即为你的数据,我这里就没给初始化了,你根据你的需求取数据。
ServletUtils.currentResponse().setHeader("Content-disposition","attachment;filename="+URLEncoder.encode("舆情报告.xls", "UTF-8"));//设置EXCEL文件名称。
String[]title={"关键词","微博id","发布日期","个人ID","微博内容","评论数","转发数","舆情性质","处理日期","微博链接"};//EXCEL文件包含的列命
String[]keys={"keyword","contentId","time","name","text","comments","reposts","surveyResult","surveyTime","url"}; //EXCEL文件包含的列命在数据源data中所对应的字段命
ExcelUtil.outputExcel(ServletUtils.currentResponse().getOutputStream(),title,list, keys, "surveyResult");//调用输出方法

2.这是输出文件具体方法
public class ExcelUtil {
public static voidoutputExcel(OutputStream out,String[]title,List<Map<String,Object>> data, String[] keys,Stringsplit) throws IOException, RowsExceededException,WriteException{
WritableWorkbookworkbook=Workbook.createWorkbook(out);
//单元格样式
WritableFont wfc = newWritableFont(WritableFont.ARIAL,14
,WritableFont.BOLD,false,UnderlineStyle.NO_UNDERLINE,Colour.YELLOW);
WritableCellFormat wcff = newWritableCellFormat(wfc);
wcff.setWrap(false);//不自动换行
wcff.setBackground(Colour.GREEN);
try {

if(split==null){
WritableSheetst1=workbook.createSheet("sheet1", 0);
for(inti=0;i<title.length;i++){
Label l=newLabel(i,0,title[i],wcff);
if(i==3){//这里i=3时是微博内容 要长些
st1.setColumnView(i, 30);
}else{
st1.setColumnView(i, 18);
}
st1.addCell(l);
}
for(intj=1;j<data.size();j++){
Map<String,Object>m=data.get(j);
for(inti=0;i<keys.length;i++){
Label l=newLabel(i,j,m.get(keys[i])!=null?m.get(keys[i]).toString():"");
st1.addCell(l);
}
}
}else{
String cur=(String)data.get(0).get(split);
WritableSheet curSheet=null;
for(intj=0,k=1;j<data.size();j++,k++){
Map<String,Object>m=data.get(j);
if(m.get(split)!=null&&!((String)m.get(split)).equals(cur)||j==0){
cur=(String)m.get(split);//根据split字段名创建sheet,这里需要注意的是,要按哪个字段创建sheet,传入的数据就必须按那个字段排序,这里暂时是这样处理的,大家可以优化下。
curSheet=workbook.createSheet(cur!=null?cur:"无", 0);
for(inti=0;i<title.length;i++){
Label l=newLabel(i,0,title[i],wcff);
if(i==3){
curSheet.setColumnView(i,30);
}else{
curSheet.setColumnView(i,18);
}
curSheet.addCell(l);
}
k=1;
}
for(inti=0;i<keys.length;i++){
Object o=m.get(keys[i]);
if(o instanceof Integer||oinstanceof Long){
jxl.write.Number n=newjxl.write.Number(i,k,(Integer)o);
curSheet.addCell(n);
}else{
Label l=newLabel(i,k,o!=null?o+"":"");
curSheet.addCell(l);
}
}
}
}
workbook.write();
workbook.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static voidoutputExcel(OutputStream out,String[]title,List<Map<String,Object>> data, String[] keys) throwsIOException, RowsExceededException, WriteException{
outputExcel(out, title,data,keys);
}
}


0 0