Java讀取Excel文件內容

maven引入

<!--Apache POI - Java API To Access Microsoft Format Files-->
  	 <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.13</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.13</version>
        </dependency>

相關讀取代碼

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
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;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

public class ExcelTest {

    public static void main(String[] args) throws Exception {
        readExcel("C:\\Users\\z0042ssu\\Desktop\\unit.xlsx");
    }
    private static void readExcel(String path) throws Exception {
        File file = new File(path);
        if (file.isFile() && file.exists()) {
            System.out.println(file.getPath());
            String[] split = file.getName().split("\\.");
            Workbook wb;
            if ("xls".equals(split[1])) {
                FileInputStream inputStream = new FileInputStream(file);
                wb = new HSSFWorkbook(inputStream);
            }else if ("xlsx".equals(split[1])){
                wb = new XSSFWorkbook(file);
            }else {
                System.out.println("文件類型錯誤");
                return;
            }
            Sheet sheet = wb.getSheetAt(0);
            //第一行是列名,所以從第二行開始遍歷
            int firstRowNum = sheet.getFirstRowNum()+1;
            int lastRowNum = sheet.getLastRowNum();
            //遍歷行
            int i = 1;
            for (int rIndex = firstRowNum; rIndex <= lastRowNum; rIndex++) {
                Map map =new HashMap();
                //獲取當前行的內容
                Row row = sheet.getRow(rIndex);
                if (row != null) {
                    String value = row.getCell(0).getStringCellValue();
                 	//可以對讀取的值進行操作
                }
               
            }
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章