用Java解析Excel文件


用到了Apache的→POI插件←,可點擊鏈接從官網下載,目前已更新至4.0版本

1.將下載好的放入lib(class_path)目錄下,

2.編寫代碼

package com.fyf.test;

import java.io.FileInputStream;

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;

public class PoiRead {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        try {
            FileInputStream fStream = new FileInputStream("D:/test.xls");
            Workbook wb = new HSSFWorkbook(fStream);
            Sheet sheet = wb.getSheetAt(0);
            //因為Sheet接口繼承了 java.lang.Iterable接口所以,遍歷表中的行可以一用foreach很方便    
            for (Row row : sheet) {
          //跳過空行
if (row==null) { continue; } System.out.print("row:"+row.getRowNum()+"\t");
          //同理行中的單元格也可以用foreach遍歷
for (Cell cell : row) { if (cell==null) { continue; }
            //對cell進行判斷后輸出 System.out.print(
"|"+getStringCell(cell)+"\t|"); } System.out.println(); } } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } } public static String getStringCell(Cell cell) { String result = ""; int cellType = cell.getCellType(); switch (cellType) { case Cell.CELL_TYPE_BOOLEAN: result = String.valueOf(cell.getBooleanCellValue()); break; case Cell.CELL_TYPE_NUMERIC:
       //這里將數組作為日期返回 result
= String.valueOf(cell.getDateCellValue()); break; case Cell.CELL_TYPE_STRING: result = cell.getStringCellValue(); break; default: break; } return result; } }

 


免責聲明!

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



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