通过使用poi技术生成Excel,使用反射技术实现自动映射列表的数据。

ExportTableUtil.java

public class ExportTableUtil {

	/**
*
* @Description: 获取csv格式的字符串
* @param @param 表格头
* @param @param fieldNameList 对应的属性名 按照先后与表头对应而且值与数据类型的属性名对应
* @param @param params 数据
* @param @return
* @param @throws IllegalArgumentException
* @param @throws IllegalAccessException
* @param @throws NoSuchFieldException
* @param @throws SecurityException 设定文件
* @return String 返回类型
*/
public static String csv(String[] headList, String[] fieldNameList, List<?> params) throws IllegalArgumentException, IllegalAccessException,
NoSuchFieldException, SecurityException {
StringBuilder stringBuilder = new StringBuilder();
// add head on first
for (int i = 0; null != headList && i < headList.length; i++) {
stringBuilder.append(headList[i]);
if (i < headList.length - 1) {
stringBuilder.append(",");
} else {
stringBuilder.append("\r\n");
}
}
// add data from second line to ---
for (int i = 0; null != params && i < params.size(); i++) {
Class<? extends Object> clazz = params.get(i).getClass();
for (int j = 0; null != fieldNameList && j < fieldNameList.length; j++) {
String fieldName = fieldNameList[j];
if (!fieldName.contains(".")) {
Field field = clazz.getDeclaredField(fieldName);
if (null != field) {
field.setAccessible(true);
Object obj = field.get(params.get(i));
if (null != obj) {
stringBuilder.append(obj.toString());
}
} else {
stringBuilder.append("");
}
if (j < fieldNameList.length - 1) {
stringBuilder.append(",");
}
}else{
Object param = params.get(i);
Object valObj = vectorObj(clazz, fieldName, param);
if(null!=valObj){
stringBuilder.append(valObj.toString());
}else {
stringBuilder.append("");
}
if (j < fieldNameList.length - 1) {
stringBuilder.append(",");
}
}
}
stringBuilder.append("\r\n");
} return stringBuilder.toString();
} /**
*
* @Description: 通过response下载文档
* @param @param response
* @param @param fileName
* @param @param headList
* @param @param fieldNameList
* @param @param params 设定文件
* @return void 返回类型
*/
public static void httpExportCSV(HttpServletRequest request, HttpServletResponse response, String fileName, String[] headList,
String[] fieldNameList, List<?> params) {
Map<String, Object> map = new HashMap<String, Object>();
try {
response.setCharacterEncoding("UTF-8");
response.setContentType("application/x-download");
final String userAgent = request.getHeader("USER-AGENT");
String csvContent = csv(headList, fieldNameList, params);
String finalFileName = null;
if (StringUtils.contains(userAgent, "MSIE")) {// IE浏览器
finalFileName = URLEncoder.encode(fileName, "UTF8");
} else if (StringUtils.contains(userAgent, "Mozilla")) {// google,火狐浏览器
finalFileName = new String(fileName.getBytes(), "ISO8859-1");
} else {
finalFileName = URLEncoder.encode(fileName, "UTF8");// 其他浏览器
} response.setHeader("Content-Disposition", "attachment; filename=\"" + finalFileName + "\"");
response.getOutputStream().write(csvContent.getBytes());
} catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException | SecurityException | IOException e) { e.printStackTrace();
map.put("state", "202");
map.put("message", "数据转换异常");
try {
response.getOutputStream().write(JSONUtils.toJSONString(map).getBytes());
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
} } /**
*
* @Description: 得到excel表的二进制流
* @param @param headList 表头
* @param @param fieldNameList 属性名按照表头先后顺序对应而且必须在数据类型中存在属性名与之对应
* @param @param params
* @param @return
* @param @throws IllegalArgumentException
* @param @throws IllegalAccessException
* @param @throws NoSuchFieldException
* @param @throws SecurityException
* @param @throws IOException 设定文件
* @return byte[] 返回类型
*/
public static byte[] xls(String[] headList, String[] fieldNameList, List<?> params) throws IllegalArgumentException, IllegalAccessException,
NoSuchFieldException, SecurityException, IOException {
Workbook work = new HSSFWorkbook();
Sheet sheet = work.createSheet();
Row rowOne = sheet.createRow(0);
for (int i = 0; null != headList && i < headList.length; i++) {// 表头
Cell cellOne = rowOne.createCell(i);
cellOne.setCellValue(headList[i]);// 填充值
} // 数据填充
for (int i = 0; null != params && i < params.size(); i++) {
Class<? extends Object> clazz = params.get(i).getClass();
Row dataRow = sheet.createRow(i + 1);
for (int j = 0; null != fieldNameList && j < fieldNameList.length; j++) {
String fieldName = fieldNameList[j];
Cell cell = dataRow.createCell(j);
if (!fieldName.contains(".")) {
Field field = clazz.getDeclaredField(fieldName);
field.setAccessible(true);
Object obj = field.get(params.get(i));
if (null != obj) { if (obj instanceof String) {
cell.setCellValue(obj.toString());
} else if (obj instanceof Double) {
cell.setCellValue((double) obj);
} else if (obj instanceof Boolean) {
cell.setCellValue((boolean) obj);
} else if (obj instanceof Date) {
cell.setCellValue((Date) obj);
} else {
cell.setCellValue(obj.toString());
}
}
} else if (fieldName.contains(".")) {
Object param = params.get(i);
Object valObj = vectorObj(clazz, fieldName, param); cell.setCellValue(null == valObj ? null : valObj.toString());
} } }
ByteOutputStream bos = new ByteOutputStream();
work.write(bos);
work.close();
return bos.getBytes();
} private static Object vectorObj(Class<? extends Object> clazz, String fieldName, Object obj) throws NoSuchFieldException, SecurityException,
IllegalArgumentException, IllegalAccessException {
if (!fieldName.contains(".")) {
Field field = clazz.getDeclaredField(fieldName);
field.setAccessible(true);
return field.get(obj);
} else {
String fieldChildName = fieldName.substring(0, fieldName.indexOf("."));
Object newObj = null;
if (null != fieldChildName) { Field field = clazz.getDeclaredField(fieldChildName);
field.setAccessible(true);
newObj = field.get(obj);
if (newObj == null) {
return null; } else {
Class<? extends Object> clazz2 = newObj.getClass();
String fieldOtherChildName = fieldName.substring(fieldName.indexOf(".") + 1);
return vectorObj(clazz2, fieldOtherChildName, newObj);
} }
return null;
} } /**
*
* @Description: 导出xls表-------------从第一列开始
* @param @param request
* @param @param response
* @param @param fileName 文件名
* @param @param headList 表头
* @param @param fieldNameList 属性名 和按照表头先后顺序对应,值和数据列表中对象类型的属性名相同
* @param @param params 设定文件
* @return void 返回类型
*/
public static void httpExportXLS(HttpServletRequest request, HttpServletResponse response, String fileName, String[] headList,
String[] fieldNameList, List<?> params) {
Map<String, Object> map = new HashMap<String, Object>();
try {
response.setCharacterEncoding("UTF-8");
response.setContentType("application/x-download");
final String userAgent = request.getHeader("USER-AGENT");
byte[] xlsContent = xls(headList, fieldNameList, params);
String finalFileName = null;
if (StringUtils.contains(userAgent, "MSIE")) {// IE浏览器
finalFileName = URLEncoder.encode(fileName, "UTF8");
} else if (StringUtils.contains(userAgent, "Mozilla")) {// google,火狐浏览器
finalFileName = new String(fileName.getBytes(), "ISO8859-1");
} else {
finalFileName = URLEncoder.encode(fileName, "UTF8");// 其他浏览器
} response.setHeader("Content-Disposition", "attachment; filename=\"" + finalFileName + "\"");
response.getOutputStream().write(xlsContent);
} catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException | SecurityException | IOException e) { e.printStackTrace();
map.put("state", "202");
map.put("message", "数据转换异常");
try {
response.getOutputStream().write(JSONUtils.toJSONString(map).getBytes());
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
} /**
*
* @Description: 根据路径的后缀名导出对应的文件
* @param @param request
* @param @param response
* @param @param fileName------------文件名(格式*.xls,*.csv)
* @param @param headList--------------表格头部内容
* @param @param fieldNameList----------属性名和数据列表中类型的属性名相同,通过先后循序和表头对应。
* @param @param params--------------数据
* @param @throws Exception ----文件名不合法
* @return void 返回类型
*/
public static void httpExport(HttpServletRequest request, HttpServletResponse response, String fileName, String[] headList,
String[] fieldNameList, List<?> params) throws Exception {
if (null == fileName || StringUtils.isEmpty(fileName)) {
throw new NullPointerException("文件名不可以为空");
} else {
String suffix = fileName.substring(fileName.indexOf(".") + 1);
if (null != suffix) {
System.out.println(suffix);
switch (suffix) {
case "csv":
httpExportCSV(request, response, fileName, headList, fieldNameList, params);
break;
case "xls":
httpExportXLS(request, response, fileName, headList, fieldNameList, params);
break;
case "xlsx":
httpExportXLS(request, response, fileName, headList, fieldNameList, params);
break;
case "doc":
break;
case "docx":
break;
case "pdf":
break;
}
} else {
throw new Exception("文件名的格式不合法");
}
}
}
}

  

java使用poi实现excel表格生成的更多相关文章

