Java 中如何使用 Apache POI 写入 Excel 文件

x33g5p2x  于2021-10-16 转载在 Java  
字(5.4k)|赞(0)|评价(0)|浏览(478)

在本文中,您将学习如何使用 Apache POI 在 Java 中创建和写入 Excel 文件。

您可以查看之前的文章,了解 Apache POI 的高级架构以及如何使用 Apache POI 库读取 excel 文件。

依赖

您需要添加以下依赖项以在您的项目中包含 Apache POI。

maven

Maven 用户可以将以下内容添加到他们的 pom.xml 文件中 -

<!-- Used to work with the older excel file format - `.xls` -->
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>3.17</version>
</dependency>

<!-- Used to work with the newer excel file format - `.xlsx` -->
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>3.17</version>
</dependency>

并且 gradle 用户可以将以下内容添加到他们的 build.gradle 文件中 -

gradle

compile "org.apache.poi:poi:3.17"	     // For `.xls` files
compile "org.apache.poi:poi-ooxml:3.17"	 // For `.xlsx` files

使用 Apache POI 写入 excel 文件

让我们先创建一个简单的 Employee 类。我们将初始化员工列表并将列表写入我们将使用 Apache POI 生成的 excel 文件。

class Employee {
    private String name;
    private String email;
    private Date dateOfBirth;
    private double salary;

    public Employee(String name, String email, Date dateOfBirth, double salary) {
        this.name = name;
        this.email = email;
        this.dateOfBirth = dateOfBirth;
        this.salary = salary;
    }

	// Getters and Setters (Omitted for brevity)
}

现在让我们看一下创建excel文件然后向其中写入数据的程序。请注意,我将使用 XSSFWorkbook 来创建 Workbook 实例。这将生成较新的基于 XML 的 excel 文件 (.xlsx)。如果要生成旧的二进制 excel 格式 (.xls),可以选择使用 HSSFWorkbook

查看上一篇文章中的 Apache POI 术语部分,了解 WorkbookXSSFWorkbookHSSFWorkbook 和其他 Apache POI 术语。

import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class ExcelWriter {

    private static String[] columns = {"Name", "Email", "Date Of Birth", "Salary"};
    private static List<Employee> employees =  new ArrayList<>();

	// Initializing employees data to insert into the excel file
    static {
        Calendar dateOfBirth = Calendar.getInstance();
        dateOfBirth.set(1992, 7, 21);
        employees.add(new Employee("Rajeev Singh", "rajeev@example.com", 
                dateOfBirth.getTime(), 1200000.0));

        dateOfBirth.set(1965, 10, 15);
        employees.add(new Employee("Thomas cook", "thomas@example.com", 
                dateOfBirth.getTime(), 1500000.0));

        dateOfBirth.set(1987, 4, 18);
        employees.add(new Employee("Steve Maiden", "steve@example.com", 
                dateOfBirth.getTime(), 1800000.0));
    }

    public static void main(String[] args) throws IOException, InvalidFormatException {
        // Create a Workbook
        Workbook workbook = new XSSFWorkbook(); // new HSSFWorkbook() for generating `.xls` file

        /* CreationHelper helps us create instances of various things like DataFormat, Hyperlink, RichTextString etc, in a format (HSSF, XSSF) independent way */
        CreationHelper createHelper = workbook.getCreationHelper();

        // Create a Sheet
        Sheet sheet = workbook.createSheet("Employee");

        // Create a Font for styling header cells
        Font headerFont = workbook.createFont();
        headerFont.setBold(true);
        headerFont.setFontHeightInPoints((short) 14);
        headerFont.setColor(IndexedColors.RED.getIndex());

        // Create a CellStyle with the font
        CellStyle headerCellStyle = workbook.createCellStyle();
        headerCellStyle.setFont(headerFont);

        // Create a Row
        Row headerRow = sheet.createRow(0);

        // Create cells
        for(int i = 0; i < columns.length; i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(columns[i]);
            cell.setCellStyle(headerCellStyle);
        }

        // Create Cell Style for formatting Date
        CellStyle dateCellStyle = workbook.createCellStyle();
        dateCellStyle.setDataFormat(createHelper.createDataFormat().getFormat("dd-MM-yyyy"));

        // Create Other rows and cells with employees data
        int rowNum = 1;
        for(Employee employee: employees) {
            Row row = sheet.createRow(rowNum++);

            row.createCell(0)
                    .setCellValue(employee.getName());

            row.createCell(1)
                    .setCellValue(employee.getEmail());

            Cell dateOfBirthCell = row.createCell(2);
            dateOfBirthCell.setCellValue(employee.getDateOfBirth());
            dateOfBirthCell.setCellStyle(dateCellStyle);

            row.createCell(3)
                    .setCellValue(employee.getSalary());
        }

		// Resize all columns to fit the content size
        for(int i = 0; i < columns.length; i++) {
            sheet.autoSizeColumn(i);
        }

        // Write the output to a file
        FileOutputStream fileOut = new FileOutputStream("poi-generated-file.xlsx");
        workbook.write(fileOut);
        fileOut.close();

        // Closing the workbook
        workbook.close();
    }
}

在上面的程序中,我们首先使用 XSSFWorkbook 类创建了一个工作簿。然后我们创建了一个名为“员工”的工作表。获得工作表后,我们创建了标题行和列。标题单元格的样式使用了不同的字体。

创建标题行后,我们从员工列表中创建了其他行和列。

接下来,我们使用 sheet.autoSizeColumn() 方法调整所有列的大小以适应内容大小。

最后,我们将输出写入文件。以下是运行上述程序生成的文件——

哇,这很好,不是吗? :)

打开和修改现有的 Excel 文件

以下方法向您展示了如何打开现有的 excel 文件并对其进行更新 -

private static void modifyExistingWorkbook() throws InvalidFormatException, IOException {
    // Obtain a workbook from the excel file
    Workbook workbook = WorkbookFactory.create(new File("existing-spreadsheet.xlsx"));

    // Get Sheet at index 0
    Sheet sheet = workbook.getSheetAt(0);

    // Get Row at index 1
    Row row = sheet.getRow(1);
    
    // Get the Cell at index 2 from the above row
    Cell cell = row.getCell(2);

    // Create the cell if it doesn't exist
    if (cell == null)
        cell = row.createCell(2);

    // Update the cell's value
    cell.setCellType(CellType.STRING);
    cell.setCellValue("Updated Value");

    // Write the output to the file
    FileOutputStream fileOut = new FileOutputStream("existing-spreadsheet.xlsx");
    workbook.write(fileOut);
    fileOut.close();

    // Closing the workbook
    workbook.close();
}

上述程序是不言自明的。我们首先使用 WorkbookFactory.create() 方法获取 Workbook,然后获取第 1 张表的第 2 行的第 3 列并更新其值。

最后,我们将更新后的输出写入文件。

结论

恭喜各位!在本文中,您学习了如何使用 Apache POI 库在 Java 中创建和写入 Excel 文件。

您可以在 Github repository 上找到完整的源代码。如果您觉得它有用,请给该项目一个 Star。

相关文章

微信公众号

最新文章

更多