实战练习之java导出Excel方法封装

2019-06-15 00:00:00 实战 导出 封装

本文
使用poi实现导出Excel,本文将要输入的参数提取出来,封装成公用方法,重点是对导出文件的内容进行的处理。将要输出的数据存放在List中,以键(数据库对应字段名称)值(对应数据)对的形式传给封装的公用方法,同时将每一列展示的字段对应的数据库字段名称一次存放在Listfields中,根据fields中存放的字段名称找到map中对应的值,从而实现各种Bean都可以调用此方法实现导出,摆脱了限制。
环境中使用maven管理java包,对pom.xml进行如下配置,导入需要的包。

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

toExcel是封装的导出Excel的方法,main函数调用实现。
对输出的内容封装时处理时间和数字是用的标记。
一般数据库时间的字段起名最后一个单词会是Time,所以利用这个通性,判断传入的字段名称如果包含Time这个单词就默认为时间,将数据进行特殊处理在存入到excel的列中。(如果有幕友有更好的方法欢迎指教)

package com.lhzs;

import java.io.FileOutputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

public class CreateExcel {

	public static void toExcel(String sheetName, List<String> headers,
			List<String> fields, List<Map> contentList, String filePath) {
		HSSFWorkbook wb = new HSSFWorkbook();
		HSSFSheet sheet = wb.createSheet(sheetName);
		HSSFRow row = sheet.createRow((int) 0);// 表头
		HSSFCellStyle style = wb.createCellStyle(); 
		style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);  
		style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
		HSSFCell cell;
		// 表头
		for (int i = 0; i < headers.size(); i++) {
			cell = row.createCell((short) i);
			cell.setCellValue(headers.get(i));
			cell.setCellStyle(style);
		}
		// 内容
		for (int i = 0; i < contentList.size(); i++) {
			row = sheet.createRow((int) i + 1);
			Map content = contentList.get(i);
			for (int j = 0; j < fields.size(); j++) {
				if (null != content.get(fields.get(j))) {
					// 时间字段
					if (fields.get(j).indexOf("Time") != -1) {
						Date date = new Date();
						DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
						row.createCell(j).setCellValue(
								sdf.format(content.get(fields.get(j))));
					}
					// 数字
					else if (fields.get(j).indexOf("Amount") != -1) {
						row.createCell(j).setCellValue(
								(double) content.get(fields.get(j)));
					} else {
						row.createCell(j).setCellValue(
								String.valueOf(content.get(fields.get(j))));
					}

				} else {
					row.createCell(j).setCellValue("");
				}
			}

		}

		try {
			FileOutputStream fout = new FileOutputStream(filePath);
			wb.write(fout);
			fout.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public static void main(String[] args) throws Exception {

		List<String> headers = new ArrayList<>();
		headers.add("学号");
		headers.add("姓名");
		headers.add("年龄");
		headers.add("生日");
		headers.add("分数");

		List<String> fields = new ArrayList<>();
		fields.add("id");
		fields.add("name");
		fields.add("age");
		fields.add("birthTime");
		fields.add("scoreAmount");

		List<Student> studentList = new ArrayList<Student>();
		SimpleDateFormat df = new SimpleDateFormat("yyyy-mm-dd");

		Student user1 = new Student(1, "张三", 11.0, df.parse("1996-08-12"),
				345.66);

		Student user2 = new Student(2, "李四", 23.5, df.parse("1996-07-12"), 456);
		Student user3 = new Student(3, "王五", 45.10, df.parse("1996-09-12"),
				878.98);
		studentList.add(user1);
		studentList.add(user2);
		studentList.add(user3);

		List<Map> contentList = new ArrayList<Map>();

		for (Student stu : studentList) {
			Map a = new HashMap<>();
			a.put("id", stu.getId());
			a.put("name", stu.getName());
			a.put("age", stu.getAge());
			a.put("birthTime", stu.getBirthTime());
			a.put("scoreAmount", stu.getScoreAmount());
			contentList.add(a);
		}

		String filePath = "E:/test3.xls";

		toExcel("页面1", headers, fields, contentList, filePath);

	}

}

Student.java 简单的javabean

package com.lhzs;

import java.util.Date;

 

public class Student {
	 private int id;  
	    private String name;  
	    private double age;  
	    private Date birthTime;  
	    private double scoreAmount;
	     
	    public Student(int id, String name, double age, Date date,double score)  
	    {  
	        this.id = id;  
	        this.name = name;  
	        this.age = age;  
	        this.birthTime =  date;  
	        this.scoreAmount = score;
	    } 

		public int getId() {
			return id;
		} 

		public void setId(int id) {
			this.id = id;
		} 

		public String getName() {
			return name;
		}

		public void setName(String name) {
			this.name = name;
		} 

		public double getAge() {
			return age;
		} 

		public void setAge(double age) {
			this.age = age;
		} 

		public Date getBirthTime() {
			return birthTime;
		}
 

		public void setBirthTime(Date birthTime) {
			this.birthTime = birthTime;
		}
 

		public double getScoreAmount() {
			return scoreAmount;
		} 

		public void setScoreAmount(double scoreAmount) {
			this.scoreAmount = scoreAmount;
		}
 
	   
}

相关文章