  1. java用poi读取Excel表格中的数据

    Java读写Excel的包是Apache POI(项目地址:http://poi.apache.org/),因此需要先获取POI的jar包,本实验使用的是POI 3.9稳定版.Apache POI 代 ...

  2. Java使用POI解析Excel表格

    概述 Excel表格是常用的数据存储工具,项目中经常会遇到导入Excel和导出Excel的功能. 常见的Excel格式有xls和xlsx.07版本以后主要以基于XML的压缩格式作为默认文件格式xlsx ...

  3. Java Struts2 POI创建Excel文件并实现文件下载

    Java Struts2 POI创建Excel文件并实现文件下载2013-09-04 18:53 6059人阅读 评论(1) 收藏 举报 分类: Java EE(49) Struts(6) 版权声明: ...

  4. JAVA使用POI获取Excel的列数与行数

    Apache POI 是用Java编写的免费开源的跨平台的 Java API,Apache POI提供API给Java程式对Microsoft Office格式档案读和写的功能. 下面这篇文章给大家介 ...

  5. Java之POI导出Excel(一):单sheet

    相信在大部分的web项目中都会有导出导入Excel的需求,今天我们就来看看如何用Java代码去实现 用POI导出Excel表格. 一.pom引用 pom文件中,添加以下依赖 查看代码  <!-- ...

  6. JAVA使用POI读取EXCEL文件的简单model

    一.JAVA使用POI读取EXCEL文件的简单model 1.所需要的jar commons-codec-1.10.jarcommons-logging-1.2.jarjunit-4.12.jarlo ...

  7. java通过poi编写excel文件

    public String writeExcel(List<MedicalWhiteList> MedicalWhiteList) { if(MedicalWhiteList == nul ...

  8. java使用POI实现excel文件的读取,兼容后缀名xls和xlsx

    需要用的jar包如下: 如果是maven管理的项目,添加依赖如下: <!-- https://mvnrepository.com/artifact/org.apache.poi/poi --&g ...

  9. Java之POI读取Excel的Package should contain a content type part [M1.13]] with root cause异常问题解决

    Java之POI读取Excel的Package should contain a content type part [M1.13]] with root cause异常问题解决 引言: 在Java中 ...

随机推荐

  1. DOM简介

    什么是DOM? DOM 是 Document Object Model(文档对象模型)的缩写. W3C 文档对象模型 (DOM) 是中立于平台和语言的接口,它允许程序和脚本动态地访问和更新文档的内容. ...

  2. 执行Java脚本firefox启动成功,不运行test方法,且提示NullPointerException

    在ideal中新建maven项目,将录制好的Java脚本文件,直接复制到项目中,添加相关的依赖脚本. 代码不报错之后,运行录制好的Java脚本,启动了firefox之后,不执行test方法,报错Nul ...

  3. 工作笔记-javascript-网络层封装

    /** * @Author Mona * @Date 2016-12-08 * @description 网络层封装 */ /** * 封装基本请求方式 */ window.BaseRequest = ...

  4. Flask之flask-script模块使用

    Flask Script扩展提供向Flask插入外部脚本的功能,包括运行一个开发用的服务器,一个定制的Python shell,设置数据库的脚本,cronjobs,及其他运行在web应用之外的命令行任 ...

  5. vue的ref与$refs

    一. ref使用在父组件上 父组件html: <information ref='information'></information> import information ...

  6. hdu6206 Apple

    地址:http://acm.split.hdu.edu.cn/showproblem.php?pid=6206 题目: Apple Time Limit: 1000/1000 MS (Java/Oth ...

  7. NC审批流开发流程

            1.新建的是数据库表结构中一定要有                          [审批人.                            制单人.             ...

  8. “使用驱动器中J:的光盘之前需要将其格式化

    不知道神马原因致使U盘无法打开——大家千万注意:以后遇见这种情况千万别格式化(当然如果你的U盘或者硬盘里没有重要东西那就另当别论),进入“开始-cmd”,因为我的U盘在电脑上读出来是J盘,所以在cmd ...

  9. AVAudioSession(3):定制 Audio Session 的 Category

    本文转自:AVAudioSession(3):定制 Audio Session 的 Category | www.samirchen.com 本文内容主要来源于 Working with Catego ...

  10. 如何交叉编译Python到ARM-Linux平台(转)

    源: 如何交叉编译Python到ARM-Linux平台