java数据导出到Excel Java中用POI实现将数据导出到Excel

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

java数据导出到Excel Java中用POI实现将数据导出到Excel

忆晨丶   2021-04-22 我要评论
想了解Java中用POI实现将数据导出到Excel的相关内容吗,忆晨丶在本文为您仔细讲解java数据导出到Excel的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:java数据导出到Excel,Java,POI数据导出,Java,POI,Excel,下面大家一起来学习吧。

一、前言

数据导出为Excel在我们写项目的过程中经常用到

需要用到的jar包 poi-3.17.jar

二、具体实现步骤

//第一步创建一个webbook,对应一个Excel文件
	HSSFWorkbook wb=new HSSFWorkbook();
	//第二步,在webbook中添加一个sheet,对应Excel文件中的sheet
	HSSFSheet sheet=wb.createSheet("食物信息数据");
	//第三步,在sheet中添加表头第0行
	HSSFRow row = sheet.createRow(0);
	//第四步,创建单元格,并设置表头居中
	HSSFCellStyle style = wb.createCellStyle();
	style.setAlignment(HorizontalAlignment.CENTER);//居中格式
	HSSFCell cell = row.createCell(0);
	cell.setCellValue("编号");
	cell.setCellStyle(style);
	
	cell=row.createCell((short)1);
	cell.setCellValue("名称");
	cell.setCellStyle(style);
	
	cell=row.createCell((short)2);
	cell.setCellValue("类型");
	cell.setCellStyle(style);
	
	cell=row.createCell((short)3);
	cell.setCellValue("单价");
	cell.setCellStyle(style);
	
	cell=row.createCell((short)4);
	cell.setCellValue("库存");
	cell.setCellStyle(style);
	
	//第五步,写入实体数据,从数据库拿数据
	FoodController controller=new FoodController();
	List<Foods> foodsList = controller.foodsList(null, null);
	for (int i = 0; i < foodsList.size(); i++) {
		//创建单元格,并赋值
		row=sheet.createRow(i+1);
		Foods foods = foodsList.get(i);
		row.createCell((short)0).setCellValue(foods.getId());
		row.createCell((short)1).setCellValue(foods.getName());
		row.createCell((short)2).setCellValue(foods.getType());
		row.createCell((short)3).setCellValue(foods.getPrice());
		row.createCell((short)4).setCellValue(foods.getNum());
	}
	//第六步,下载Excel
	OutputStream out=null;
	out=response.getOutputStream();
	String fileName="食物信息.xls";
	response.setContentType("application/x-=msdownload");
	response.setHeader("Content-Disposition", "attachment; filename="
			+URLEncoder.encode(fileName, "UTF-8"));
	wb.write(out);

三、实现效果图

导出成功后数据成功显示

在这里插入图片描述

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们