如下是根据ID从数据查询出来导出Excel的方法,但现在只是导出最后一条记录(每次都是后面的替换前面的),请教怎样才能全部导出来?
请教各位,感谢!!
public InputStream importExcel() throws Exception {
String str = "1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19";
List all = new ArrayList();
 //1.建立工作的Excel文档
HSSFWorkbook wb = new HSSFWorkbook();
if(str!=null)
{
//2.建立工作区
HSSFSheet sheet = wb.createSheet("导Excel");
//3.编辑表格
HSSFRow row = null;//声明行
HSSFCell cell = null;//声明列
//利用工作区获取行的对象;注意第一行就是0,起始位置为0开始
row = sheet.createRow(0);
//利用行获取一个列的对象;注意第一列就是0,起始位置为0开始
cell = row.createCell((short)0);
//利用单元格获取一个单元格样式对象
HSSFCellStyle style = cell.getCellStyle();
//利用样式对象进行设置样式;
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);//设置水平居中
style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);//设置竖直居中
cell.setCellStyle(style);//将样式对象设置回单于格中;
cell.setCellValue(new HSSFRichTextString("测试"));
//合并单元格;
sheet.addMergedRegion(new Region(0,(short)0,2,(short)20));
row = sheet.createRow(3);
//4.填写数据;
List titleList = new ArrayList();
titleList.add("序号");
titleList.add("大类");
titleList.add("小类");
titleList.add("品牌");
titleList.add("时间");
titleList.add("数量");
titleList.add("金额");
for (short i = 0; i < titleList.size(); i++) {

cell = row.createCell(i);
cell.setCellValue(new HSSFRichTextString((String)titleList.get(i)));
}
  String[] allStr=str.split(",");//分割字符串,得到ID
  for(int i=0;i<allStr.length;i++)
  {
     String strC = allStr[i];
     if(strC != null)
     {
     int id = Integer.parseInt(strC);
String hql = "FROM CarInfo WHERE prtid=?";//根据ID,查询记录
Query q = this.getSession().createQuery(hql);
q.setInteger(0, id);
List all1 = q.list();
if(all1.size()>0)
{
CarInfo p = (CarInfo)all1.get(0);
int ids = p.getCid();//ID
String t1 = p.getCSt();//大类
String site = p.getCSt1();//小类
String type = p.getCtype();//品牌
String con = p.getCtime();//时间
String t2 = p.getCCount();//数量
double price1 = p.getCprice();//金额
cell = row.createCell((short)0);
cell.setCellValue(ids);
//大类
cell = row.createCell((short)1);
cell.setCellValue(new HSSFRichTextString(t1));
//小类
cell = row.createCell((short)2);
cell.setCellValue(new HSSFRichTextString(site));
//品牌
cell = row.createCell((short)3);
cell.setCellValue(new HSSFRichTextString(type));
//时间
cell = row.createCell((short)4);
cell.setCellValue(new HSSFRichTextString(con));
//数量
cell = row.createCell((short)5);
cell.setCellValue(new HSSFRichTextString(t2));
//金额
cell = row.createCell((short)6);
String price = String.valueOf(price1);
cell.setCellValue(new HSSFRichTextString(price));
}
     }
  }
}
String fileName = null;
    String path = "/D/d";
try {
    fileName = "excel"+new Date().getTime()+".xls";
String downloaddir = ServletActionContext.getRequest().getRealPath(path);
FileOutputStream fos = new FileOutputStream(downloaddir+"/"+fileName);
wb.write(fos);
fos.close();
} catch (Exception e) {
e.printStackTrace();

}

ByteArrayOutputStream os = new ByteArrayOutputStream();
 OutputStream oo = new ByteArrayOutputStream();
wb.write(os);
os.flush();

byte[] content = os.toByteArray();
InputStream inputStream = new ByteArrayInputStream(content, 0, content.length);
os.close();
return null;
}在线等待,请教

