1. 程式人生 > >java的poi技術讀取Excel[xls,xlsx]

java的poi技術讀取Excel[xls,xlsx]

(最近專案需要對excel進行操作,所以在網上找到了這篇博文,並且很好的應用到了專案中,在此做個記錄。)

這篇blog主要是講述java中poi讀取excel,而excel的版本包括:2003-2007和2010兩個版本, 即excel的字尾名為:xls和xlsx。

下面是本文的專案結構:

這裡寫圖片描述

專案中所需要的jar檔案:

這裡寫圖片描述

所用的Excel資料(2003-2007,2010都是一樣的資料)

這裡寫圖片描述

執行效果:

這裡寫圖片描述

原始碼部分:

=================================================

/Excel2010/src/com/b510/common/Common.java

/**
 * 
 */
package com.b510.common;

/**
 * @author Hongten
 * @created 2014-5-21
 */
public class Common {

    public static final String OFFICE_EXCEL_2003_POSTFIX = "xls";
    public static final String OFFICE_EXCEL_2010_POSTFIX = "xlsx";

    public static final String EMPTY = "";
    public static final
String POINT = "."; public static final String LIB_PATH = "lib"; public static final String STUDENT_INFO_XLS_PATH = LIB_PATH + "/student_info" + POINT + OFFICE_EXCEL_2003_POSTFIX; public static final String STUDENT_INFO_XLSX_PATH = LIB_PATH + "/student_info" + POINT + OFFICE_EXCEL_2010_POSTFIX; public
static final String NOT_EXCEL_FILE = " : Not the Excel file!"; public static final String PROCESSING = "Processing..."; }

/Excel2010/src/com/b510/excel/ReadExcel.java

/**
 * 
 */
package com.b510.excel;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

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

import com.b510.common.Common;
import com.b510.excel.util.Util;
import com.b510.excel.vo.Student;

/**
 * @author Hongten
 * @created 2014-5-20
 */
public class ReadExcel {

    /**
     * read the Excel file
     * @param path the path of the Excel file
     * @return
     * @throws IOException
     */
    public List<Student> readExcel(String path) throws IOException {
        if (path == null || Common.EMPTY.equals(path)) {
            return null;
        } else {
            String postfix = Util.getPostfix(path);
            if (!Common.EMPTY.equals(postfix)) {
                if (Common.OFFICE_EXCEL_2003_POSTFIX.equals(postfix)) {
                    return readXls(path);
                } else if (Common.OFFICE_EXCEL_2010_POSTFIX.equals(postfix)) {
                    return readXlsx(path);
                }
            } else {
                System.out.println(path + Common.NOT_EXCEL_FILE);
            }
        }
        return null;
    }

    /**
     * Read the Excel 2010
     * @param path the path of the excel file
     * @return
     * @throws IOException
     */
    public List<Student> readXlsx(String path) throws IOException {
        System.out.println(Common.PROCESSING + path);
        InputStream is = new FileInputStream(path);
        XSSFWorkbook xssfWorkbook = new XSSFWorkbook(is);
        Student student = null;
        List<Student> list = new ArrayList<Student>();
        // Read the Sheet
        for (int numSheet = 0; numSheet < xssfWorkbook.getNumberOfSheets(); numSheet++) {
            XSSFSheet xssfSheet = xssfWorkbook.getSheetAt(numSheet);
            if (xssfSheet == null) {
                continue;
            }
            // Read the Row
            for (int rowNum = 1; rowNum <= xssfSheet.getLastRowNum(); rowNum++) {
                XSSFRow xssfRow = xssfSheet.getRow(rowNum);
                if (xssfRow != null) {
                    student = new Student();
                    XSSFCell no = xssfRow.getCell(0);
                    XSSFCell name = xssfRow.getCell(1);
                    XSSFCell age = xssfRow.getCell(2);
                    XSSFCell score = xssfRow.getCell(3);
                    student.setNo(getValue(no));
                    student.setName(getValue(name));
                    student.setAge(getValue(age));
                    student.setScore(Float.valueOf(getValue(score)));
                    list.add(student);
                }
            }
        }
        return list;
    }

    /**
     * Read the Excel 2003-2007
     * @param path the path of the Excel
     * @return
     * @throws IOException
     */
    public List<Student> readXls(String path) throws IOException {
        System.out.println(Common.PROCESSING + path);
        InputStream is = new FileInputStream(path);
        HSSFWorkbook hssfWorkbook = new HSSFWorkbook(is);
        Student student = null;
        List<Student> list = new ArrayList<Student>();
        // Read the Sheet
        for (int numSheet = 0; numSheet < hssfWorkbook.getNumberOfSheets(); numSheet++) {
            HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(numSheet);
            if (hssfSheet == null) {
                continue;
            }
            // Read the Row
            for (int rowNum = 1; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
                HSSFRow hssfRow = hssfSheet.getRow(rowNum);
                if (hssfRow != null) {
                    student = new Student();
                    HSSFCell no = hssfRow.getCell(0);
                    HSSFCell name = hssfRow.getCell(1);
                    HSSFCell age = hssfRow.getCell(2);
                    HSSFCell score = hssfRow.getCell(3);
                    student.setNo(getValue(no));
                    student.setName(getValue(name));
                    student.setAge(getValue(age));
                    student.setScore(Float.valueOf(getValue(score)));
                    list.add(student);
                }
            }
        }
        return list;
    }

