2014-05-14 187 views
0

我正在从使用apache POI库的java代码创建Excel报表。格式化Excel单元格时遇到问题。请在下面找到一段代码。Excel表单格式化使用Apache POI

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工作表中得到的影响。

在此先感谢。

回答

0

您需要设置的颜色是这样的:

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

这一点,你需要填充图案

+0

感谢@详细模式多数民众赞成fillmattern罚款。我们是否有类似的方法来添加边框并使单元格数据变为粗体? – prathap

+0

您需要为样式添加字体(XSSFFont valueCellFont =(XSSFFont)workbook.createFont()) - 您可以将字体配置为粗体。 XSSFCellStyle也有设置边界的方法 – Mirco

2

试试吧,波纹管的工作对我罚款:

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(); } 
    } 
} 
+0

感谢回应迈克尔。我也尝试过使用'CellStyle',但同样的问题,格式不受影响,虽然我可以看到单元格中的单元格数据。 – prathap

+0

@prathap查看更新的答案/它对我的工作很好 –

+0

是的迈克尔你的代码适用于正常的'表',但对于我的xssfsheet上面的代码与getIndex不能正常工作,并从@verbose答案我认为我们需要明确使用'setFillPattern'。 – prathap