欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java如何生成可变表头的excel

程序员文章站 2023-11-28 09:42:58
本文为大家分享了java生成可变表头excel的具体步骤,供大家参考,具体内容如下 1、实现功能:   传入一个表头和数据,将数据导入到excel中。   为了便...

本文为大家分享了java生成可变表头excel的具体步骤,供大家参考,具体内容如下

1、实现功能:

  传入一个表头和数据,将数据导入到excel中。

  为了便于项目的扩展,数据传入通过泛型集合传入,获取数据时,通过反射的方式获取,这样无论你的表头是多少项,我都能很方便的生成。另外为了便于数据的管理,我每天都会自动生成一个文件夹,excel生成在相应的文件夹中。文件的根目录通过读取项目中的properties文件获取(详情可查看:)。好啦,接下来直接进入代码开发吧。

2、所需jar包

  这里使用的是通过poi的方式将数据导入到excel中。

java如何生成可变表头的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)、测试结果

生成了文件

java如何生成可变表头的excel

  文件内容如下

java如何生成可变表头的excel

properties文件读取可查看:

读取excel可查看:java使用poi批量导入excel数据的方法

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。