java使用POI读取properties文件并写到Excel的方法

所属分类: 软件编程 / java 阅读数: 48
收藏 0 赞 0 分享

本文实例讲述了java使用POI读取properties文件并写到Excel的方法。分享给大家供大家参考。具体实现方法如下:

package com.hubberspot.code;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Properties;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
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.HSSFColor;
public class ReadWriteXlsProperties {
  // Create a HashMap which will store the properties 
  HashMap< String, String > propMap = new HashMap< String, String >();
  public static void main(String[] args) {
    // Create object of ReadWriteXlsProperties
    ReadWriteXlsProperties readWriteXlsDemo = new ReadWriteXlsProperties();
    // Call method readProperties() it take path to properties file 
    readWriteXlsDemo.readProperties("config.properties");
    // Call method writeToExcel() it will take path to excel file
    readWriteXlsDemo.writeToExcel("test.xls");
  }
  private void readProperties(String propertiesFilePath) {
    // Create a File object taking in path of properties 
    // file
    File propertiesFile = new File(propertiesFilePath);
    // If properties file is a file do below stuff
    if(propertiesFile.isFile())
    {
      try
      {
        // Create a FileInputStream for loading the properties file
        FileInputStream fisProp = new FileInputStream(propertiesFile);
        // Create a Properties object and load 
        // properties key and value to it through FileInputStream
        Properties properties = new Properties();
        properties.load(fisProp);
        // Create a object of Enumeration and call keys()
        // method over properties object created above
        // it will return us back with a Enumeration types
        Enumeration< Object > keysEnum = properties.keys();
        // Looping over the elements of Enumeration
        while(keysEnum.hasMoreElements())
        {
          // Extracting the key and respective values from it.
          String propKey = (String)keysEnum.nextElement();
          String propValue = (String)properties.getProperty(propKey);
          // After extracting the key and value from the properties file
          // we will store the values in a HashMap.
          propMap.put( propKey.toLowerCase().trim(),propValue.toLowerCase().trim());
        }  
        // printing the HashMap and closing the file FileInputStream
        System.out.println("Properties Map ... \n" + propMap);
        fisProp.close();
      }
      catch(FileNotFoundException e)
      {           
        e.printStackTrace();
      }
      catch(IOException e)
      {          
        e.printStackTrace();
      }
    }
  }
  private void writeToExcel(String excelPath) {
    // Create a Workbook using HSSFWorkbook object
    HSSFWorkbook workBook = new HSSFWorkbook();
    // Create a sheet with name "properties" by 
    // the createSheet method of the Workbook
    HSSFSheet worksheet = workBook.createSheet("Properties");
    // Create a row by calling createRow method of the 
    // Worksheet
    HSSFRow row = worksheet.createRow((short) 0);
    // Create a cell style by calling createCellStyle()
    // from the workbook
    HSSFCellStyle cellStyle = workBook.createCellStyle();
    // setting of the foreground and fill pattern by calling methods
    // of HSSFCellStyle as setFillForegroundColor() and setFillPattern()
    cellStyle.setFillForegroundColor(HSSFColor.GOLD.index);
    cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
    // Create a HSSFCell from the row object created above 
    HSSFCell cell1 = row.createCell(0);
    // Setting the value of the cell as the keys by calling 
    // setCellValue() method over the HSSFCell
    cell1.setCellValue(new HSSFRichTextString("Keys"));
    // Giving it the style created above.
    cell1.setCellStyle(cellStyle);
    HSSFCell cell2 = row.createCell(1);
    cell2.setCellValue(new HSSFRichTextString("Values"));
    cell2.setCellStyle(cellStyle);
    // Create a Iterator and as propMap is a HashMap 
    // it is converted to a HashSet by calling keySet() method 
    // which will return with Set.
    // Iterator object is pointed to keys of Set
    Iterator< String > iterator = propMap.keySet().iterator();
    // Looping across the elements of Iterator
    while(iterator.hasNext())
    {     
      // Creating a new row from the worksheet
      // at the last used row + 1 location
      HSSFRow rowOne = worksheet.createRow(worksheet.getLastRowNum()+1);
      // Creating two cells in the row at 0 and 1 position.
      HSSFCell cellZero = rowOne.createCell(0);
      HSSFCell cellOne = rowOne.createCell(1);
      // extracting key and value from the map and set
      String key = (String) iterator.next();
      String value = (String) propMap.get(key);
      // setting the extracted keys and values in the cells 
      cellZero.setCellValue(new HSSFRichTextString(key));
      cellOne.setCellValue(new HSSFRichTextString(value));
    }     
    try{
      FileOutputStream fosExcel =null;     
      // Creating a xls File
      File fileExcel = new File(excelPath);        
      // Setting the File to FileOutputStream
      fosExcel = new FileOutputStream(fileExcel);
      // Writing the contents of workbook to the xls
      workBook.write(fosExcel);
      // Flushing the FileOutputStream
      fosExcel.flush();
      // Closing the FileOutputStream
      fosExcel.close();
    }catch(Exception e){
      e.printStackTrace();
    }
  }
}

