简体   繁体   中英

How to create a XSSFTable in Apache POI

I am trying to create an Excel sheet that contains an Excel table using Java with the Apache POI library but I couldn't get a result file that is readable by Microsoft Excel 2016 (Office 365). This is my code:

import org.apache.poi.ss.util.AreaReference;
import org.apache.poi.ss.util.CellReference;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

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

class Scratch {
    public static void main(String[] args) throws IOException {
        XSSFWorkbook workbook = new XSSFWorkbook();
        XSSFSheet sheet = workbook.createSheet("Table Sheet");

        XSSFRow row0 = sheet.createRow(0);
        row0.createCell(0).setCellValue("#");
        row0.createCell(1).setCellValue("Name");

        XSSFRow row1 = sheet.createRow(1);
        row1.createCell(0).setCellValue("1");
        row1.createCell(1).setCellValue("Foo");

        XSSFRow row2 = sheet.createRow(2);
        row2.createCell(0).setCellValue("2");
        row2.createCell(1).setCellValue("Bar");

        AreaReference area = workbook.getCreationHelper().createAreaReference(
                new CellReference(row0.getCell(0)),
                new CellReference(row2.getCell(1))
        );
        sheet.createTable(area);

        try(FileOutputStream file = new FileOutputStream(new File("workbook.xlsx"))) {
            workbook.write(file);
        }
    }
}

The code runs fine but when I open the output file in Excel I get a message that the file has unreadable content.

I have tried running the official sample and the result is the same. The official sample can be found here: https://svn.apache.org/repos/asf/poi/trunk/src/examples/src/org/apache/poi/xssf/usermodel/examples/CreateTable.java

I need to know the minimum code required to get a readable table.

I am using version 4.0.0 of Apache POI with Oracle JavaSE JDK 1.8.0_172 on Windows 10.

Not sure what happens with the "official sample" codes always. They seems not even be tested.

The CreateTable uses XSSFTable table = sheet.createTable(reference); which creates a table having 3 columns as given from the area reference. But all of those have id 1, so we need repairing. And of course the columns should not be created again then.

So repaired sample code would be:

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

import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.AreaReference;
import org.apache.poi.ss.util.CellReference;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFTable;
import org.apache.poi.xssf.usermodel.XSSFTableStyleInfo;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

/**
 * Demonstrates how to create a simple table using Apache POI.
 */
public class CreateTable {

    public static void main(String[] args) throws IOException {

        try (Workbook wb = new XSSFWorkbook()) {
            XSSFSheet sheet = (XSSFSheet) wb.createSheet();

            // Set which area the table should be placed in
            AreaReference reference = wb.getCreationHelper().createAreaReference(
                    new CellReference(0, 0), new CellReference(2, 2));

            // Create
            XSSFTable table = sheet.createTable(reference); //creates a table having 3 columns as of area reference
            // but all of those have id 1, so we need repairing
            table.getCTTable().getTableColumns().getTableColumnArray(1).setId(2);
            table.getCTTable().getTableColumns().getTableColumnArray(2).setId(3);

            table.setName("Test");
            table.setDisplayName("Test_Table");

            // For now, create the initial style in a low-level way
            table.getCTTable().addNewTableStyleInfo();
            table.getCTTable().getTableStyleInfo().setName("TableStyleMedium2");

            // Style the table
            XSSFTableStyleInfo style = (XSSFTableStyleInfo) table.getStyle();
            style.setName("TableStyleMedium2");
            style.setShowColumnStripes(false);
            style.setShowRowStripes(true);
            style.setFirstColumn(false);
            style.setLastColumn(false);
            style.setShowRowStripes(true);
            style.setShowColumnStripes(true);

            // Set the values for the table
            XSSFRow row;
            XSSFCell cell;
            for (int i = 0; i < 3; i++) {
                // Create row
                row = sheet.createRow(i);
                for (int j = 0; j < 3; j++) {
                    // Create cell
                    cell = row.createCell(j);
                    if (i == 0) {
                        cell.setCellValue("Column" + (j + 1));
                    } else {
                        cell.setCellValue((i + 1.0) * (j + 1.0));
                    }
                }
            }

            // Save
            try (FileOutputStream fileOut = new FileOutputStream("ooxml-table.xlsx")) {
                wb.write(fileOut);
            }
        }
    }
}

Btw.: My code from How to insert a table in ms excel using apache java poi works as well using apache poi 4.0.0 . The sheet.createTable() is deprecated. So do using XSSFTable table = sheet.createTable(null); instead. Because the area as well as all other things is set using low level classes. Not even more code than the new example though.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM