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 "#";
        }
    }

}
发布了78 篇原创文章 · 获赞 79 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/jack1liu/article/details/104696623
今日推荐