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(转)的更多相关文章

  1. 如何生成可变表头的excel

    1.实现功能: 传入一个表头和数据,将数据导入到excel中. 为了便于项目的扩展,数据传入通过泛型集合传入,获取数据时,通过反射的方式获取,这样无论你的表头是多少项,我都能很方便的生成.另外为了便于 ...

  2. 使用C#动态生成Word文档/Excel文档的程序测试通过后,部署到IIS服务器上,不能正常使用的问题解决方案

    使用C#动态生成Word文档/Excel文档的程序功能调试.测试通过后,部署到服务器上,不能正常使用的问题解决方案: 原因: 可能asp.net程序或iis访问excel组件时权限不够(Ps:Syst ...

  3. 用java从0生成一个简单的excel

    用java从0生成一个简单的excel 目标 用代码实现对一个excel的基础操作,包括创建,插入文字,(好像就这些了),生成的excel可以用wps打开,如果直接用c++的文件流会生成假的xls表格 ...

  4. vue+element-ui动态生成多级表头,并且将有相同字段下不同子元素合并为同一个

    element表头要多层生成,下一级表头数据源必须是当前表头的子一级,这样一层一层嵌套可以生成多层表头: 要把数据处理成这种类型的数据 var arr = []; for (var key in ob ...

  5. Python生成文本格式的excel\xlwt生成文本格式的excel\Python设置excel单元格格式为文本\Python excel xlwt 文本格式

    Python生成文本格式的excel\xlwt生成文本格式的excel\Python设置excel单元格格式为文本\Python excel xlwt 文本格式 解决: xlwt 中设置单元格样式主要 ...

  6. JAVA操作Excel 可配置,动态 生成复杂表头 复杂的中国式报表表头

    转载:开源社区http://www.oschina.net/code/snippet_1424099_49530?p=2代码] [Java]代码 该代码实现了Excel复杂表头的生成 基于sql se ...

  7. 用Python3生成30万条excel数据(xlsx格式)

    在B/S架构的系统测试中,有时需要通过导入excel文件来生成一些数据记录,当数据量小的时候,一般不会出现什么问题,而当导入的数据量巨大时,对系统的性能就是一个考验了.为了验证系统的性能,有时需要导入 ...

  8. 【C#附源码】数据库文档生成工具支持(Excel+Html)

    [2015] 很多时候,我们在生成数据库文档时,使用某些工具,可效果总不理想,不是内容不详细,就是表现效果一般般.很多还是word.html的.看着真是别扭.本人习惯用Excel,所以闲暇时,就简单的 ...

  9. NPOI操作EXCEL(五)——含合并单元格复杂表头的EXCEL解析

    我们在第三篇文章中谈到了那些非常反人类的excel模板,博主为了养家糊口,也玩命做出了相应的解析方法... 我们先来看看第一类复杂表头: ...... 博主称这类excel模板为略复杂表头模板(蓝色部 ...

随机推荐

  1. FusionCharts简单教程---建立第一个FusionCharts图形

    由于项目需求需要做一个报表,选择FusionCharts作为工具使用.由于以前没有接触过报表,网上也没有比较详细的fusionCharts教程,所以决定好好研究FusionCharts,同时做一个比较 ...

  2. java自学者的福音

    谈到自学对于程序员来说并不陌生,自从我们离开校门就开始了自学之路.这一路上绝大部分都是 百步止于九十 步, 不是因为他们不够坚持,而是没有找到学习的方法和资源.当然这一路上我也走得很辛苦,刚毕业后自学 ...

  3. 玩转web之javaScript(五)---js和jquery一些不可不知的方法(input篇)

    很多时候我们都利用js和jquery中操作input,比如追加属性,改变属性值等等,我在这里简单的整理了一下,并在以后逐步补充. 1:删除input的某一属性. <input name=&quo ...

  4. uva 11992 为矩阵更新查询段树

    http://uva.onlinejudge.org/index.php? option=com_onlinejudge&Itemid=8&page=show_problem& ...

  5. Linux下一个php+mysql+nginx构建编译(三)

    在此之前一直是一个关键构建webserver.但一个关键的建筑环境都比较旧的.假定使用一个相对较新的环境,尤其是正式的server.您必须手动编译自己建(基于以下的结构linux centos6.5 ...

  6. UBUNTU12.04下安装配置体验gnome3

    年. ubuntu12.04默认采用unity界面,但是自己更加喜欢gnome3的操作方式. 安装gnome3: sudo apt-get install  gnome-shell 其实安装成功后,注 ...

  7. 解决 下载 CM-12.0 源代码出现 Fatal: duplicate project .....问题

    在使用 repo init -u git://github.com/CyanogenMod/android.git -b cm-12.0 初始化代码库的时候出现如下错误: fatal: manifes ...

  8. leetcode——Evaluate Reverse Polish Notation 求算式值(AC)

    Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operators are +, -, ...

  9. 玩转Web之easyui(三)-----easy ui dataGird 重新指定url以获取不同数据源信息

    如果已经写了一个dataGird并且已经通过url绑定数据源,能不能在其他地方改变url使其从不同数据源获取信息,从而实现查询等操作?答案当然是肯定的,而且仅需要几行代码 $('#btnq').bin ...

  10. 无奈而又苦逼的二分版本号回退法定位新引入的bug!!!

    昨天測试人员和开发者都发现, 某新版本号有严重的bug.  群里已经開始嚷嚷了, 但没有谁知道是谁引入的问题.本来呢, 这个问题不应该是由我去定位, 但主管让我帮定位一下, 毕竟时间太紧急, 必须尽快 ...