csv格式文件实际为txt文本文件,可以右键选择用notepad++查看

//HttpServletResponse response...
try {
	StringBuilder sb = new StringBuilder();
	//sb为文本内容...
	byte[] b = sb.toString().getBytes();  
	response.setCharacterEncoding("utf-8");  
	String filename = "";
	if (operation_type != null && operation_type.equals("RELEASE")) {
		filename = "应用发布记录";
	} else if (operation_type != null && operation_type.equals("OPS")) {
		filename = "应用运维记录";
	}
	filename=URLEncoder.encode(filename,"utf-8"); //解决中文文件名下载后乱码的问题 
	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:MM:ss"); 
	response.setHeader("Content-Disposition","p_w_upload; filename=" + filename+ sdf.format(new Date())+".csv");  
	//获取响应报文输出流对象  
	//javax.servlet.ServletOutputStream
	ServletOutputStream  out =response.getOutputStream();  
	//输出  
	out.write(b);  
	out.flush();  
	out.close();  
} catch (IOException e) {

}


这里以下载文本文件为示例,实际上下载的文件可以是任何格式的。只要将要下载的数据转成byte数组即可下载。


wKiom1XDTcvi36wWAAHiOS1a67Y217.jpg


可以采用POI来生成excel文件

public class SettleGroup {
    private String settleGroupNo;//团单号
    private String settlePackageNo;//套餐号
    private String shopId;//验券门店
    private BigDecimal settlePrice;//结算价
    private BigDecimal sellPrice;//售价
    private Date consumeTime;//验券时间
    private String voucherNo;//券号
    private String status;//打款状态:打款 未打款
    //......
}

生产excel

/**
 * Created on 2016/5/5.
 */
public class ExportExcel <T> {
    public HSSFWorkbook exportExcel(Collection<T> dataset) {
        return exportExcel("导出结果", null, dataset);
    }

    public HSSFWorkbook exportExcel(String[] headers, Collection<T> dataset) {
        return exportExcel("导出结果", headers, dataset);
    }

    @SuppressWarnings("unchecked")
    public HSSFWorkbook exportExcel(String title, String[] headers,
                            Collection<T> dataset) {
        // 声明一个工作薄
        HSSFWorkbook workbook = new HSSFWorkbook();
        // 生成一个表格
        HSSFSheet sheet = workbook.createSheet(title);
        // 设置表格默认列宽度为18个字节
        sheet.setDefaultColumnWidth((short) 18);
        // 生成一个样式
        HSSFCellStyle style = workbook.createCellStyle();
        // 设置这些样式
        style.setFillForegroundColor(HSSFColor.WHITE.index);
        style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        style.setBorderRight(HSSFCellStyle.BORDER_THIN);
        style.setBorderTop(HSSFCellStyle.BORDER_THIN);
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        // 生成一个字体
        HSSFFont font = workbook.createFont();
//        font.setColor(HSSFColor.VIOLET.index);
        font.setFontHeightInPoints((short) 12);
        font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        // 把字体应用到当前的样式
        style.setFont(font);
        // 生成并设置另一个样式
        HSSFCellStyle style2 = workbook.createCellStyle();
        style2.setFillForegroundColor(HSSFColor.WHITE.index);
        style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        style2.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        style2.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        style2.setBorderRight(HSSFCellStyle.BORDER_THIN);
        style2.setBorderTop(HSSFCellStyle.BORDER_THIN);
        style2.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        // 生成另一个字体
        HSSFFont font2 = workbook.createFont();
        font2.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
        // 把字体应用到当前的样式
        style2.setFont(font2);

        // 产生表格标题行
        HSSFRow row = sheet.createRow(0);
        for (short i = 0; i < headers.length; i++) {
            HSSFCell cell = row.createCell(i);
            cell.setCellStyle(style);
            HSSFRichTextString text = new HSSFRichTextString(headers[i]);
            cell.setCellValue(text);
        }

        // 遍历集合数据,产生数据行
        Iterator<T> it = dataset.iterator();
        int index = 0;
        while (it.hasNext()) {
            index++;
            row = sheet.createRow(index);
            T t = (T) it.next();
            // 利用反射,根据javabean属性的先后顺序,动态调用getXxx()方法得到属性值
            Field[] fields = t.getClass().getDeclaredFields();
            for (short i = 0; i < fields.length; i++) {
                HSSFCell cell = row.createCell(i);
                cell.setCellStyle(style2);
                Field field = fields[i];
                String fieldName = field.getName();
                String getMethodName = "get"
                        + fieldName.substring(0, 1).toUpperCase()
                        + fieldName.substring(1);
                try {
                    Class tCls = t.getClass();
                    Method getMethod = tCls.getMethod(getMethodName,
                            new Class[] {});
                    Object value = getMethod.invoke(t, new Object[] {});
                    // 判断值的类型后进行强制类型转换
                    if(fieldName.equals("settlePrice") || fieldName.equals("sellPrice")){
                        cell.setCellValue(Double.parseDouble(value.toString()));
                    }else if(value instanceof Date) {
                        Date date = (Date) value;
                        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        cell.setCellValue(sdf.format(date));
                    }else {
                        cell.setCellValue(value.toString());
                    }
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } finally {
                    // 清理资源
                }
            }
        }
       return workbook;
    }