希望本文所述对大家的java程序设计有所帮助。

更多精彩内容其他人还在看

JAVA实现caesar凯撒加密算法

Carsar加密算法是最简单的加密算法,原理是把一个字母在字母表中移动相应的位置,比如输入a,将其移动3位,经过Caesar加密后输出的d,位置可以循环移动,输入x,则输出a
收藏 0 赞 0 分享

java使用randomaccessfile在文件任意位置写入数据

Java在文件任意位置写入数据可以使用RandomAccessFile方法来完成,下面看一个简单的示例就明白了
收藏 0 赞 0 分享

java实现sunday算法示例分享

Sunday算法的思想和BM算法中的坏字符思想非常类似。差别只是在于Sunday算法在匹配失败之后,是取目标串中当前和Pattern字符串对应的部分后面一个位置的字符来做坏字符匹配,写了个小例子来实现以下这个算法
收藏 0 赞 0 分享

java设计模式之单例模式学习

单例对象(Singleton)是一种常用的设计模式。在Java应用中,单例对象能保证在一个JVM中,该对象只有一个实例存在
收藏 0 赞 0 分享

java设计模式之建造者模式学习

建造者模式(Builder Pattern)主要用于“分步骤构建一个复杂的对象”,在这其中“分步骤”是一个稳定的算法,下面给出了详细的示例
收藏 0 赞 0 分享

java自定义日志输出文件(log4j日志文件输出多个自定义日志文件)

打印日志的在程序中是必不可少的,如果需要将不同的日志打印到不同的地方,则需要定义不同的Appender,然后定义每一个Appender的日志级别、打印形式和日志的输出路径,下面看一个示例吧
收藏 0 赞 0 分享

java进行error捕获和处理示例(java异常捕获)

通常来说,大家都是对Java中的Exception进行捕获和进行相应的处理,有些人说,error就无法捕获了。其实,error也是可以捕获的。Error和Exception都是Throwable的子类。既然可以catch Throwable,那么error也是可以catch的
收藏 0 赞 0 分享

java序列化和java反序列化示例

在web项目开发的时候,经常用到序列化和反序列化用来传递大流量的数据,类只有实现Serializable借口才能被序列化,下来是java序列化和反序列化演示
收藏 0 赞 0 分享

java字符串比较获取字符串出现次数的示例

java获取一个字符串在整个字符串出现的次数,下面写出我的思路和二个实现方法,大家参考使用吧
收藏 0 赞 0 分享

java字符串反转示例分享

这篇文章主要介绍了将一个字符串进行反转或者字符串中指定部分进行反转的方法,大家参考使用吧
收藏 0 赞 0 分享
查看更多