生成xls、和xlsx写法一致,只是xls用的HSSF、xlsx用的XSSF
org.apache.poi
poi
3.16
org.apache.poi
poi-ooxml
3.16
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
* @param title 文件名
* @param headers 列标题
* @param dataset 数据内容
* @param pattern 时间格式
*/
@SuppressWarnings("unchecked")
public static void exportXlsExcel(String[] headers, List 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 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
* @param title 文件名
* @param headers 列标题
* @param dataset 数据内容
* @param pattern 时间格式
*/
public static void exportXlsxExcel(String[] headers, List 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 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();
}
}
}