java實現excel導入導出

一、Excel解析的集中實現方式

  1. POI
  2. JXL
  3. FastExcel

提示:本節只介紹POI和JXL對Excel的讀寫
筆記原文:java實現excel導入導出
源碼: https://github.com/caojx-git/learn/tree/master/code/excel-java

1.1 POI

Apache POI是Apache軟件基金會的開放源碼函式庫,POI提供API給Java程序對Microsoft Office格式檔案的度和寫的功能,功能非常強大,我們使用其中的HSSF(Horrible SpreadSheet Format),即"討厭的電子表格格式"。通過HSSF,你可以用純Java代碼來讀取、寫入、修改Excel文檔。

其中POI主要提供瞭如下功能:

  • HSSF 讀寫Microsoft Excel格式檔案的功能,即(97~2003,結尾是.xls格式的excel)。
  • XSSF 讀寫Microsoft Excel OOXML格式檔案的功能(2007以上excel的,結尾.xlsx)。
  • HWPF 讀寫Microsoft Word格式檔案的功能。
  • HSLF 讀寫Microsoft PowerPoint格式檔案的功能。
  • HDFG 讀寫Microsoft Visio格式檔案的功能。

1.2 iText

通過iText不僅可以生成PDF或rtf的文檔,而且可以將XML、Html文件轉化爲PDF文件,使用起來相對簡單,這點作爲一個擴充,本文主要介紹Excel的讀寫。

1.3 JXL

Java Excel是一個開放源碼項目,可以讀取Excel文件的內容,創建新的Excel文件,更新已經存在的Excel文件,包括常見格式的設置如:字體、顏色、背景、合併單元格等。

1.4 POI與JXL對比

POI JXL
效率高 效率低
操作相對複雜 操作簡單
支持公式,宏,圖像圖表一些企業應用上非常實用 部分支持
能夠修飾單元格屬性 能夠修飾單元格屬性,格式支持不如POI強大
支持字體、數字、日期操作 支持字體、數字、日期操作

1.5 FastExcel

FastExcel是一個採用純java開發的Excel文件讀寫的組件,支持Excel 97-2003文件格式。
FastExcel只能讀取單元格的字符信息,而其他屬性入顏色,字體等就不怎麼支持了,因此FastExcel只需要很小的內存。

1.6 提要

在編碼之前我們先知道如下知識點:

  • 工作薄:相當於Excel文件
  • 工作表:sheet,Excel文件中的sheet
  • 行記錄:Row,即sheet中的一行
  • 單元格:Cell,即sheet中的一個單元格

二、JXL讀寫Excel編碼實現

2.1 maven依賴

<dependency>
  <groupId>net.sourceforge.jexcelapi</groupId>
  <artifactId>jxl</artifactId>
  <version>2.6.12</version>
</dependency>

2.2 JXL創建Excel

目前,jxl對於excel的讀寫不支持07以上的Office Excel格式,即支持.xls格式不支持.xlsx格式,如果需要支持.xlsx格式需要使用POI。

  1. JxlWriteExcel.java
    JXL方式創建Excel
package excel.jxl;

import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;

import java.io.File;
import java.io.IOException;

/**
 * POI創建Excel,格式是.xls,不支持2007+以上的Excel,即不支持.xlsx結尾的Excel
 */
public class JxlWriteExcel {

    /**
     * JXL創建Excel文件
     * @param args
     */
    public static void main(String[] args) {
        //定義標題
        String[] title = {"id","name","sex"};
        //1.創建一個Excel文件
        File file = new File("jxl_test.xls");
        try {
            file.createNewFile();
            //2.創建工作薄
            WritableWorkbook workbook = Workbook.createWorkbook(file);
            //3.創建sheet
            WritableSheet sheet = workbook.createSheet("sheet1",0);

            //4.設置標題
            Label label = null;
            for (int i = 0; i < title.length; i++) {
                label = new Label(i,0,title[i]); //三個參數分別爲:所在列、所在行,數據值
                //將標題設置到對應的sheet中的單元格
                sheet.addCell(label);
            }
            //5.追加數據
            for (int i = 1; i < 10; i++) {
                label = new Label(0, i,"a"+i);
                sheet.addCell(label);
                label = new Label(1, i,"user"+i);
                sheet.addCell(label);
                label = new Label(2, i,"男");
                sheet.addCell(label);
            }

            //寫入數據
            workbook.write();
            //關閉流資源
            workbook.close();

        } catch (IOException e) {
            e.printStackTrace();
        } catch (RowsExceededException e) {
            e.printStackTrace();
        } catch (WriteException e) {
            e.printStackTrace();
        }
    }
}

jxl_test.xls生成結果

2.3 JXL讀取Excel

  1. JxlReadExcel.java
    JXL讀取Excel
package excel.jxl;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;

import java.io.File;
import java.io.IOException;

