Excel表格格式化使用apache POI



我正在使用apache POI库从java代码创建excel报告。我遇到了一个问题,而格式化excel单元格。请查看下面的代码

    XSSFWorkbook workbook = new XSSFWorkbook();
    XSSFSheet sheet = workbook.createSheet("coverageData");
    int rownum = 0,cellnum=0;
    Row row1 = sheet.createRow(rownum++);
    Cell cell10 = row1.createCell(cellnum++);
    cell10.setCellValue("cell data");
    XSSFCellStyle row1style = (XSSFCellStyle)cell10.getCellStyle();
    XSSFColor grayColor = new XSSFColor(Color.DARK_GRAY);
    row1style.setFillBackgroundColor(grayColor);
    cell10.setCellStyle(row1style);
    try         
    {             
        //Write the workbook in file system
        FileOutputStream out = new FileOutputStream(new File("P:\automation\Spreadsheet.xlsx"));
        workbook.write(out); 
        out.close(); 
        System.out.println("Spreadsheet.xlsx written successfully on disk."); 
    }   
    catch (Exception e)
    {  
        e.printStackTrace();
    } 

这里的问题是我在最后一行代码中设置cell10样式,但它不会在程序创建的excel工作表中受到影响。

试一试,下面的工作对我来说很好:

import java.io.File;
import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class TestClass {
    public static void main(String[] args){
        Workbook wb = new XSSFWorkbook();
        Sheet sheet = wb.createSheet("coverageData");
        int rownum = 0,cellnum=0;
        Row row1 = sheet.createRow((short)rownum++);
        //Set Color style start
        CellStyle row1style = wb.createCellStyle();
        row1style.setFillBackgroundColor(IndexedColors.LIGHT_GREEN.getIndex());
        row1style.setFillPattern(CellStyle.BIG_SPOTS);
        //Set Color style end
        Cell cell10 = row1.createCell((short)cellnum++);
        cell10.setCellStyle(row1style);
        cell10.setCellValue("cell data");
        try{             
            //Write the workbook in file system
            FileOutputStream out = new FileOutputStream(new File("Spreadsheet.xlsx"));
            wb.write(out); 
            out.close(); 
            System.out.println("Spreadsheet.xlsx written successfully on disk."); 
        } catch (Exception e) { e.printStackTrace(); } 
    }
}

你需要像这样设置颜色:

final XSSFCellStyle description = (XSSFCellStyle) workbook.createCellStyle();
description.setFillForegroundColor( yourColor );
description.setFillPattern( FillPatternType.SOLID_FOREGROUND );

你需要一个填充样式

最新更新