Java POI 读取Excel-从开始到实例
POI 是apache提供的用于处理Excel 等文件的API。
1. 下载jar档
http://poi.apache.org/download.html#POI-3.7
目前的稳定版本是 3.7.
Window 下开发下载: poi-bin-3.7-20101029.zip
2. 下载后,解压
3. 在Eclipse 下新建Project.
把下面的jar 档导入到工程。
根目录下的jar档
lib目录下的jar档
ooxml-libooxml-lib 的jar 档
4. 测试Class
package poi; import java.io.FileInputStream; import java.util.Iterator; import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class POITest { private static void ReadAndPrintExcelFile(String filePath, String sSheetName) { try { FileInputStream fis = new FileInputStream(filePath); XSSFWorkbook wb = new XSSFWorkbook(fis); XSSFSheet sheet = wb.getSheet(sSheetName); for (int i = 0; i < sheet.getPhysicalNumberOfRows(); i++) { String cellNovalue = ""; XSSFRow row = sheet.getRow(i); Iterator it = row.cellIterator(); while (it.hasNext()) { XSSFCell cell = (XSSFCell) it.next(); try { cellNovalue = cell.getStringCellValue(); } catch (IllegalStateException e) { try { double dcellNovalue = sheet.getRow(i).getCell(0) .getNumericCellValue(); cellNovalue = String.valueOf(dcellNovalue); } catch (IllegalStateException e2) { cellNovalue = ""; e.printStackTrace(); } } catch (Exception e3) { cellNovalue = ""; e3.printStackTrace(); } System.out.println("Row=" + i + "; Cell=" + cell.getColumnIndex() + "; Value=" + cellNovalue); } } } catch (Exception e) { e.printStackTrace(); } } /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub ReadAndPrintExcelFile("E:\\1.xlsx","test"); } }