/**
 * Jxl讀取Excel,格式是.xls 不支持2007+以上的Excel,即不支持.xlsx結尾的Excel
 */
public class JxlReadExcel {

    /**
     * JXL解析Excel文件
     * @param args
     */
    public static void main(String[] args) {
        try {
            //1.創建workbook
            Workbook workbook = Workbook.getWorkbook(new File("jxl_test.xls"));
            //2.獲取第一個工作表sheet
            Sheet sheet = workbook.getSheet(0   );
            //獲取數據
            for (int i = 0; i < sheet.getRows(); i++) {
                for (int j = 0; j < sheet.getColumns(); j++) {
                    Cell cell = sheet.getCell(j,i); //列,行
                    //獲取單元格的內容
                    System.out.print(cell.getContents()+" ");
                }
                System.out.println("");
            }
            workbook.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (BiffException e) {
            e.printStackTrace();
        }

    }
}

讀取結果:

id name sex 
a1 user1 男 
a2 user2 男 
a3 user3 男 
a4 user4 男 
a5 user5 男 
a6 user6 男 
a7 user7 男 
a8 user8 男 
a9 user9 男 

三、POI讀寫Excel編碼實現

POI可以支持.xls和.xlsx格式的Excel

HSSF 讀寫Microsoft Excel格式檔案的功能,即(97~2003,結尾是.xls格式的excel)

XSSF 讀寫Microsoft Excel OOXML格式檔案的功能(2007以上excel的,結尾.xlsx)

3.1 maven依賴

<!--poi-->
<!--支持.xls格式的excel-->
<dependency>
  <groupId>commons-io</groupId>
  <artifactId>commons-io</artifactId>
  <version>2.4</version>
</dependency>

<dependency>
  <groupId>org.apache.poi</groupId>
  <artifactId>poi</artifactId>
  <version>3.15</version>
</dependency>

<!--支持.xlsx格式的excel-->
<dependency>
  <groupId>org.apache.poi</groupId>
  <artifactId>poi-ooxml</artifactId>
  <version>3.15</version>
</dependency>

3.2 POI創建Excel

package excel.poi;

import org.apache.commons.io.FileUtils;
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 java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * POI創建Excel,格式是.xls
 */
public class POIWriteExcel {

