溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

java如何生成可變表頭的excel

發(fā)布時間:2020-08-24 10:28:32 來源:腳本之家 閱讀:143 作者:WhyWin 欄目:編程語言

本文為大家分享了java生成可變表頭excel的具體步驟,供大家參考,具體內(nèi)容如下

1、實現(xiàn)功能:

  傳入一個表頭和數(shù)據(jù),將數(shù)據(jù)導(dǎo)入到excel中。

  為了便于項目的擴(kuò)展,數(shù)據(jù)傳入通過泛型集合傳入,獲取數(shù)據(jù)時,通過反射的方式獲取,這樣無論你的表頭是多少項,我都能很方便的生成。另外為了便于數(shù)據(jù)的管理,我每天都會自動生成一個文件夾,excel生成在相應(yīng)的文件夾中。文件的根目錄通過讀取項目中的properties文件獲?。ㄔ斍榭刹榭矗韩@取tomcat上properties文件內(nèi)容的方法)。好啦,接下來直接進(jìn)入代碼開發(fā)吧。

2、所需jar包

  這里使用的是通過poi的方式將數(shù)據(jù)導(dǎo)入到excel中。

java如何生成可變表頭的excel

3、代碼設(shè)計

1)、properties文件內(nèi)容

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對應(yīng)的值,
  * @param filePath properities文件路徑【包含properities文件】
  * @param key 要查找的key值
  * @return key對應(yīng)的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文件中可以對應(yīng)的存儲地點
  * @param key 查詢主鍵
  * @return key對應(yīng)的存儲地址
  */
 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
{
 /**
  * 查詢當(dāng)前生成的excel需要存在在哪個路徑,如果存在則存儲在相應(yīng)的位置,否則生成改目錄, 每天生成一個文件夾,文件夾的命名規(guī)則為 年月日的時間戳
  * @param foldName 生成excel保存路徑
  * @return   現(xiàn)在的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
{
 /**
  * 通過關(guān)鍵字查詢properties文件相應(yīng)文件的存儲位置,根據(jù)表頭順序?qū)?shù)據(jù)保存到相應(yīng)文件路徑的xls文件中, 文件的命名規(guī)則是時間戳加一串全球唯一編碼
  * @param fileDir       //查找文件存儲根目錄
  * @param head       //表頭
  * @param list       //數(shù)據(jù)
  * @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數(shù)據(jù)"); //設(shè)置表格工作簿名稱
  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數(shù)據(jù)____ ");
  titleCell.setCellStyle(cellStyle);
  HSSFRow row1 = sheet.createRow(1);
  
  
  //設(shè)置表頭
  for(int i = 0 ; i < head.length ; i++)
  {
   HSSFCell cell = row1.createCell(i);
   cell.setCellValue(head[i]); //設(shè)置值
   cell.setCellStyle(cellStyle);//設(shè)置樣式
  }
  
  
  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);
    
    //添加數(shù)據(jù)行
    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
     {
      //通過反射獲得相應(yīng)的get方法,用于獲得相應(yīng)的屬性值
      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();
      } //設(shè)置值
      dataCell.setCellStyle(cellStyle);//設(shè)置樣式
     }
     catch (SecurityException e)
     {
      e.printStackTrace();
     }
     catch (NoSuchMethodException e)
     {
      e.printStackTrace();
     }
     
    }
    System.out.println();
   }
  }
  else
  {
   System.out.println("沒有數(shù)據(jù)");
  }
  
  //獲得文件存儲路徑
  //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;
 }

 
 /**
  * 提供外界調(diào)用的接口,生成以head為表頭,list為數(shù)據(jù)的excel
  * @param head //數(shù)據(jù)表頭
  * @param list //數(shù)據(jù)
  * @return  //excel所在的路徑
  */
 public <T> String generateExcel(String [] head,List<T> list)
 {
  final String FilePath = "filePath";
  String saveFilePathAndName = "";
 
  //獲得存儲的根目錄
  String savePath = new GetFilePlace().getFileDirFromProperties(FilePath);
  
  //獲得當(dāng)天存儲的路徑
  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)、測試結(jié)果

生成了文件

java如何生成可變表頭的excel

  文件內(nèi)容如下

java如何生成可變表頭的excel

properties文件讀取可查看:獲取tomcat上properties文件內(nèi)容的方法

讀取excel可查看:java使用POI批量導(dǎo)入excel數(shù)據(jù)的方法

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI