java response excel_Java 实现生成Excel,以下载方式返回浏览器本地

这篇博客介绍了如何使用Java实现将服务端数据导出为Excel文件,并以下载方式返回给浏览器。主要步骤包括:引入jxl库,设置Servlet响应头,创建并填充Excel工作簿,最后通过FileInputStream读取文件流发送到响应输出流。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

简述:

实现访问一个service, 返回相应数据的Excel返回本地(下载)

步骤:

1.首先需要导入excel的包,此处添加Maven的依赖项

net.sourceforge.jexcelapi

jxl

2.6.12

Spring中的servlet映射, 包括文件流的形式返回

/**

* 输出活动到Excel文件

* @param request

* @param response

*/

public void exportOneActivityToExcel(HttpServletRequest request

, HttpServletResponse response){

String activityId = request.getParameter("activityId");

if(activityId == null || activityId == ""){

logger.error("活动ID为空");

response.setStatus(HttpServletResponse.SC_BAD_REQUEST);

return;

}

SignActivity activity = signActivityService.getSignActivityById(activityId);

File outputFile = signActivityService.exportActivityToExcelById(activity

, this.getServletContext().getRealPath("/upload/excelFile/"));

//返回excel的文件流

try {

response.reset();// 清空输出流

response.setHeader("Content-disposition", "attachment; filename=sign_activity"

+ new SimpleDateFormat("yyyyMMdd_HHmmssSSS")

.format(new Date()) +".xls");// 设定输出文件头

response.setContentType("application/msexcel");// 定义输出类型

// 读取文件并且输出

FileInputStream fin = new FileInputStream(outputFile);

byte[] tempBytes = new byte[2048];

while (fin.read(tempBytes) != -1) {

response.getOutputStream().write(tempBytes);

}

response.getOutputStream().close();

} catch (IOException e) {

e.printStackTrace();

}

}

service层调用了自己用jxl实现的工具类的生成excel方法

/**

* 导出活动的Excel表

* @param activityId

* @return

*/

public File exportActivityToExcelById(final SignActivity activity, final String filePath) {

File excelFile = ExcelUtilProcess.exportOneSignActivity(activity, filePath) ;

return excelFile;

}

工具类中生成Ecel,返回FIle文件形式

public static File exportOneSignActivity(SignActivity activity, final String filePath){

File tempFileDir = new File(filePath);

if(!tempFileDir.exists()){

tempFileDir.mkdirs();

logger.debug("创建临时文件目录");

}

File tempExcelFile=new File(tempFileDir, "sign_activity_" + activity.getId()+".xls");

if(tempExcelFile.exists()){

tempExcelFile.delete();

logger.debug("删除同名Excel文件");

}

try {

tempExcelFile.createNewFile();

logger.debug("创建Excel文件" + tempExcelFile.getPath());

WritableWorkbook workBook=Workbook.createWorkbook(tempExcelFile);

WritableSheet sheet=workBook.createSheet("活动名单", 0);

logger.debug("创建工作表");

WritableFont wfont = new WritableFont(WritableFont.ARIAL, 16,

WritableFont.BOLD, false, UnderlineStyle.NO_UNDERLINE,

Colour.BLACK);

WritableCellFormat wcfFC = new WritableCellFormat(wfont);

wcfFC.setBackground(Colour.AQUA);

wfont = new jxl.write.WritableFont(WritableFont.ARIAL, 14,

WritableFont.BOLD, false, UnderlineStyle.NO_UNDERLINE,

Colour.BLACK);

wcfFC = new WritableCellFormat(wfont);

//插入标题

sheet.addCell(new Label(0, 0, "名称"));

sheet.addCell(new Label(1, 0, "描述"));

sheet.addCell(new Label(2, 0, "地址"));

sheet.addCell(new Label(3, 0, "发布日期"));

sheet.addCell(new Label(4, 0, "开始日期"));

sheet.addCell(new Label(5, 0, "结束日期"));

logger.debug("插入标题");

//添加传入的签到活动数据

int rowIndex=1;

sheet.addCell(new Label(0, rowIndex, activity.getName()));

sheet.addCell(new Label(1, rowIndex, activity.getDescription()));

sheet.addCell(new Label(2, rowIndex, activity.getSignAddress()));

sheet.addCell(new Label(3, rowIndex,

new SimpleDateFormat("yyyy-MM-dd").format(activity.getPublishTime())));

sheet.addCell(new Label(4, rowIndex,

new SimpleDateFormat("yyyy-MM-dd").format(activity.getStartTime())));

sheet.addCell(new Label(5, rowIndex,

new SimpleDateFormat("yyyy-MM-dd").format(activity.getEndTime())));

logger.debug("导出Excel文件完成");

// 写入Excel对象

workBook.write();

workBook.close();

logger.debug("释放资源");

} catch (IOException e) {

e.printStackTrace();

} catch (WriteException e) {

e.printStackTrace();

}

return tempExcelFile;

}

下面是前端调用后台service的实现

/**

* 获取当前部署项目的url

* 例如:

* http://192.168.2.199://8087/myWebProject

*/

function GetContextPath(){

var localObj = window.location;

var contextPath = localObj.pathname.split("/")[1];

var basePath = localObj.protocol+"//"+localObj.host+"/"+contextPath;

return basePath;

}

/**

* 导出单条活动

*/

function outputActivity(activityId){

var action = 'exportOneActivityToExcel';

window.location.href = GetContextPath() + "/business/activity?action="

+ action + "&activityId=" + activityId;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值