easyexcel icon indicating copy to clipboard operation
easyexcel copied to clipboard

多列表组合填充填充 其他单元格不能合并

Open xzxlove opened this issue 2 years ago • 1 comments

1 多列表组合填充填充 其他单元格不能合并指标的单元格可以根据 list长度合并单元格,并添加边框

xzxlove avatar Feb 26 '24 09:02 xzxlove


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

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

public class ExcelGenerator {

    public static void generateWorkbook(Object[][] dataList, String fileName) throws IOException {
        // Create a new workbook and sheet
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("Sheet1");

        // Assuming the data is in a 2D array, where each row is an entry in dataList
        int rowIdx = 0; // Start from row 0 (Excel is 0-indexed)

        // Adding the data and applying borders
        for (Object[] data : dataList) {
            Row row = sheet.createRow(rowIdx);
            int columnIdx = 0; // Start from column 0 (A)

            // Loop through each cell in the row
            for (Object cellValue : data) {
                Cell cell = row.createCell(columnIdx);
                cell.setCellValue(cellValue.toString());

                // Add borders to the cell
                CellStyle style = workbook.createCellStyle();
                BorderStyle borderStyle = BorderStyle.THIN;
                style.setBorderTop(borderStyle);
                style.setBorderBottom(borderStyle);
                style.setBorderLeft(borderStyle);
                style.setBorderRight(borderStyle);
                cell.setCellStyle(style);

                columnIdx++; // Move to the next column
            }

            // Merge cells in a specific column if necessary (e.g., merging the first column)
            if (data.length > 1) {
                sheet.addMergedRegion(new CellRangeAddress(rowIdx, rowIdx, 0, 0)); // Merge cells in column A
            }

            rowIdx++; // Move to the next row after adding data
        }

        // Save the workbook to a file
        try (FileOutputStream fileOut = new FileOutputStream(fileName)) {
            workbook.write(fileOut);
        } finally {
            workbook.close(); // Always close the workbook to avoid memory leaks
        }
    }

    public static void main(String[] args) {
        // Sample data (this would be dynamic in real cases)
        Object[][] dataList = {
                {"Header1", "Header2"},
                {"Value1", "Value2"},
                {"MergedValue1", "Value2"},
                {"Value1", "Value2"},
        };

        try {
            generateWorkbook(dataList, "example_output.xlsx");
            System.out.println("Workbook saved successfully.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

ljluestc avatar Nov 30 '24 00:11 ljluestc