    public static void main(String[] args) {
        ExportExcel<SettleGroup> ex = new ExportExcel<SettleGroup>();
        String[] headers = { "团单号", "套餐号", "验券门店", "结算价", "售价", "验券时间", "券号", "打款状态"};
        List<SettleGroup> dataset = new ArrayList<SettleGroup>();

        SettleGroup settleGroup = new SettleGroup();
        settleGroup.setStatus("已打款");
        settleGroup.setConsumeTime(new Date());
        settleGroup.setSellPrice(new BigDecimal("188"));
        settleGroup.setSettleGroupNo("15034827");
        settleGroup.setSettlePackageNo("15142878");
        settleGroup.setSettlePrice(new BigDecimal("174.84"));
        settleGroup.setShopId("11313206");
        settleGroup.setVoucherNo("7893006716");
        for(int i = 0; i < 10; i++){
            dataset.add(settleGroup);
        }
        try {
            HSSFWorkbook workbook = ex.exportExcel(headers, dataset);
            OutputStream out = new FileOutputStream("E://a.xls");
            workbook.write(out);
            out.close();
            System.out.println("excel导出成功!");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Controller部分

/**
 * Created on 2016/5/5.
 */

@RequestMapping("/settle")
@Controller
public class SettleController {

    @Autowired
    private SettleService settleService;

    @RequestMapping("/downloadResult")
    public void downloadResult(@RequestParam String groupNo, HttpServletRequest request, HttpServletResponse response){
        System.out.println(groupNo);

        ExportExcel<SettleGroup> ex = new ExportExcel<SettleGroup>();
        String[] headers = { "团单号", "套餐号", "验券门店", "结算价", "售价", "验券时间", "券号", "打款状态"};
        List<SettleGroup> dataset = new ArrayList<SettleGroup>();

        //测试数据
        SettleGroup settleGroup = new SettleGroup();
        settleGroup.setStatus("已打款");
        settleGroup.setConsumeTime(new Date());
        settleGroup.setSellPrice(new BigDecimal("188"));
        settleGroup.setSettleGroupNo("15034827");
        settleGroup.setSettlePackageNo("15142878");
        settleGroup.setSettlePrice(new BigDecimal("174.84"));
        settleGroup.setShopId("11313206");
        settleGroup.setVoucherNo("7893006716");
        for(int i = 0; i < 10; i++){
            dataset.add(settleGroup);
        }
        try {
            HSSFWorkbook workbook = ex.exportExcel(headers, dataset);

            String filename = "result.xls";
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-disposition", "p_w_upload;filename=" + filename);
            OutputStream ouputStream = response.getOutputStream();
            workbook.write(ouputStream);
            ouputStream.flush();
            ouputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

需要添加pom依赖

      <dependency>
          <groupId>org.apache.poi</groupId>
          <artifactId>poi-ooxml</artifactId>
          <version>3.5-FINAL</version>
      </dependency>