使用REST服务下载excel文件

使用REST服务下载excel文件。用HSSFWorkbook生成excel文件,用jax-rs、resteasy提供rest服务。

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;

@Path("/download")
public class DownloadFileService {
    @GET
    @Path("/excel")
    @Produces("application/vnd.ms-excel; charset=UTF-8")
    public Response getExcelFile() {
 
    	Workbook workbook = new HSSFWorkbook();
		String title = "明细表";
		Sheet sheet = workbook.createSheet(title);
		Row headerRow = sheet.createRow(0);
		// TODO
		headerRow.createCell(0).setCellValue("开始时间");
		headerRow.createCell(1).setCellValue("结束时间");
		headerRow.createCell(2).setCellValue("持续时间");
		headerRow.createCell(3).setCellValue("描述");
		
		Row row = sheet.createRow(1);
		row.createCell(0).setCellValue("2015-11-11");
		row.createCell(1).setCellValue("2015-11-13");
		row.createCell(2).setCellValue("2");
		row.createCell(3).setCellValue("这里是描述");
		
		//================================
		Sheet sheett = workbook.getSheetAt(0);
		sheett.setDefaultColumnWidth(25);
		CellStyle style = workbook.createCellStyle();

		// 设置这些样式
		style.setFillForegroundColor(HSSFColor.WHITE.index);
		style.setFillPattern(CellStyle.SOLID_FOREGROUND);
		style.setBorderBottom(CellStyle.BORDER_THIN);
		style.setBorderLeft(CellStyle.BORDER_THIN);
		style.setBorderRight(CellStyle.BORDER_THIN);
		style.setBorderTop(CellStyle.BORDER_THIN);
		style.setAlignment(CellStyle.ALIGN_CENTER);

		// 生成一个字体
		Font font = workbook.createFont();
		font.setColor(HSSFColor.BLACK.index);
		font.setFontHeightInPoints((short) 12);

		// 把字体应用到当前的样式
		style.setFont(font);
		for (Row roww : sheet) {
			for (Cell cell : roww) {
				cell.setCellStyle(style);
			}
		}
		ByteArrayOutputStream baos = null;
		try {
			 baos = new ByteArrayOutputStream();
			workbook.write(baos);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
        ResponseBuilder response = Response.ok(baos.toByteArray());
        response.header("Content-Disposition","attachment; filename=\"test.xls\"");
        return response.build();
 
    }
}
浏览器输入http://127.0.0.1:8080/rest-project/rest/download/excel就能下载生成的excel文件

你可能感兴趣的:(Excel,resteasy)