如何生成可变表头的excel(转)
1、实现功能:
传入一个表头和数据,将数据导入到excel中。
为了便于项目的扩展,数据传入通过泛型集合传入,获取数据时,通过反射的方式获取,这样无论你的表头是多少项,我都能很方便的生成。另外为了便于数据的管理,我每天都会自动生成一个文件夹,excel生成在相应的文件夹中。文件的根目录通过读取项目中的properties文件获取(详情可查看:http://www.cnblogs.com/0201zcr/p/4700418.html)。好啦,接下来直接进入代码开发吧。
2、所需jar包
这里使用的是通过poi的方式将数据导入到excel中。
3、代码设计
1)、properties文件内容
filePath=E\:/appData
2)、获取文件保存的根目录(来自项目中的properties文件)

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties; public class GetFilePlace
{
/**
* 读取文件,获取excel保存的根目录
* @return excel保存的根目录
*/
public String getFilePath()
{
String dir = System.getProperty("user.dir"); //获得tomcat所在的工作路径 //获取到存储了文件存储位置的filedir.properties 文件路径
String realDir = dir + File.separator + "src" + File.separator +"META-INF" + File.separator + "filedir.properties"; /*String realDir = dir.substring(0, dir.length()-4) + File.separator +"webapps" + File.separator + "generateExcels"
+ File.separator + "classes" + File.separator + "META-INF" + File.separator + "config" + File.separator + "filedir.properties";
*/
return realDir;
} /**
* 获取filePath路径【properities文件】中key对应的值,
* @param filePath properities文件路径【包含properities文件】
* @param key 要查找的key值
* @return key对应的value
*/
public String GetValueByKey(String filePath, String key)
{
Properties pps = new Properties();
try {
InputStream in = new BufferedInputStream (new FileInputStream(filePath));
pps.load(in);
String value = pps.getProperty(key);
in.close();
return value; }catch (IOException e) {
e.printStackTrace();
return null;
}
} /**
* 查询properities文件中可以对应的存储地点
* @param key 查询主键
* @return key对应的存储地址
*/
public String getFileDirFromProperties(String key)
{
return GetValueByKey(getFilePath(),key);
} public static void main(String[] args)
{
System.out.println(new GetFilePlace().getFileDirFromProperties("filePath"));
}
}

3)、生成文件夹

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Calendar; public class GenerateFold
{
/**
* 查询当前生成的excel需要存在在哪个路径,如果存在则存储在相应的位置,否则生成改目录, 每天生成一个文件夹,文件夹的命名规则为 年月日的时间戳
* @param foldName 生成excel保存路径
* @return 现在的excel需要保存路径
*/
public String getFold(String foldName)
{
SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd"); String todayStr = format.format(Calendar.getInstance().getTime()); String foldPath = foldName + File.separator + todayStr; File file = new File(foldPath); if(!file.exists() && !file.isDirectory())
{
System.out.println("不存在");
file.mkdirs();
}
else
{
System.out.println("存在");
}
return foldPath;
} }

