Apache POI 是一个非常强大的 Java 库用于 Excel、Word 和 PowerPoint

      Apache POI 是一个非常强大的 Java 库,用于读取和写入 Microsoft Office 格式的文件,包括 Excel、Word 和 PowerPoint。以下是 Apache POI 的详细介绍,包括其主要功能、组件、使用方法和一些常见用法示例。
1. 概述
     Apache POI 是 Apache Software Foundation 的一个开源项目,旨在提供纯 Java 的 API 来操作 Microsoft Office 文档。它支持以下几种文件格式:
Excel (HSSF 和 XSSF):用于读写 .xls 和 .xlsx 文件。
Word (HWPF 和 XWPF):用于读写 .doc 和 .docx 文件。
PowerPoint (HSLF 和 XSLF):用于读写 .ppt 和 .pptx 文件。
2. 主要组件
2.1 HSSF (Horrible SpreadSheet Format)
用途:用于读写 Microsoft Excel .xls 文件。
主要类:
HSSFWorkbook:表示整个工作簿。
HSSFSheet:表示工作表。
HSSFRow:表示行。
HSSFCell:表示单元格。
HSSFCellStyle:表示单元格样式。
HSSFFont:表示字体。
HSSFPalette:表示调色板。
2.2 XSSF (XML SpreadSheet Format)
用途:用于读写 Microsoft Excel .xlsx 文件。
主要类:
XSSFWorkbook:表示整个工作簿。
XSSFSheet:表示工作表。
XSSFRow:表示行。
XSSFCell:表示单元格。
XSSFCellStyle:表示单元格样式。
XSSFFont:表示字体。
XSSFColor:表示颜色。
2.3 HWPF (Horrible Word Processor Format)
用途:用于读写 Microsoft Word .doc 文件。
主要类:
HWPFDocument:表示整个文档。
Range:表示文档的一部分。
Paragraph:表示段落。
CharacterRun:表示字符运行。
2.4 XWPF (XML Word Processor Format)
用途:用于读写 Microsoft Word .docx 文件。
主要类:
XWPFDocument:表示整个文档。
XWPFParagraph:表示段落。
XWPFRun:表示字符运行。
XWPFTable:表示表格。
XWPFTableCell:表示单元格。
2.5 HSLF (Horrible Slide Layout Format)
用途:用于读写 Microsoft PowerPoint .ppt 文件。
主要类:
HSLFSlideShow:表示整个演示文稿。
HSLFSlide:表示幻灯片。
HSLFTextParagraph:表示文本段落。
HSLFTextRun:表示文本运行。
2.6 XSLF (XML Slide Layout Format)
用途:用于读写 Microsoft PowerPoint .pptx 文件。
主要类:
XMLSlideShow:表示整个演示文稿。
XSLFSlide:表示幻灯片。
XSLFTextParagraph:表示文本段落。
XSLFTextRun:表示文本运行。
3. 使用方法
3.1 添加依赖
如果你使用 Maven,可以在 pom.xml 文件中添加以下依赖:

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

3.2 读取 Excel 文件
以下是一个读取 Excel 文件的示例:

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

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

public class ReadExcelExample {
    public static void main(String[] args) {
        try (FileInputStream fis = new FileInputStream(new File("input.xlsx"));
             Workbook workbook = new XSSFWorkbook(fis)) {

            Sheet sheet = workbook.getSheetAt(0);
            for (Row row : sheet) {
                for (Cell cell : row) {
                    switch (cell.getCellType()) {
                        case STRING:
                            System.out.print(cell.getStringCellValue() + "\t");
                            break;
                        case NUMERIC:
                            System.out.print(cell.getNumericCellValue() + "\t");
                            break;
                        default:
                            System.out.print("\t");
                            break;
                    }
                }
                System.out.println();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

3.3 写入 Excel 文件
以下是一个写入 Excel 文件的示例:

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

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

public class WriteExcelExample {
    public static void main(String[] args) {
        // 创建工作簿
        Workbook workbook = new XSSFWorkbook();

        // 创建工作表
        Sheet sheet = workbook.createSheet("Data");

        // 创建标题行
        Row headerRow = sheet.createRow(0);
        String[] headers = {"ID", "Name", "Age"};
        for (int i = 0; i < headers.length; i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(headers[i]);
        }

        // 创建数据行
        List<Person> data = new ArrayList<>();
        data.add(new Person(1, "张三", 25));
        data.add(new Person(2, "李四", 30));
        data.add(new Person(3, "王五", 28));

        int rowNum = 1;
        for (Person person : data) {
            Row row = sheet.createRow(rowNum++);
            row.createCell(0).setCellValue(person.getId());
            row.createCell(1).setCellValue(person.getName());
            row.createCell(2).setCellValue(person.getAge());
        }

        // 自动调整列宽
        for (int i = 0; i < headers.length; i++) {
            sheet.autoSizeColumn(i);
        }

        // 将工作簿写入文件
        try (FileOutputStream fileOut = new FileOutputStream("output.xlsx")) {
            workbook.write(fileOut);
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 关闭工作簿
        try {
            workbook.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    static class Person {
        private int id;
        private String name;
        private int age;

        public Person(int id, String name, int age) {
            this.id = id;
            this.name = name;
            this.age = age;
        }

        public int getId() {
            return id;
        }

        public String getName() {
            return name;
        }

        public int getAge() {
            return age;
        }
    }
}

4. 常见用法
4.1 设置单元格样式

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

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

public class SetCellStyleExample {
    public static void main(String[] args) {
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("Styled Data");

        // 创建标题行
        Row headerRow = sheet.createRow(0);
        String[] headers = {"ID", "Name", "Age"};

        // 创建样式
        CellStyle headerStyle = workbook.createCellStyle();
        Font font = workbook.createFont();
        font.setBold(true);
        font.setColor(IndexedColors.BLUE.getIndex());
        headerStyle.setFont(font);

        for (int i = 0; i < headers.length; i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(headers[i]);
            cell.setCellStyle(headerStyle);
        }

        // 创建数据行
        List<Person> data = new ArrayList<>();
        data.add(new Person(1, "张三", 25));
        data.add(new Person(2, "李四", 30));
        data.add(new Person(3, "王五", 28));

        int rowNum = 1;
        for (Person person : data) {
            Row row = sheet.createRow(rowNum++);
            row.createCell(0).setCellValue(person.getId());
            row.createCell(1).setCellValue(person.getName());
            row.createCell(2).setCellValue(person.getAge());
        }

        // 自动调整列宽
        for (int i = 0; i < headers.length; i++) {
            sheet.autoSizeColumn(i);
        }

        // 将工作簿写入文件
        try (FileOutputStream fileOut = new FileOutputStream("styled_output.xlsx")) {
            workbook.write(fileOut);
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 关闭工作簿
        try {
            workbook.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    static class Person {
        private int id;
        private String name;
        private int age;

        public Person(int id, String name, int age) {
            this.id = id;
            this.name = name;
            this.age = age;
        }

        public int getId() {
            return id;
        }

        public String getName() {
            return name;
        }

        public int getAge() {
            return age;
        }
    }
}

5. 总结
        Apache POI 是一个功能强大且灵活的库,适用于处理各种 Microsoft Office 文件。通过上述示例,你可以看到如何使用 Apache POI 进行基本的读写操作和样式设置。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值