poi解析Excel文檔

package test;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
public class ExcelTest {
 public static void main(String[] args) {
  
//  POIFSFileSystem fs = null;
//    HSSFWorkbook wb = null;
//    try {
//     fs = new POIFSFileSystem(new FileInputStream(""));
//     wb = new HSSFWorkbook(fs);
//    } catch (IOException e) {
//     e.printStackTrace();
//    }
  HSSFWorkbook workbook;
  HSSFSheet sheet;
  HSSFRow row;
  HSSFCell cell = null;
  int columnNo;// 列數
  File file=new File("E:/excel.xls");
  FileInputStream fis=null;
  try {
   fis=new FileInputStream(file);
   workbook = new HSSFWorkbook(fis);
   //獲取第一個表單
   sheet = workbook.getSheetAt(0);
   //獲取第2行 行對象
   row = sheet.getRow(1);
   //順次讀取單元格數據
   cell = row.getCell(0);
   //文本類型
   String str=cell.getStringCellValue();
   System.out.println(str);
   cell = row.getCell(1);
   //數字類型
   int num=(int)cell.getNumericCellValue();
   System.out.println("num:"+num);
   long longn=(long)cell.getNumericCellValue();
   System.out.println("longn:"+longn);
   float floatn=(float)cell.getNumericCellValue();
   System.out.println("floatn:"+floatn);
   //日期類型
   cell = row.getCell(2);
   System.out.println(cell.getDateCellValue());
   String   strFormat   =   "yyyy-MM-dd"; 
   SimpleDateFormat   sdf   =   new   SimpleDateFormat(strFormat);
   try {
    String entryPersonDate = sdf.format(cell.getDateCellValue());
    System.out.println(entryPersonDate);
   } catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }  
   //時間類型
   cell = row.getCell(3);
   
   
//   HSSFCellStyle cellStyle = workbook.createCellStyle(); // 建立新的cell樣式
//   cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("hh:mm:ss")); // 設置cell樣式爲定製的日期格式
//   cell.setCellStyle(cellStyle); // 設置該cell日期的顯示格式
//   System.out.println(cell.getDateCellValue());
   
   String   str1   =   "hh:mm:ss";
   SimpleDateFormat   sdf1   =   new   SimpleDateFormat(str1); 
   try {
    System.out.println(cell.getDateCellValue());
    String entryPersonDate = sdf1.format(cell.getDateCellValue());
    System.out.println(entryPersonDate);
   } catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  finally{
   try {
    fis.close();
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }
  
  
 }

 
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章