4)、生成excel

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.UUID; import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
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.hssf.util.Region;
import org.apache.poi.ss.usermodel.CellStyle; import com.zcr.until.GetFilePlace;
import com.zcr.until.User; /**
* 生成excel
* @author zcr
*
*/
public class GenerateExcel
{
/**
* 通过关键字查询properties文件相应文件的存储位置,根据表头顺序将数据保存到相应文件路径的xls文件中, 文件的命名规则是时间戳加一串全球唯一编码
* @param fileDir //查找文件存储根目录
* @param head //表头
* @param list //数据
* @return //文件的保存路径及其名字的字符串
*/
public <T> String generateExcels(String fileDir,String [] head,List<T> list)
{
//获得存储的路径
//String savePath = new GetFilePlace().getFileDirFromProperties(key); //文件存储名字
String saveFileName = "";
SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmssSS");
saveFileName += format.format(Calendar.getInstance().getTime()); UUID uuid = UUID.randomUUID(); //全球唯一编码 saveFileName += "-" + uuid.toString(); HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet();
workbook.setSheetName(0,"APP数据"); //设置表格工作簿名称
HSSFCellStyle cellStyle = workbook.createCellStyle();
cellStyle.setAlignment(CellStyle.ALIGN_CENTER);
cellStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER); HSSFRow titleRow = sheet.createRow(0);
sheet.addMergedRegion(new Region(0,(short)0,0,(short)(head.length-1)));
HSSFCell titleCell = titleRow.createCell(0);
titleCell.setCellValue("AAP数据____ ");
titleCell.setCellStyle(cellStyle);
HSSFRow row1 = sheet.createRow(1); //设置表头
for(int i = 0 ; i < head.length ; i++)
{
HSSFCell cell = row1.createCell(i);
cell.setCellValue(head[i]); //设置值
cell.setCellStyle(cellStyle);//设置样式
} if(null != list && list.size() > 0)
{
int size = list.size();
Class classType = list.get(0).getClass();
for(int i = 0,rowNum=2 ; i < size ; i ++,rowNum++)
{
HSSFRow rows = sheet.createRow(rowNum);
T t = list.get(i); //添加数据行
for(int j = 0 ; j < head.length ; j++)
{
//获得首字母
String firstLetter = head[j].substring(0,1).toUpperCase(); //获得get方法,getName,getAge等
String getMethodName = "get" + firstLetter + head[j].substring(1); Method method;
try
{
//通过反射获得相应的get方法,用于获得相应的属性值
method = classType.getMethod(getMethodName, new Class[]{}); HSSFCell dataCell = rows.createCell(j);
try
{
System.out.print(getMethodName +":" + method.invoke(t, new Class[]{}) +",");
dataCell.setCellValue(method.invoke(t, new Class[]{}).toString());
}
catch (IllegalArgumentException e)
{
e.printStackTrace();
}
catch (IllegalAccessException e)
{
e.printStackTrace();
}
catch (InvocationTargetException e)
{
e.printStackTrace();
} //设置值
dataCell.setCellStyle(cellStyle);//设置样式
}
catch (SecurityException e)
{
e.printStackTrace();
}
catch (NoSuchMethodException e)
{
e.printStackTrace();
} }
System.out.println();
}
}
else
{
System.out.println("没有数据");
} //获得文件存储路径
//String fileDir = new GetFilePlace().getFileDirFromProperties(key);
saveFileName += ".xls";
String saveFilePathAndName = fileDir + File.separator + saveFileName;
OutputStream out = null;
try
{
out = new FileOutputStream(saveFilePathAndName);
try
{
workbook.write(out);//保存文件
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
try
{
out.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
} return saveFilePathAndName;
} /**
* 提供外界调用的接口,生成以head为表头,list为数据的excel
* @param head //数据表头
* @param list //数据
* @return //excel所在的路径
*/
public <T> String generateExcel(String [] head,List<T> list)
{
final String FilePath = "filePath";
String saveFilePathAndName = ""; //获得存储的根目录
String savePath = new GetFilePlace().getFileDirFromProperties(FilePath); //获得当天存储的路径
String realSavePath = new GenerateFold().getFold(savePath); //生成excel并将存储的路径返回(包含文件名)
saveFilePathAndName = generateExcels(realSavePath, head, list); return saveFilePathAndName;
} public static void main(String[] args)
{
String [] head = {"name","sex","adress","height","age","jj"}; List<User> list = new ArrayList<User>();
User user1 = new User("zhangsan",1,1.1f,"北京","男","AA");
User user2 = new User("lisi",22222,3.2f,"上海","女","BB"); list.add(user1);
list.add(user2); System.out.println(new GenerateExcel().generateExcel(head,list));
//System.out.println(new GenerateExcel().generateExcels("E:\\appData\\20151104",head,list));
} }

5)、测试结果
生成了文件
文件内容如下
properties文件读取可查看:http://www.cnblogs.com/0201zcr/p/4700418.html
读取excel可查看:http://www.cnblogs.com/0201zcr/p/4656779.html
http://www.cnblogs.com/0201zcr/p/4950619.html
如何生成可变表头的excel(转)的更多相关文章
- 如何生成可变表头的excel
1.实现功能: 传入一个表头和数据,将数据导入到excel中. 为了便于项目的扩展,数据传入通过泛型集合传入,获取数据时,通过反射的方式获取,这样无论你的表头是多少项,我都能很方便的生成.另外为了便于 ...
- 使用C#动态生成Word文档/Excel文档的程序测试通过后,部署到IIS服务器上,不能正常使用的问题解决方案
使用C#动态生成Word文档/Excel文档的程序功能调试.测试通过后,部署到服务器上,不能正常使用的问题解决方案: 原因: 可能asp.net程序或iis访问excel组件时权限不够(Ps:Syst ...
- 用java从0生成一个简单的excel
用java从0生成一个简单的excel 目标 用代码实现对一个excel的基础操作,包括创建,插入文字,(好像就这些了),生成的excel可以用wps打开,如果直接用c++的文件流会生成假的xls表格 ...
- vue+element-ui动态生成多级表头,并且将有相同字段下不同子元素合并为同一个
element表头要多层生成,下一级表头数据源必须是当前表头的子一级,这样一层一层嵌套可以生成多层表头: 要把数据处理成这种类型的数据 var arr = []; for (var key in ob ...
- Python生成文本格式的excel\xlwt生成文本格式的excel\Python设置excel单元格格式为文本\Python excel xlwt 文本格式
Python生成文本格式的excel\xlwt生成文本格式的excel\Python设置excel单元格格式为文本\Python excel xlwt 文本格式 解决: xlwt 中设置单元格样式主要 ...
- JAVA操作Excel 可配置,动态 生成复杂表头 复杂的中国式报表表头
转载:开源社区http://www.oschina.net/code/snippet_1424099_49530?p=2代码] [Java]代码 该代码实现了Excel复杂表头的生成 基于sql se ...
- 用Python3生成30万条excel数据(xlsx格式)
在B/S架构的系统测试中,有时需要通过导入excel文件来生成一些数据记录,当数据量小的时候,一般不会出现什么问题,而当导入的数据量巨大时,对系统的性能就是一个考验了.为了验证系统的性能,有时需要导入 ...
- 【C#附源码】数据库文档生成工具支持(Excel+Html)
[2015] 很多时候,我们在生成数据库文档时,使用某些工具,可效果总不理想,不是内容不详细,就是表现效果一般般.很多还是word.html的.看着真是别扭.本人习惯用Excel,所以闲暇时,就简单的 ...
- NPOI操作EXCEL(五)——含合并单元格复杂表头的EXCEL解析
我们在第三篇文章中谈到了那些非常反人类的excel模板,博主为了养家糊口,也玩命做出了相应的解析方法... 我们先来看看第一类复杂表头: ...... 博主称这类excel模板为略复杂表头模板(蓝色部 ...
随机推荐
- 【ThinkingInC++】61、非成员运算符
非成员运算符 当操作者的左侧是不同的类时.运算符重载不可能是正确的类中. IostreamOperatorOverloading.cpp /** * 书本:[ThinkingInC++] * 功能:非 ...
- crontab,想说爱你不easy
悲剧的背景 跑自己主动化脚本的机器连不上toastserver了, 仅仅能自己写个脚本每天跑了. 当然要放在crontab里了. 5 3 * * * sh ~/nosecron.sh 更悲剧的结果 第 ...
- hadoop调度程序时出现“Error opening job jar”错误
提示出现的问题: Exception in thread "main" java.io.IOException: Error opening job jar: /home/depl ...
- zigbee学习:示例程序SampleApp中通讯流程
zigbee学习:示例程序SampleApp中通讯流程 本文博客链接:http://blog.csdn.net/jdh99,作者:jdh,转载请注明. 参考链接: http://wjf88223.bl ...
- RedGate 工具SQLTEST 1.0.15.1
原文:RedGate 工具SQLTEST 1.0.15.1 RedGate 工具SQLTEST 1.0.15.1 SQL TEST1.0.15.1的破解可以参考这篇文章:http://www.cnbl ...
- SQLSERVER图片查看工具SQL Image Viewer5.5.0.156
原文:SQLSERVER图片查看工具SQL Image Viewer5.5.0.156 SQLSERVER图片查看工具SQL Image Viewer5.5.0.156 在2013年某一次北京SQL ...
- 索尼 LT26I刷机包 X.I.D 增加官方风格 GF A3.9.4 各方面完美
ROM介 FX_GF_A系列是具有官方风格的.稳定的.流畅的.省电的.新功能体验的.最悦耳音效体验的ROM. FX_GF_A更新日志 ☆ GF_3.9.4 更新信息 ☆ 更新播放器 ☆ 更新adsp数 ...
- UVA11100- The Trip, 2007
option=com_onlinejudge&Itemid=8&category=512&page=show_problem&problem=2041"> ...
- Test SRM Level Two: CountExpressions, Brute Force
题目来源:http://community.topcoder.com/stat?c=problem_statement&pm=8157 这道题目跟扑克牌算24的题目比较像,但要简单一些.点击查 ...
- c++ 计算程序运行时间
转载 http://blog.csdn.net/trustbo/article/details/10582287 以前经常听人提起如何计算程序运行时间,给出一系列函数,当时没有注意,随便选了clock ...