使用java在Excel工作表中着色列名

时间:2015-01-22 07:33:39

标签: java excel apache-poi

我使用java在excel表中存储一些文件。我需要为列的名称着色。我怎么处理这个。我想用不同的颜色为不同的列着色。

resultMap.put("Question", question);
resultMap.put("Option a", options.get(0));
resultMap.put("Option b", options.get(1));
resultMap.put("Option c", options.get(2));
resultMap.put("Option d", options.get(3));

问题,选项a,选项b,选项c,选项d是我存储的五列。 excel表格为.xlsx格式

XSSFWorkbook myWorkBook = new XSSFWorkbook ();

            // Return first sheet from the XLSX workbook
XSSFSheet mySheet = myWorkBook.createSheet(sheetName);
XSSFRow row = mySheet.createRow(0);
row.createCell(7).setCellValue("Question");
row.createCell(8).setCellValue("Option a");
row.createCell(9).setCellValue("Option b");
row.createCell(10).setCellValue("Option c");
row.createCell(11).setCellValue("Option d");
FileOutputStream fileOut = new FileOutputStream(outputFilePath);
myWorkBook.write(fileOut);
fileOut.close();
myWorkBook.close();

1 个答案:

答案 0 :(得分:1)

假设您使用的是Apache POI,您可以执行以下操作,或者查看此页面以获取更多信息和示例:http://poi.apache.org/spreadsheet/quick-guide.html#FillsAndFrills

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

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
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 ExCell {

/**
 * @param args
 * @throws IOException 
 */
public static void main(String[] args) throws IOException {

    Workbook myWorkBook = new XSSFWorkbook();

    Sheet mySheet = myWorkBook.createSheet("Main");
    Row row = mySheet.createRow(0);

    Font font = myWorkBook.createFont();
    font.setColor(IndexedColors.BLUE.getIndex());
    CellStyle style = myWorkBook.createCellStyle();
    style.setFillPattern(CellStyle.SOLID_FOREGROUND);
    style.setFillForegroundColor(IndexedColors.YELLOW.getIndex());
    style.setFont(font);

    Cell newCell = row.createCell(7);
    newCell.setCellValue("Question");
    newCell.setCellStyle(style);

    row.createCell(8).setCellValue("Option a");
    row.createCell(9).setCellValue("Option b");
    row.createCell(10).setCellValue("Option c");
    row.createCell(11).setCellValue("Option d");

    FileOutputStream fileOut = new FileOutputStream("Sandeep.xlsx");

    myWorkBook.write(fileOut);
    fileOut.close();
    myWorkBook.close();

    System.out.println("Done");
}

}