在项目开发的过程中,少不了要把数据导入导出,把数据导出到Excel文档中又是经常使用的。本篇文章将介绍一个Java提供的POI来实现把数据导出到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);

三、实现效果图

导出成功后数据成功显示

以上就是关于Java中POI的使用,以及使用POI导出数据到Excel的步骤,想要了解更多Java POI导出数据到其他文档文件的内容,可以浏览W3Cschool相关技术文章,希望本篇文章能够对大家的学习有所帮助!

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。