    /**
     * POI創建Excel文件
     * @param args
     */
    public static void main(String[] args) {
        //定義標題
        String[] title = {"id","name","sex"};
        //1.創建工作薄
        HSSFWorkbook workbook = new HSSFWorkbook();
        //2.創建工作表
        HSSFSheet sheet = workbook.createSheet();
        //設置標題
        HSSFRow row = sheet.createRow(0);
        HSSFCell cell = null;
        for (int i = 0; i < title.length; i++) {
            cell = row.createCell(i); //i所在列
            cell.setCellValue(title[i]); //設置列的內容
        }

        //追加數據
        for (int i = 1; i < 10; i++) {
            HSSFRow nextRow = sheet.createRow(i);
            HSSFCell cell2 = nextRow.createCell(0); //第一列
            cell2.setCellValue("a"+i);
            cell2 = nextRow.createCell(1); //第二列
            cell2.setCellValue("user"+i);
            cell2 = nextRow.createCell(2); //第三列
            cell2.setCellValue("男"+i);
        }

        //創建一個文件
        File file = new File("poi_test.xls");
        try {
            file.createNewFile();
            //將數據保存到excel文件中
            FileOutputStream outputStream = FileUtils.openOutputStream(file);
            workbook.write(outputStream);
            //關閉資源
            outputStream.close();
            workbook.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

poi_test.xls生成結果:

3.3 POI讀取Excel

package excel.poi;

import org.apache.commons.io.FileUtils;
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 java.io.File;
import java.io.IOException;

/**
 * POI讀取Excel,格式是.xls
 */
public class POIReadExcel {

    /**
     * POI解析Excel文件的內容
     * @param args
     */
    public static void main(String[] args) {
        //1.需要解析的Excel文件
        File file = new File("poi_test.xls");
        try {
            //2.創建工作薄,讀取Excel文件內容
            HSSFWorkbook workbook = new HSSFWorkbook(FileUtils.openInputStream(file));
            //3.確定sheet
            //獲取指定名稱的sheet
            //HSSFSheet sheet = workbook.getSheet("Sheet0");
            //根據索引獲取sheet
            HSSFSheet sheet = workbook.getSheetAt(0);
            int firstRowNum = 0;
            //獲取sheet中最後一行行號
            int lastRowNum = sheet.getLastRowNum();
            for (int i = 0; i < lastRowNum; i++) {
                HSSFRow row = sheet.getRow(i);
                //獲取當前最後單元格列號
                int lastCellNum = row.getLastCellNum();
                for (int j = 0; j < lastCellNum; j++) {
                    HSSFCell cell = row.getCell(j);
                    String value = cell.getStringCellValue();
                    System.out.print(value+" ");
                }
                System.out.println();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

poi_test.xls讀取結果:

id name sex 
a1 user1 男1 
a2 user2 男2 
a3 user3 男3 
a4 user4 男4 
a5 user5 男5 
a6 user6 男6 
a7 user7 男7 
a8 user8 男8 

3.4 POI創建高版本的Excel

3.2與3.3中的方式不支持2007+的office格式即.xlsx格式的excel文件讀取,使用XSSF方式可以支持。

package excel.poi;

import org.apache.commons.io.FileUtils;
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.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * .xlsx格式的創建,這是Office 2007+支持的Excel格式,不過我們不知道客戶的Office是什麼版本,所以我們一般在生產中不會使用.xlsx格式
 */
public class POIWriteExcel2 {

    /**
     * POI創建Excel文件 .xlsx格式
     * @param args
     */
    public static void main(String[] args) {
        //定義標題
        String[] title = {"id","name","sex"};
        //1.創建工作薄
        XSSFWorkbook workbook = new XSSFWorkbook();
        //2.創建工作表
        Sheet sheet = workbook.createSheet();
        //設置標題
        Row row = sheet.createRow(0);
        Cell cell = null;
        for (int i = 0; i < title.length; i++) {
            cell = row.createCell(i); //i所在列
            cell.setCellValue(title[i]); //設置列的內容
        }

        //追加數據
        for (int i = 1; i < 10; i++) {
            Row nextRow = sheet.createRow(i);
            Cell cell2 = nextRow.createCell(0); //第一列
            cell2.setCellValue("a"+i);
            cell2 = nextRow.createCell(1); //第二列
            cell2.setCellValue("user"+i);
            cell2 = nextRow.createCell(2); //第三列
            cell2.setCellValue("男"+i);
        }

        //創建一個文件
        File file = new File("poi_test2.xlsx");
        try {
            file.createNewFile();
            //將數據保存到excel文件中
            FileOutputStream outputStream = FileUtils.openOutputStream(file);
            workbook.write(outputStream);
            //關閉資源
            outputStream.close();
            workbook.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

poi_test2.xlsx生成結果:

3.5 POI讀取高版本的Excel

package excel.poi;

import org.apache.commons.io.FileUtils;
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.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * .xlsx格式的創建,這是Office 2007+支持的Excel格式,不過我們不知道客戶的Office是什麼版本,所以我們一般在生產中不會使用.xlsx格式
 */
public class POIWriteExcel2 {

    /**
     * POI創建Excel文件 .xlsx格式
     * @param args
     */
    public static void main(String[] args) {
        //定義標題
        String[] title = {"id","name","sex"};
        //1.創建工作薄
        XSSFWorkbook workbook = new XSSFWorkbook();
        //2.創建工作表
        Sheet sheet = workbook.createSheet();
        //設置標題
        Row row = sheet.createRow(0);
        Cell cell = null;
        for (int i = 0; i < title.length; i++) {
            cell = row.createCell(i); //i所在列
            cell.setCellValue(title[i]); //設置列的內容
        }

        //追加數據
        for (int i = 1; i < 10; i++) {
            Row nextRow = sheet.createRow(i);
            Cell cell2 = nextRow.createCell(0); //第一列
            cell2.setCellValue("a"+i);
            cell2 = nextRow.createCell(1); //第二列
            cell2.setCellValue("user"+i);
            cell2 = nextRow.createCell(2); //第三列
            cell2.setCellValue("男"+i);
        }

        //創建一個文件
        File file = new File("poi_test2.xlsx");
        try {
            file.createNewFile();
            //將數據保存到excel文件中
            FileOutputStream outputStream = FileUtils.openOutputStream(file);
            workbook.write(outputStream);
            //關閉資源
            outputStream.close();
            workbook.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

poi_test2.xlsx讀取結果:

id name sex 
a1 user1 男1 
a2 user2 男2 
a3 user3 男3 
a4 user4 男4 
a5 user5 男5 
a6 user6 男6 
a7 user7 男7 
a8 user8 男8 

四、JavaWeb項目導入導出excel思路

4.1 導入

一般在web項目中我們會手動創建Excel模板文件文件,而不是通過代碼創建Excel模板文件,在用戶需要導入數據的時候,下載模板Excel,填寫好數據後導入到我們系統中。

4.2 導出

假如我們想導出前臺頁面的列表數據

導出全部數據:前臺列表的表頭傳遞到後臺,通過方法去數據庫查詢對應的數據數據,表頭+數據生成Excel,用戶下載Excel。

導出部分數據:前臺列表的表頭和查詢條件傳遞到後臺,後臺通過方法查詢數據生成Excel,用戶下載。

發佈了60 篇原創文章 · 獲贊 81 · 訪問量 12萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章