使用POI工具将数据库的数据导出生成Excel表格

版权声明:本文为博主原创文章,转载请说明出处。 https://blog.csdn.net/qq_42361748/article/details/88709846
package com.shang;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.util.CellRangeAddress;

/**
 * @author shang
 * 
 * @date 2019年3月21日
 **/
public class POIUtil<T> {

	/**
	 * 生成表格的工具类
	 * @param list	获取到的对象集合
	 * @param param	需要打印的属性名(列名) 全部打印则为NULL
	 * @param title	表格的标题
	 * @param sheetName	表格文件的名字
	 * @param request	HttpServletRequest
	 * @return	String 服务器下载路径
	 * @throws IntrospectionException
	 * @throws IllegalAccessException
	 * @throws IllegalArgumentException
	 * @throws InvocationTargetException
	 * @throws IOException
	 */
	public String download(List<T> list, String[] param, String title, String sheetName, HttpServletRequest request)
			throws IntrospectionException, IllegalAccessException, IllegalArgumentException, InvocationTargetException,
			IOException {
		if (list != null) {
			// 获得集合中的第一个对象
			Object o = list.get(0);
			//
			Field[] fields = o.getClass().getDeclaredFields();
			// 获取对象的属性长度
			int length = fields.length;
			// 新建一个用来存储属性名的数组
			String[] propertyName = new String[length];
			// 新建一个用来存储属性类型的数组
			String[] propertyType = new String[length];
			// 遍历field数组,调用其中的getName,getType方法
			for (int i = 0; i < length; i++) {
				propertyName[i] = fields[i].getName();
				propertyType[i] = fields[i].getType().toString();

			}
			// 如果需要全部打印即param==null||param.length()==0;
			if (param == null || param.length == 0) {
				param = new String[propertyName.length];
				for (int i = 0; i < propertyName.length; i++) {
					param[i] = propertyName[i];
				}
			}
			// 创建表
			// 设置文件生成的路径
			// String path = "RentalManage/WebContent/files";
			String path = request.getSession().getServletContext().getRealPath("/files");
			System.out.println(path);
			// 获取file
			File file = new File(path);
			// 判断文件夹是否存在,若不存在就自动生成
			if (!file.exists()) {
				file.mkdirs();
			}
			// 获取工作簿
			HSSFWorkbook workbook = new HSSFWorkbook();
			// 创建工作表
			HSSFSheet sheet = workbook.createSheet();
			// 创建标题
			CellRangeAddress rangeAddress = new CellRangeAddress(0, 0, 0, param.length - 1);
			sheet.addMergedRegion(rangeAddress);
			HSSFRow titleRow = sheet.createRow(0);
			// 设置行高
			titleRow.setHeightInPoints(30);
			// 创建标题单元格
			HSSFCell titleCell = titleRow.createCell(0);
			// 创建标题栏的样式
			HSSFCellStyle titleCellStyle = workbook.createCellStyle();
			// 设置水平居中
			titleCellStyle.setAlignment(HorizontalAlignment.CENTER);
			// 设置垂直居中
			titleCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
			// 创建字体样式对象
			HSSFFont font = workbook.createFont();
			// 是否粗体
			font.setBold(true);
			// 设置字体大小
			font.setFontHeightInPoints((short) 20);
			// 将字体设置进样式
			titleCellStyle.setFont(font);
			// 将样式设置进单元格
			titleCell.setCellStyle(titleCellStyle);
			// 将标题设置进表格
			titleCell.setCellValue(title);
			for (int i = -1; i < list.size(); i++) {
				// 创建行
				HSSFRow row = sheet.createRow(i + 2);
				// 设置行高
				row.setHeightInPoints(22);
				int n = 0;
				for (int j = 0; j < propertyType.length; j++) {

					for (int k = 0; k < param.length; k++) {
						if (param[k] == propertyName[j]) {
							// 创建单元格
							HSSFCell cell = row.createCell(n);
							n++;
							// 创建表头
							if (i == -1) {
								//创建表头样式
								HSSFCellStyle headStyle = workbook.createCellStyle();
								//创建表头字体
								HSSFFont headFont = workbook.createFont();
								//设置粗体
								headFont.setBold(true);
								//设置字体大小
								headFont.setFontHeightInPoints((short)18);
								//将字体设置进样式
								cell.setCellStyle(headStyle);
								//设置表头字体
								headStyle.setFont(headFont);
								//将表头写入内容
								cell.setCellValue(propertyName[j]);
							} else {
								// 创建表格内容
								HSSFCellStyle style = workbook.createCellStyle();
								// 判断该单元格类型为时间类型
								if ("date".equalsIgnoreCase(propertyType[j])
										|| "timestamp".equalsIgnoreCase(propertyType[j])) {
									// 设置单元格的属性为时间
									style.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy h:mm"));
									// 设置单元格类型
									cell.setCellStyle(style);
								}
								// 判断该单元格类型为小数
								if ("double".equalsIgnoreCase(propertyType[j])) {
									// 设置单元格属性为小数类型
									style.setDataFormat(HSSFDataFormat.getBuiltinFormat("0.00"));
									// 设置单元格类型
									cell.setCellStyle(style);
								}

								// 设置单元格内容
								// 内容部分基本样式
								// 设置水平居中
								style.setAlignment(HorizontalAlignment.CENTER);
								// 设置垂直居中
								style.setVerticalAlignment(VerticalAlignment.CENTER);
								// 为表格添加边框
								style.setBorderBottom(BorderStyle.THIN);
								style.setBorderLeft(BorderStyle.THIN);
								style.setBorderRight(BorderStyle.THIN);
								style.setBorderTop(BorderStyle.THIN);
								// 获得字体对象
								HSSFFont bodyFont = workbook.createFont();
								// 设置字体大小
								bodyFont.setFontHeightInPoints((short) 16);
								// 将字体设置进样式
								style.setFont(bodyFont);
								// 将样式设置进单元格
								cell.setCellStyle(style);
								// 获取给类的方法
								PropertyDescriptor descriptor = new PropertyDescriptor(
										list.get(i).getClass().getDeclaredFields()[j].getName(), o.getClass());
								// 获得集合中的get方法
								Method getMethod = descriptor.getReadMethod();
								// 判断数据类型并对使用get方法得到的数据进行类型转换
								if ("class java.lang.String".equalsIgnoreCase(propertyType[j])) {
									String invoke = (String) getMethod.invoke(list.get(i));
									cell.setCellValue(invoke);
								}
								// 如果该属性类型为int则将get方法取回的的值转换为int(Integer)类型
								if ("int".equalsIgnoreCase(propertyType[j])) {
									Integer invoke = (Integer) getMethod.invoke(list.get(i));
									cell.setCellValue(invoke);
								}
								// 如果该属性类型为double则将get方法取回的的值转换为double(Double)类型
								if ("double".equalsIgnoreCase(propertyType[j])) {
									Double invoke = (Double) getMethod.invoke(list.get(i));
									cell.setCellValue(invoke);
								}
								// 如果该属性类型为date则将get方法取回的的值转换为Date类型
								if ("class java.util.Date".equalsIgnoreCase(propertyType[j])) {
									Date invoke = (Date) getMethod.invoke(list.get(i));
									cell.setCellValue(invoke);
								}
								// 如果该属性类型为timestamp则将get方法取回的的值转换为Date类型
								if ("timestamp".equalsIgnoreCase(propertyType[j])) {
									Date invoke = (Timestamp) getMethod.invoke(list.get(i));
									cell.setCellValue(invoke);
								}
							}
						}
					}
				}
			}
			for (int k = 0; k < param.length; k++) {
				// 设置自适应列宽
				sheet.autoSizeColumn(k);
			}
			// 设置默认行高
			// sheet.setDefaultRowHeightInPoints(25);

			// 获取输出流对象
			FileOutputStream out = new FileOutputStream(path + "/" + sheetName + ".xls");
			// 写入
			workbook.write(out);
			// 关闭流对象
			out.close();
			// 获取服务器路径
			String scheme = request.getScheme();
			String contextPath = request.getContextPath();
			String BasePath = scheme + "://" + request.getServerName() + ":" + request.getServerPort() + contextPath
					+ "/files/" + sheetName + ".xls";

			return BasePath;
		}

		return null;
	}

}

猜你喜欢

转载自blog.csdn.net/qq_42361748/article/details/88709846