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

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 void outputExcel(OutputStream out,String[] title,List<Map<String, Object>> data, String[] keys,String split) throws IOException, RowsExceededException, WriteException{
WritableWorkbook workbook=Workbook.createWorkbook(out);
//单元格样式
WritableFont wfc = new WritableFont(WritableFont.ARIAL,14
,WritableFont.BOLD,false,UnderlineStyle.NO_UNDERLINE,Colour.YELLOW);
WritableCellFormat wcff = new WritableCellFormat(wfc);
wcff.setWrap(false);//不自动换行
wcff.setBackground(Colour.GREEN);
try {

if(split==null){
WritableSheet st1=workbook.createSheet("sheet1", 0);
for(int i=0;i<title.length;i++){
Label l=new Label(i,0,title[i],wcff);
if(i==3){//这里i=3时是微博内容 要长些
st1.setColumnView(i, 30);
}else{
st1.setColumnView(i, 18);
}
st1.addCell(l);
}
for(int j=1;j<data.size();j++){
Map<String,Object> m=data.get(j);
for(int i=0;i<keys.length;i++){
Label l=new Label(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(int j=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(int i=0;i<title.length;i++){
Label l=new Label(i,0,title[i],wcff);
if(i==3){
curSheet.setColumnView(i, 30);
}else{
curSheet.setColumnView(i, 18);
}
curSheet.addCell(l);
}
k=1;
}
for(int i=0;i<keys.length;i++){
Object o=m.get(keys[i]);
if(o instanceof Integer||o instanceof Long){
jxl.write.Number n=new jxl.write.Number(i,k,(Integer)o);
curSheet.addCell(n);
}else{
Label l=new Label(i,k,o!=null?o+"":"");
curSheet.addCell(l);
}
}
}
}
workbook.write();
workbook.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void outputExcel(OutputStream out,String[] title,List<Map<String, Object>> data, String[] keys) throws IOException, RowsExceededException, WriteException{
outputExcel(out, title,data, keys);
}
}


阅读更多
上一篇JAVA发送邮件。
下一篇关于Android新浪客户端SDK,如何用…
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