maven依赖
org.apache.poi
poi-ooxml
3.14
ExportUtil.java:
package com.parsec.customs.util;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.lang.reflect.Field;
import java.util.List;
/**
* Created by wuhao on 13/06/2017.
*/
public class ExportUtil {
/**
* 导出成excel
*
* @param titles 表头
* @param list 数据
* @param field 在类里的属性名
* @param clazz 具体类型
* @param
* @return
*/
public static XSSFWorkbook export(String[] titles, List list, String[] field, Class clazz) {
try {
XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = wb.createSheet();
XSSFRow row = sheet.createRow(0);
for (int i = 0; i < titles.length; i++) {
row.createCell(i).setCellValue(titles[i]);
}
for (int i = 1; i <= list.size(); i++) {
XSSFRow hssfRow = sheet.createRow(i);
// clazz = (Class) list.get(i - 1).getClass();
for (int j = 0; j < field.length; j++) {
Field declaredField = clazz.getDeclaredField(field[j]);
declaredField.setAccessible(true);
if (declaredField.getType().toString().equals("int")) {
hssfRow.createCell(j).setCellValue(declaredField.getInt(list.get(i - 1)));
} else {
String str = "" + declaredField.get(list.get(i - 1));
hssfRow.createCell(j).setCellValue("null".equals(str) ? "" : str);
}
}
}
return wb;
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return null;
}
/**
* 导出成csv
*
* @see ExportUtil.export
*
* @param titles
* @param list
* @param field
* @param clazz
* @param
* @return
*/
public static String exportToCsv(String[] titles, List list, String[] field, Class clazz) {
try {
StringBuffer csvStr = new StringBuffer();
for (String title : titles) {
csvStr.append(title + ",");
}
csvStr.append("\n");
for (int i = 1; i <= list.size(); i++) {
for (int j = 0; j < field.length; j++) {
Field declaredField = clazz.getDeclaredField(field[j]);
declaredField.setAccessible(true);
if (declaredField.getType().toString().equals("int")) {
csvStr.append(declaredField.getInt(list.get(i - 1))).append(",");
} else {
String str = "" + declaredField.get(list.get(i - 1));
csvStr.append("null".equals(str) ? "" : str).append(",");
}
}
csvStr.append("\n");
}
return csvStr.toString();
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return null;
}
}
How to use?
List likeSendIdRecords = ...;
XSSFWorkbook export = ExportUtil.export(new String[]{"总运单号", "申报日期", "集中数字", "相似占比"}, likeSendIdRecords, new String[]{"voyageNo", "dDate", "idkey", "rate"}, LikeSendIdRecord.class);
下载文件的代码参考
response.setHeader("Content-disposition", "attachment; filename*=utf-8\'zh_cn\'" + file + ".xlsx");
response.setContentType("application/vnd.ms-excel;charset=UTF-8");
try {
export.write(response.getOutputStream());
response.getOutputStream().flush();
} catch (IOException e) {
e.printStackTrace();
}