WEB基础:Apache POI的基本使用方法详解

Apache POI是Java操作Microsoft Office文档的API,包括Word、Excel等。使用前需导入相关依赖,创建对应对象进行读写操作。

Apache POI是一个开源的Java库,它提供了一种简单的方式来读写Microsoft Office格式的文件,它支持多种文件格式,包括Excel、Word、PowerPoint等,在本文中,我们将详细介绍Apache POI的基本使用方法。

Apache POI的安装与使用

1、1 Apache POI的安装

WEB基础:Apache POI的基本使用方法详解

Apache POI可以通过Maven或者Gradle进行安装,在pom.xml文件中添加以下依赖:

<dependencies>
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi</artifactId>
        <version>4.1.2</version>
    </dependency>
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poiooxml</artifactId>
        <version>4.1.2</version>
    </dependency>
</dependencies>

1、2 Apache POI的使用

WEB基础:Apache POI的基本使用方法详解

Apache POI提供了丰富的API,可以方便地操作Excel、Word和PowerPoint文件,以下是一些基本的使用方法:

1、2.1 创建Excel文件

WEB基础:Apache POI的基本使用方法详解

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileOutputStream;
import java.io.IOException;
public class CreateExcel {
    public static void main(String[] args) throws IOException {
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("Sheet1");
        Row row = sheet.createRow(0);
        Cell cell = row.createCell(0);
        cell.setCellValue("Hello, World!");
        try (FileOutputStream outputStream = new FileOutputStream("workbook.xlsx")) {
            workbook.write(outputStream);
        } finally {
            workbook.close();
        }
    }
}

1、2.2 读取Excel文件内容

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Iterator;
public class ReadExcel {
    public static void main(String[] args) throws IOException {
        iterateRowsOfSheet(0); // iterate rows of first sheet only
    }
    private static void iterateRowsOfSheet(int sheetIndex) throws IOException {
        try (FileInputStream inputStream = new FileInputStream("workbook.xlsx")) {
            Workbook workbook = new XSSFWorkbook(inputStream);
            Sheet sheet = workbook.getSheetAt(sheetIndex);
            Iterator<Row> rowIterator = sheet.iterator();
            while (rowIterator.hasNext()) {
                Row row = rowIterator.next();
                Iterator<Cell> cellIterator = row.cellIterator();
                while (cellIterator.hasNext()) {
                    Cell cell = cellIterator.next();
                    switch (cell.getCellType()) {
                        case STRING:
                            System.out.print(cell.getStringCellValue() + "\t");
                            break;
                        case NUMERIC:
                            System.out.print(cell.getNumericCellValue() + "\t");
                            break;
                        case BOOLEAN:
                            System.out.print(cell.getBooleanCellValue() + "\t");
                            break;
                        default:
                            System.out.print("Unknown\t");
                    }
                }
                System.out.println(); // move to a new line after each row, end of line reached in the file is not guaranteed to be a new line in the output stream!
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally { } // do nothing here, just let the method complete normally if an exception occurred earlier! The finally block will be executed regardless of whether an exception was thrown or not! It's good practice to leave it empty anyway! If you want to close resources in a finally block, use trywithresources instead! See below for more information on this topic! In general, you should avoid using finally blocks as much as possible and only use them when absolutely necessary! They can make your code harder to read and understand! Instead, use trywithresources whenever possible! This will automatically close resources for you even if an exception occurs! You can also use the "trywithresources" statement with methods that return a resource object like FileInputStream or Workbook in this case! This way, you don't have to manually close the resources yourself anymore! The Java 7 language specification introduced the "trywithresources" statement which makes it easier to manage resources in Java programs! It allows you to declare one or more resources in a try statement and automatically close them at the end of the statement! This helps prevent resource leaks and makes your code cleaner and easier to understand! For more information on this topic, see the following link: https://docs

原创文章,作者:K-seo,如若转载,请注明出处:https://www.kdun.cn/ask/508425.html

(0)
K-seoK-seoSEO优化员
上一篇 2024年5月22日 20:04
下一篇 2024年5月22日 20:07

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

免备案 高防CDN 无视CC/DDOS攻击 限时秒杀,10元即可体验  (专业解决各类攻击)>>点击进入