    @SuppressWarnings("static-access")
    private String getValue(XSSFCell xssfRow) {
        if (xssfRow.getCellType() == xssfRow.CELL_TYPE_BOOLEAN) {
            return String.valueOf(xssfRow.getBooleanCellValue());
        } else if (xssfRow.getCellType() == xssfRow.CELL_TYPE_NUMERIC) {
            return String.valueOf(xssfRow.getNumericCellValue());
        } else {
            return String.valueOf(xssfRow.getStringCellValue());
        }
    }

    @SuppressWarnings("static-access")
    private String getValue(HSSFCell hssfCell) {
        if (hssfCell.getCellType() == hssfCell.CELL_TYPE_BOOLEAN) {
            return String.valueOf(hssfCell.getBooleanCellValue());
        } else if (hssfCell.getCellType() == hssfCell.CELL_TYPE_NUMERIC) {
            return String.valueOf(hssfCell.getNumericCellValue());
        } else {
            return String.valueOf(hssfCell.getStringCellValue());
        }
    }
}

/Excel2010/src/com/b510/excel/client/Client.java

/**
 * 
 */
package com.b510.excel.client;

import java.io.IOException;
import java.util.List;

import com.b510.common.Common;
import com.b510.excel.ReadExcel;
import com.b510.excel.vo.Student;

/**
 * @author Hongten
 * @created 2014-5-21
 */
public class Client {

    public static void main(String[] args) throws IOException {
        String excel2003_2007 = Common.STUDENT_INFO_XLS_PATH;
        String excel2010 = Common.STUDENT_INFO_XLSX_PATH;
        // read the 2003-2007 excel
        List<Student> list = new ReadExcel().readExcel(excel2003_2007);
        if (list != null) {
            for (Student student : list) {
                System.out.println("No. : " + student.getNo() + ", name : " + student.getName() + ", age : " + student.getAge() + ", score : " + student.getScore());
            }
        }
        System.out.println("======================================");
        // read the 2010 excel
        List<Student> list1 = new ReadExcel().readExcel(excel2010);
        if (list1 != null) {
            for (Student student : list1) {
                System.out.println("No. : " + student.getNo() + ", name : " + student.getName() + ", age : " + student.getAge() + ", score : " + student.getScore());
            }
        }
    }
}

/Excel2010/src/com/b510/excel/util/Util.java

/**
 * 
 */
package com.b510.excel.util;

import com.b510.common.Common;

/**
 * @author Hongten
 * @created 2014-5-21
 */
public class Util {

    /**
     * get postfix of the path
     * @param path
     * @return
     */
    public static String getPostfix(String path) {
        if (path == null || Common.EMPTY.equals(path.trim())) {
            return Common.EMPTY;
        }
        if (path.contains(Common.POINT)) {
            return path.substring(path.lastIndexOf(Common.POINT) + 1, path.length());
        }
        return Common.EMPTY;
    }
}

/Excel2010/src/com/b510/excel/vo/Student.java

/**
 * 
 */
package com.b510.excel.vo;

/**
 * Student
 * 
 * @author Hongten
 * @created 2014-5-18
 */
public class Student {
    /**
     * id   
     */
    private Integer id;
    /**
     * 學號
     */
    private String no;
    /**
     * 姓名
     */
    private String name;
    /**
     * 學院
     */
    private String age;
    /**
     * 成績
     */
    private float score;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getNo() {
        return no;
    }

    public void setNo(String no) {
        this.no = no;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }

    public float getScore() {
        return score;
    }

    public void setScore(float score) {
        this.score = score;
    }

}

相關推薦

java的poi技術讀取Excel[xlsxlsx]

(最近專案需要對excel進行操作,所以在網上找到了這篇博文,並且很好的應用到了專案中,在此做個記錄。) 這篇blog主要是講述java中poi讀取excel,而excel的版本包括:2003-2007和2010兩個版本, 即excel的字尾名為:xls和

poi讀取excelxlsxlsx

這是一個poi讀取excel的工具類,支援excel2003,2007以上版本 package io.utils; import org.apache.poi.hssf.usermodel.*; import org.apache.poi.xssf.usermodel.

java使用POI讀取excel檔案相容xlsxlsx

