POI版本:3.5beat(前面的版本只能操作2003,不兼容2007)

1.     Jar包導(dǎo)入項目lib文件夾下.

2.     創(chuàng)建ExcelOperation類:

 

 

package test;

 

//import org.apache.poi.hssf.model.Workbook;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.IOException;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import org.apache.poi.ss.usermodel.Cell;

import org.apache.poi.ss.usermodel.Row;

import org.apache.poi.ss.usermodel.Sheet;

import org.apache.poi.ss.usermodel.Workbook;

import org.apache.poi.xssf.usermodel.XSSFWorkbook;

 

public class ExcelIO {

 

/**

 *讀取Excel

 */

public static String readExcel() throws IOException{

/**

   *POI提供了對20032007的訪問接口,分別是HSSFWorkbookXSSFWorkbook

   *為了兼容20032007,這里選擇它們的共同接口,而不是自己的具象類

   *切記,org.apache.poi.ss.usermodel下的接口,

   *不是org.apache.poi.hssf.model下的具象類

   */

    Workbook wk = null;      //Excel對象

    Sheet sheet = null;      //表對象

    Row row = null;          //行對象

    Cell cell = null;        //單元格對象

 

    try {

//d盤根目錄有一個123.xslxExcel文檔,先讀2007,如果出現(xiàn)異常

//就是2003,在進行2003的處理

        wk = new XSSFWorkbook("D:/123.xlsx");// 2007

    }catch (Exception ex) {

        try {

        //2003的對象需要一個輸入流

           wk = new HSSFWorkbook(new FileInputStream("D:/123.xls"));// 2003

        } catch (FileNotFoundException e) {

           e.printStackTrace();

        }

    }

    //獲取第一張表

    sheet =wk.getSheetAt(0);

    //獲取第一行

    row=sheet.getRow(0);

    //獲取第一個單元格

    cell=row.getCell(0);

    /**

      *單元格中不同的數(shù)據(jù)類型,讀取的方法也不同

      *例如:字符類型使用getStringCellValue();

      *數(shù)字類型使用getNumericCellValue()---返回double;

      *其他數(shù)據(jù)類型的操作方法參考API,這里只做入門級別的操作..

      */

    //String value=cell.getStringCellValue();

    String value=cell.getNumericCellValue()+"";

   

    /**

      *下面是進行對數(shù)據(jù)的修改,但是一修改,Excel就打不開了.不清楚為什么,有待研究...

      */

    //RichTextString text=null;

    //text=new XSSFRichTextString("update");

    //cell.setCellValue(text);

    //cell.setCellValue("update");

    //FileOutputStream fileOut = new FileOutputStream("D:/123.xlsx");

    //wk.write(fileOut);fileOut.close();

    return value;

}

 

public static void main(String[] args) {

    try {

        System.out.println(readExcel());

    } catch (IOException e) {

        e.printStackTrace();

    }

}

}