Java利用POI寫Excel

目錄

一 POI 相關依賴

二 POI 基本概念

三 POI 寫 Excel

3.1 Excel 文件格式

3.2 代碼編碼 


一 POI 相關依賴

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>3.16</version>
</dependency>
 
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>3.16</version>
</dependency>

二 POI 基本概念

 在 POI 中有如下對應規則:

  • Workbook 代表着一個 Excel 文件。
  • Sheet 代表着 Workbook 中的一個表格。
  • Row 代表 Sheet 中的一行。
  • Cell 代表着一個單元格。

三 POI 寫 Excel

3.1 Excel 文件格式

3.2 代碼編碼 


import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Poi {

    public static void main(String[] args) throws Exception {
        List<Map> list = new ArrayList<>();
        Map m1 = new HashMap();
        m1.put("id", 20);
        m1.put("name", "張飛");
        m1.put("age", 15);
        list.add(m1);

        Map m2 = new HashMap();
        m2.put("id", 19);
        m2.put("name", "劉備");
        m2.put("age", 19);
        list.add(m2);
        writeExcel(list, "你的文件路徑");

    }

    public static void writeExcel(List<Map> list,  String sourceFilePath) throws Exception {
        OutputStream out = null;
        File file = new File(sourceFilePath);
        Workbook workbook = getWorkbok(file);

        //創建sheet
        Sheet sheet = workbook.createSheet("員工信息");
        //在sheet第一行寫出表單的各個字段名
        Row titleRow = sheet.createRow(0);
        titleRow.createCell(0).setCellValue("id");
        titleRow.createCell(1).setCellValue("name");
        titleRow.createCell(2).setCellValue("age");
        for(int j = 0; j<list.size(); j++) {
            Row row = sheet.createRow(j + 1);
            Map map = list.get(j);
            String id = String.valueOf(map.get("id"));
            String name = String.valueOf(map.get("name"));
            String age = String.valueOf(map.get("age"));

            row.createCell(0).setCellValue(id);
            row.createCell(1).setCellValue(name);
            row.createCell(2).setCellValue(age);
        }
        out =  new FileOutputStream(file);
        workbook.write(out);
    }

    /**
     * 判斷文件是否是 excel
     * @throws Exception
     */
    public static void checkExcelVaild(File file) throws Exception {
        if (!file.exists()) {
            throw new Exception("文件不存在");
        }
        if (!(file.isFile() && (file.getName().endsWith("xls") || file.getName().endsWith("xlsx")))) {
            throw new Exception("文件不是Excel");
        }
    }

    /**
     * 判斷Excel的版本,獲取Workbook
     * @param file
     * @return
     * @throws IOException
     */
    public static Workbook getWorkbok(File file) throws IOException{
        Workbook wb = null;
        FileInputStream in = new FileInputStream(file);
        if(file.getName().endsWith("xls")) {	 //Excel 2003
            wb = new HSSFWorkbook(in);
        } else if(file.getName().endsWith("xlsx")) {	// Excel 2007/2010
            wb = new XSSFWorkbook(in);
        }
        return wb;
    }

    /**
     * 對單元格進行特殊處理
     * @param cell
     * @return
     */
    private static String getCellStringVal(Cell cell) {
        SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
        CellType cellType = cell.getCellTypeEnum();
        switch (cellType) {
            case STRING:
                return cell.getRichStringCellValue().getString() + "#";
            case NUMERIC:
                if (DateUtil.isCellDateFormatted(cell)) {
                    return fmt.format(cell.getDateCellValue()) + "#";
                } else {
                    cell.setCellType(CellType.STRING);
                    return cell.getRichStringCellValue().getString() + "#";
                }
            case BOOLEAN:
                return cell.getBooleanCellValue() + "#";
            case BLANK:
                return cell.getStringCellValue() + "#";
            case ERROR:
                return "錯誤#";
            case FORMULA:
                cell.setCellType(CellType.STRING);
                return cell.getRichStringCellValue().getString() + "#";
            default:
                return "#";
        }
    }

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章