public List<Double> readExcels(InputStream is)throws Exception{List<Double> xlsxList = new ArrayList<Double>();    try {             if(i

PHP Excel 讀取xlsxlsx檔案並出入資料然後儲存

客戶有個需求就是在給定的excle檔案中插入相關資料,一定要注意excle裡的一些格式會匯出phpexcle讀取後無法儲存,折騰了許久,把excel檔案比較特殊的格式去掉就能正常讀取,插入資料,儲存了,下面給大家示例我的程式碼 require_once 'PHPExcel.

excel檔案匯入(xlsxlsx

public class ExcelSwitchMap {  /***   *   * @param in   POIFSFileSystem   * @param max  所匯入excel的列數   * @return map   * @throws IOException   */  @Suppres

【小家java】一個基於POI的Excel的匯入、匯出工具處理類(支援xlsxlsx格式)另有SpringMVC的匯入、匯出案例講解

相關閱讀 前言 表格的匯入、匯出可謂開發過程中經常會碰到的功能。然後這種模版化的東西並不需要每次都去編碼一次,因此我就整理了一個Excel的萬能處理類。能夠實現相容2003、2007的各種Excel格式的匯入匯出功能,使用起來也非常的方面,適用於所有業務場景

.net MVC使用NPOI讀取Excel模板再寫入數據

produce clas actor 找到 讀取 粘貼 亮點 div gin   NPOI其實已經介紹的差不多了,再貼一個方便以後復制粘貼。 亮點其實是 Server.MapPath 這個東西,可以找到MVC工程下的文件夾,找路徑還是很方便的。 /// <su

django/python excel 上傳後臺 並讀取excel內容含日期格式解析處理

step1: 讀取上傳的excel資料並存檔 step2: 讀取存入本地的excel檔案,對內容進行處理,其中包含日期格式處理 重點程式碼: issueDate = sheetContent.cell(row,1).value date_value = xlrd.xldate_as_tu

C#使用NPOI讀取excel模板並匯出excel

private void ExportDoctoryCase(HttpContext context) { //載入模板檔案路徑 string TempletFileName = context.Serv

讀取Excel檔案並對Excel檔案進行描述性分析

> mydata<-read.csv("E:\\╰凝初寒つ\\學習檔案\\大資料概論\\R語言\\soapdata.csv",header=T) > dim(mydata) > mydata<-head(mydata,41) >

pandas讀取Excel檔案以0開頭的資料出現數據缺失

這裡以從深交所現在的日行情資料檔案為例,格式為xlsx 直接使用df = pd.read_excel(os.getcwd() + os.sep + 'stock.xlsx')讀取檔案時,證券程式碼被轉換為數字(000001 =>1),0被捨去,導致不正確。

springMVC之解析excel xlsxlsx格式

一、pom.xml <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</arti

女同事半夜要我用Python讀取Excel資料我用一行程式碼搞定!

分享一個實用問題,用python讀取Excel並儲存字典,如何做?關注薇信工宗號:程式設計師大牛,”即可獲取數十套Python學習資料! 下面是該同學問題截圖和程式碼 程式碼截圖是下面這樣的。學習資料也可以加下Python扣扣裙:304零五零799自己下載學習下

java讀取excel 檔案並把讀取到的資料轉換成javabean物件

javaBean物件public class AcademicaChievements { private Integer aid; private String number; private String sname; private String award_

Java讀取Excel檔案生成SQL語句

import jxl.Sheet; import jxl.Workbook; import jxl.read.biff.BiffException; import java.io.*; public class Main { public static void

robot framework讀取Excel檔案並儲存為list

最近剛使用Robot Framework不久,為了使程式碼和資料分離,需要讀取Excel文字資訊,問題困擾了一天,最後終於解決了, 讀檔案需要ExcelLibrary包支援 1.安裝ExcelLibrary 可以直接通過命令安裝:pip install robotfr

VB.NET 開啟Excel檔案讀取Excel內容新增到DataGridView中並顯示

'Excel新增:工程->參照追加→COM→Microsoft Excel *.* ObjectLibrary   'DataGridView列列舉型定義PrivateEnumDGV_ENUMCOL_ROWCOL_NAMECOL_AGEEndEnum    'Excel

【Python】pandas遍歷讀取excel檔案修改並儲存(一)

code ide and lib version: python            2.7(64) pycharm            2018.1.4 xlrd            1.1.0 pandas            0.23.1 play:

js讀取EXCEL檔案進行一些資料處理

1.僅在IE瀏覽器下有效,因為只有IE支援ActiveXObject("Excel.application"); 2.程式碼如下 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"

POI操作Excel詳解讀取xlsxlsx格式的文件

shee xss split 類型 後綴 .sh lan xls lin package org.ian.webutil; import java.io.File; import java.io.FileInputStream; import java.io.FileN