解决方案 »

  1.   

    楼主,你不要这么写嘛
    1。从数据库查询出所有的数据,即得到:List<CarInfo> 
    2。创建Excel的工作目录
    3。用ForEach循环,将List的数据写入workbook
      

  2.   


      //利用工作区获取行的对象;注意第一行就是0,起始位置为0开始
                    row = sheet.createRow(0);
    这行有问题你的row是第一行你每次循环都是往第一行写数据。。其实并不是你的数据库没有写进去,只是你写进去的数据库,又被下一次循环给覆盖掉了。你应该这样写:我给个示例(当你数据List组装完毕后)
    for(int i =0 ; i < list.size();i++){
       sheet.createRow(i);  //这样才能保证每条数据都会建单独的一行,不会被覆盖掉
    }
      

  3.   

    谢谢楼上的回答,因为是根据用户在JSP页面中选择checkbox来查询,然后导出的,条件是通过页面中传过来的ID,所以只能通过for循环来处理
      

  4.   

    这个并不冲突啊。。
      String[]  carIds =    request.getParameterValues("checkbox");
      //接着处理一下参数,按自己的业务逻辑处理,略....  String sql = "select * from t_car where 1=1";
      for( int i = 0 ; i< carIds.length ;i++){
        sql += ........ ; //这里组装sql语句可以用in 或者exsist
     }  //执行sql.,得到一个List<Car> list .....
      
     //创建workbook  sheet; for(int j=0; j<list.size();j++){
       Row row =  sheet.createRow(i);//创建行。。
        //创建列。并设置数据
    }
      

  5.   

    谢谢楼上的回答,是不是根据ID查询出来,然后组成一个List,然后再使用
     for(int j=0; j<list.size();j++){
       Row row =  sheet.createRow(i);//创建行。。
        //创建列。并设置数据
    },请问楼上的兄弟,是这个意思?
      

  6.   

    你的for循环 可以在SQL执行的时候进行 
    把所有选中的记录查询出来组装在一个集合里面 然后在action进行创建EXCEL文件参考代码:(POI)// 创建EXCEL文件
    private void createExcel(List excelList) {
    FileOutputStream fos = null;
    try {
    String filePath = getRequest().getRealPath("/") + "/" + fileName;
    File file = new File(filePath);
    if (!file.exists())
    file.getParentFile().mkdirs();
    log.info(filePath);
    fos = new FileOutputStream(filePath);
    HSSFWorkbook wb = new HSSFWorkbook();
    HSSFSheet sheet = wb.createSheet();
    wb.setSheetName(0, "GROUPINFO");
    HSSFRow header = sheet.createRow(0);
    header.createCell(0).setCellValue(this.getText("groupinfo.code"));
    header.createCell(1).setCellValue(this.getText("groupinfo.fullname"));
    header.createCell(2).setCellValue(this.getText("groupinfo.shortname"));
    header.createCell(3).setCellValue(this.getText("groupinfo.addr"));
    header.createCell(4).setCellValue(this.getText("groupinfo.tel"));
    header.createCell(5).setCellValue(this.getText("groupinfo.bossId"));
    header.createCell(6).setCellValue(this.getText("groupinfo.cpId"));
    if (excelList != null) {
    for (short i = 0; i < excelList.size(); i++) {
    Groupinfo gr = (Groupinfo) excelList.get(i);
    if (gr != null) {
    HSSFRow row = sheet.createRow(i + 1);
    if (gr.getCode() != null)
    row.createCell(0).setCellValue(gr.getCode());
    else
    row.createCell(0).setCellValue("");
    if (gr.getFullname() != null)
    row.createCell(1).setCellValue(gr.getFullname());
    else
    row.createCell(1).setCellValue("");
    if (gr.getShortname() != null)
    row.createCell(2).setCellValue(gr.getShortname());
    else
    row.createCell(2).setCellValue("");
    if (gr.getAddr() != null) {
    row.createCell(3).setCellValue(gr.getAddr());
    } else {
    row.createCell(3).setCellValue("");
    }
    if (gr.getTel() != null) {
    row.createCell(4).setCellValue(gr.getTel());
    } else {
    row.createCell(4).setCellValue("");
    }
    if (gr.getBossId() != null) {
    row.createCell(5).setCellValue(gr.getBossId());
    } else {
    row.createCell(5).setCellValue("");
    }
    if (gr.getBossId() != null) {
    row.createCell(6).setCellValue(gr.getCpId());
    } else {
    row.createCell(6).setCellValue("");
    }
    }
    }
    }
    wb.write(fos);
    fos.close();
    } catch (Exception ex) {
    ex.printStackTrace();
    log.error(ex.getMessage());
    } finally {
    try {
    if (null != fos) {
    fos.close();
    }
    } catch (Exception ex) {}
    }
    }
      

  7.   


    是的。。先将数据库查询出来。组装成List..  
    再去创建好workbook  sheet..
    但是创建Row的时候要循环来创建。。sheet.createRow(行数的索引)  这个索引你不能写死的,写死了,他就老是往那一行里面写数据。。老是覆盖前面的数据。 这个索引就是你的数据集合List的索引。。
      

  8.   

    如果是传List过来,我都明白了,可能现在传过来的是字符串,然后把分割字符串(做成一条条ID),然后根据ID查询,再导Excel
      

  9.   


    是的。。其实导入导出,这些问题。
    最基本的思路:
    1。准备好数据
          包括查询数据库,或者是手动组装,等....
        你这里id一个String,你可以把他们变成一个Integer[]数组。。然后用 sql的in语句(carId in (1,2,3)或者exists语句, 查询出所有的结果。 然后将他们组装成一个List<Car> list2。  根据你的目标格式,创建Excel(workBook sheet)
          至于语法。你可以去poi.apache.org上去看。