通过使用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. 除去DataTable中的空行!

    昨天向数据库中导入Excel数据时  由于空行 总是报错!下面附上两种去除空行的方法! 方法一.某行某列值为空时 DataView dv = dt.DefaultView;              ...

  2. node.js---sails项目开发

    http://sailsdoc.swift.ren/ 这里有 sails中文文档 node.js---sails项目开发(1)安装,启动sails node.js---sails项目开发(2)安装测试 ...

  3. spring中的缓存--Caching

    1.spring从3.1开始支持缓存功能.spring 自带的缓存机制它只在方法上起作用,对于你使用其他持久化层的框架来讲,是没有影响的,相对来讲这种缓存方式还是不错的选择. 2.提供缓存的接口:or ...

  4. linux中执行定时任务对oracle备份(crontab命令)

    执行定时任务对oracle表数据备份: 1.创建sh脚本 [oracle@localhost ~]$ vi bak.sh 2.添加脚本内容 #!/bin/bash #:本脚本自动备份7天的数据库,每次 ...

  5. PAT 1084 Broken Keyboard[比较]

    1084 Broken Keyboard (20 分) On a broken keyboard, some of the keys are worn out. So when you type so ...

  6. Linux常见错误之Could not get lock /var/lib/dpkg/lock - open

    在Ubuntu系统上安装vim是遇到的问题: root@ubuntu:/# vim The program 'vim' can be found in the following packages: ...

  7. TensorFlow学习笔记(七)Tesnor Board

    为了更好的管理.调试和优化神经网络的训练过程,TensorFlow提供了一个可视化工具TensorBoard.TensorBoard可以有效的展示TensorFlow在运行过程中的计算图..各种指标随 ...

  8. [React-Native]入门(Hello World)

    (1)需要一台Mac(OSX),这个是前提,建议还是入手一本啦. (2)在Mac上安装Xcode,建议Xcode 6.3以上版本 (3)安装node.js:https://nodejs.org/dow ...

  9. Web Servlet的体系架构

    Servlet为根接口,里面有5个方法,init() servlet初始化,将ServletConfig作为参数传入,service() 响应请求,destroy() 销毁servlet,getSer ...

  10. iOS 动态调用方法

      - (void)bugly { dispatch_async(dispatch_get_global_queue(0, 0), ^{ if (NSClassFromString(@"Bu ...