JavaBean数据导出excel与csv文件

/**

导出excel文件,文件操作使用Apache POI框架

**/

public static <E> void exportExcel(HttpServletResponse response, String[] header, int[] column, String[] fileNames, List<E> list, String excelName) {
// 创建工作簿
HSSFWorkbook wb = new HSSFWorkbook();
// 创建一个sheet
HSSFSheet sheet = wb.createSheet(excelName);

HSSFRow headerRow = sheet.createRow(0);
HSSFRow contentRow = null;

// 设置标题
for (int i = 0; i < header.length; i++) {
headerRow.createCell(i).setCellValue(header[i]);
if (column != null) {
sheet.setColumnWidth(i, column[i]);
}
}
try {
int size = list.size();
for (int i = 0; i < size; i++) {
contentRow = sheet.createRow(i + 1);
// 获取每一个对象
E o = list.get(i);
Class cls = o.getClass();
for (int j = 0; j < fileNames.length; j++) {
String fieldName = fileNames[j].substring(0, 1).toUpperCase() + fileNames[j].substring(1);
Method getMethod;
try {
getMethod = cls.getMethod("get" + fieldName);
Object value = getMethod.invoke(o);
if (value != null) {
contentRow.createCell(j).setCellValue(value.toString());
}
} catch (NoSuchMethodException e) {
contentRow.createCell(j).setCellValue(i+1);
}

}
}
} catch (IllegalArgumentException e) {
logger.error("", e);
} catch (IllegalAccessException e) {
logger.error("", e);
} catch (InvocationTargetException e) {
logger.error("", e);
} catch (SecurityException e) {
logger.error("", e);
}

OutputStream os = null;
try {
response.reset();
response.addHeader("Content-Disposition", "attachment;filename=" + new String((excelName + ".xlsx").getBytes(), "iso-8859-1"));
response.setContentType("application/vnd.ms-excel;charset=utf-8");
os = response.getOutputStream();
wb.write(os);
} catch (Exception e) {
logger.error("", e);
} finally {
IOUtil.close(os);
}
}

 

/**

导出csv文件,文件操作使用univocity框架

**/

public static <E> void exportCsv(HttpServletResponse response, String[] header, int[] column, String[] fileNames, List<E> list, String csvName){

OutputStream os = null;
CsvWriter writer = null;
try {
response.reset();
response.addHeader("Content-Disposition", "attachment;filename=" + new String((csvName + ".csv").getBytes(), "iso-8859-1"));
response.setContentType("application/vnd.ms-excel;charset=utf-8");
os = response.getOutputStream();
writer = new CsvWriter(os, new CsvWriterSettings());
writer.writeHeaders(header);
int size = list.size();
for (int i = 0; i < size; i++) {
String[] content = new String[size];
// 获取每一个对象
E o = list.get(i);
Class cls = o.getClass();
for (int j = 0; j < fileNames.length; j++) {
String fieldName = fileNames[j].substring(0, 1).toUpperCase() + fileNames[j].substring(1);
Method getMethod;
try {
getMethod = cls.getMethod("get" + fieldName);
Object value = getMethod.invoke(o);
if (value != null) {
content[i] = value.toString();
}
} catch (NoSuchMethodException e) {
content[i] = "";
}
}
writer.writeRow(content);
}
} catch (Exception e) {
logger.error("", e);
} finally {
writer.close();
IOUtil.close(os);
}
}

 

posted @ 2017-10-24 11:52  JhonMr  阅读(1536)  评论(0编辑  收藏  举报