POI導出excel文件

生成xls、和xlsx寫法一致,只是xls用的HSSF、xlsx用的XSSF

需要引入的包

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

代碼

package com.tjsoft.tool;

import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
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.HorizontalAlignment;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ExcelUtil {

	/**
	 * 生成xls表格
	 * @param <T>
	 * @param title   文件名
	 * @param headers 列標題
	 * @param dataset 數據內容
	 * @param pattern 時間格式
	 */
	@SuppressWarnings("unchecked")
	public static <T> void exportXlsExcel(String[] headers, List<T> dataset, String pattern,HttpServletResponse response) {

		// 第一步,創建一個HSSFWorkbook,對應一個Excel文件
		HSSFWorkbook wb = new HSSFWorkbook();

		// 第二步,在workbook中添加一個sheet,對應Excel文件中的sheet
		//文件名
		String title =CTools.getNewID()+".xls";
		HSSFSheet sheet = wb.createSheet(title);
		sheet.setDefaultColumnWidth(35);
		
		// 第三步,在sheet中添加表頭第0行,產生表格標題行,注意老版本poi對Excel的行數列數有限制
		HSSFRow row = sheet.createRow(0);

		// 第四步,創建單元格,並設置值表頭 設置表頭居中
		HSSFCellStyle style = wb.createCellStyle();
		style.setAlignment(HorizontalAlignment.CENTER); // 創建一個居中格式

		// 聲明列對象
		HSSFCell cell = null;

		// 創建標題
		for (int i = 0; i < headers.length; i++) {
			cell = row.createCell(i);
			cell.setCellValue(headers[i]);
			cell.setCellStyle(style);
		}

		// 遍歷集合數據,產生數據行
		Iterator<T> it = dataset.iterator();
		int index = 0;
		while (it.hasNext()) {
			index++;
			row = sheet.createRow(index);
			T t = (T) it.next();
			// 利用反射,根據javabean屬性的先後順序,動態調用getXxx()方法得到屬性值
			Field[] fields = t.getClass().getDeclaredFields();
			for (int i = 0; i < fields.length; i++) {
				cell = row.createCell(i);
				Field field = fields[i];
				String fieldName = field.getName();
				String getMethodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
				Class tCls = t.getClass();
				try {
					Method getMethod = tCls.getMethod(getMethodName, new Class[] {});
					Object value = getMethod.invoke(t, new Object[] {});
					String textValue = null;
					if (value instanceof Integer) {
						int intValue = (Integer) value;
						cell.setCellValue(intValue);
					} else if (value instanceof Long) {
						long longValue = (Long) value;
						cell.setCellValue(longValue);
					} else if (value instanceof Boolean) {
						boolean bValue = (Boolean) value;
						textValue = "1";
						if (!bValue) {
							textValue = "0";
						}
					} else if (value instanceof Date) {
						Date date = (Date) value;
						if(!CTools.isBlank(pattern)) {
							pattern="yyyy-MM-dd HH:mm:ss";
						}
						SimpleDateFormat sdf = new SimpleDateFormat(pattern);
						textValue = sdf.format(date);
					} else {
						// 其它數據類型都當作字符串簡單處理
						if (value == null) {
							textValue = "";
						} else {
							textValue = value.toString();
						}

					}

					if (textValue != null) {
						
						Pattern p = Pattern.compile("^//d+(//.//d+)?$");
						Matcher matcher = p.matcher(textValue);
						if (matcher.matches()) {
							// 是數字當作double處理
							cell.setCellValue(Double.parseDouble(textValue));
						} else {
							HSSFRichTextString richString = new HSSFRichTextString(textValue);
							cell.setCellValue(richString);
						}
					}
				} catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException
						| InvocationTargetException e) {
					e.printStackTrace();
				}

			}
		}
		
		try {
			String fileName = new String(title.getBytes("utf-8"));
			response.setContentType("application/octet-stream;charset=utf-8");
			response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
			response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
			OutputStream os = response.getOutputStream();
			wb.write(os);
			os.flush();
			os.close();
		} catch (IOException  e) {
			e.printStackTrace();
		}
		
	}
	
	/**
	 * 生成xlsx表格
	 * @param <T>
	 * @param title   文件名
	 * @param headers 列標題
	 * @param dataset 數據內容
	 * @param pattern 時間格式
	 */
	public static <T> void exportXlsxExcel(String[] headers, List<T> dataset, String pattern,HttpServletResponse response) {
		// 第一步,創建一個HSSFWorkbook,對應一個Excel文件
				XSSFWorkbook  wb = new XSSFWorkbook();

				// 第二步,在workbook中添加一個sheet,對應Excel文件中的sheet
				//文件名
				String title =CTools.getNewID()+".xlsx";
				XSSFSheet  sheet = wb.createSheet(title);
				sheet.setDefaultColumnWidth(35);
				
				// 第三步,在sheet中添加表頭第0行,產生表格標題行,注意老版本poi對Excel的行數列數有限制
				XSSFRow row = sheet.createRow(0);

				// 第四步,創建單元格,並設置值表頭 設置表頭居中
				XSSFCellStyle style = wb.createCellStyle();
				style.setAlignment(HorizontalAlignment.CENTER); // 創建一個居中格式
				
				// 聲明列對象
				XSSFCell cell = null;

				// 創建標題
				for (int i = 0; i < headers.length; i++) {
					cell = row.createCell(i);
					cell.setCellValue(headers[i]);
					cell.setCellStyle(style);
				}

				// 遍歷集合數據,產生數據行
				Iterator<T> it = dataset.iterator();
				int index = 0;
				while (it.hasNext()) {
					index++;
					row = sheet.createRow(index);
					T t = (T) it.next();
					// 利用反射,根據javabean屬性的先後順序,動態調用getXxx()方法得到屬性值
					Field[] fields = t.getClass().getDeclaredFields();
					for (int i = 0; i < fields.length; i++) {
						cell = row.createCell(i);
						Field field = fields[i];
						String fieldName = field.getName();
						String getMethodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
						Class tCls = t.getClass();
						try {
							Method getMethod = tCls.getMethod(getMethodName, new Class[] {});
							Object value = getMethod.invoke(t, new Object[] {});
							String textValue = null;
							if (value instanceof Integer) {
								int intValue = (Integer) value;
								cell.setCellValue(intValue);
							} else if (value instanceof Long) {
								long longValue = (Long) value;
								cell.setCellValue(longValue);
							} else if (value instanceof Boolean) {
								boolean bValue = (Boolean) value;
								textValue = "1";
								if (!bValue) {
									textValue = "0";
								}
							} else if (value instanceof Date) {
								Date date = (Date) value;
								if(!CTools.isBlank(pattern)) {
									pattern="yyyy-MM-dd HH:mm:ss";
								}
								SimpleDateFormat sdf = new SimpleDateFormat(pattern);
								textValue = sdf.format(date);
							} else {
								// 其它數據類型都當作字符串簡單處理
								if (value == null) {
									textValue = "";
								} else {
									textValue = value.toString();
								}

							}

							if (textValue != null) {
								Pattern p = Pattern.compile("^//d+(//.//d+)?$");
								Matcher matcher = p.matcher(textValue);
								if (matcher.matches()) {
									// 是數字當作double處理
									cell.setCellValue(Double.parseDouble(textValue));
								} else {
									XSSFRichTextString richString = new XSSFRichTextString(textValue);
									cell.setCellValue(richString);
								}
							}
						} catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException
								| InvocationTargetException e) {
							e.printStackTrace();
						}

					}
				}
				
				try {
					String fileName = new String(title.getBytes("utf-8"));
					response.setContentType("application/octet-stream;charset=utf-8");
					response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
					OutputStream os = response.getOutputStream();
					wb.write(os);
					os.flush();
					os.close();
				} catch (IOException  e) {
					e.printStackTrace();
				}
	}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章