如何生成可變表頭的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

  致謝:感謝您的閱讀!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM