XSSF设定单元格自定义颜色

xssf 自定义颜色


博客分类: excelpoi
 
环境:poi3.9+xssf+excel2013+template.xlsx文件
 
背景:在用poi写excel时,单元格的颜色需求是必须要模板中的一样。
 
思路:先用【颜色摘取器】将颜色的RGB摘下来,然后用XSSF实现自定义颜色即可。
 
 
1、主函数类
Java代码  收藏代码
package com.poi.excel.client;  
  
import java.awt.Color;  
import java.io.FileInputStream;  
import java.io.FileNotFoundException;  
import java.io.FileOutputStream;  
import java.io.IOException;  
import java.util.HashMap;  
import java.util.LinkedList;  
import java.util.List;  
import java.util.Map;  
  
import org.apache.poi.hssf.usermodel.HSSFPalette;  
import org.apache.poi.hssf.usermodel.HSSFWorkbook;  
import org.apache.poi.hssf.usermodel.examples.CellTypes;  
import org.apache.poi.hssf.util.HSSFColor;  
import org.apache.poi.ss.usermodel.Cell;  
import org.apache.poi.ss.usermodel.CellStyle;  
import org.apache.poi.ss.usermodel.CreationHelper;  
import org.apache.poi.ss.usermodel.DataFormat;  
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.XSSFCell;  
import org.apache.poi.xssf.usermodel.XSSFCellStyle;  
import org.apache.poi.xssf.usermodel.XSSFColor;  
import org.apache.poi.xssf.usermodel.XSSFRichTextString;  
import org.apache.poi.xssf.usermodel.XSSFRow;  
import org.apache.poi.xssf.usermodel.XSSFSheet;  
import org.apache.poi.xssf.usermodel.XSSFWorkbook;  
  
import com.poi.excel.util.POIExcelUtil;  
  
public class ExcelTestClient {  
    static org.apache.log4j.Logger logger = org.apache.log4j.Logger  
            .getLogger(ExcelTestClient.class);  
  
    public static void main(String[] args) {  
         new ExcelTestClient().writeWithExcelUtil();  
    }  
  
      
  
    private void writeWithExcelUtil() {  
  
        // 如何通过一个已有的workbook创建新的workbook  
        try {  
            // Workbook wb1=new XSSFWorkbook("oldPath");  
  
            Workbook wb = new XSSFWorkbook(new FileInputStream(  
                    "c:\\germmy\\template.xlsx"));  
            Map<String, CellStyle> styles = createStyles(wb);  
  
            // create a new sheet  
            Sheet s = wb.getSheet("机构呼入量报表");  
  
            //1.先写入左上方标题  
            String content="20151013-20151019电销呼入量报表";  
            POIExcelUtil.writeDataToExcel(0, 0, s, content,  
                    Cell.CELL_TYPE_STRING, null);//sytle用null,表明利用原有样式  
              
            //2.B4,C4,B5的值  
            double b4_db=1000,c4_db=1500,b5_db=2000;  
            //2.1 B4  
            POIExcelUtil.writeDataToExcel(3, 1, s, b4_db,  
                    Cell.CELL_TYPE_NUMERIC, styles.get("normalcell"));//sytle用null,表明利用原有样式  
            //2.2 C4  
            POIExcelUtil.writeDataToExcel(3, 2, s, c4_db,  
                    Cell.CELL_TYPE_NUMERIC, styles.get("normalcell"));//sytle用normalcell  
            //2.3 B5  
            POIExcelUtil.writeDataToExcel(4, 1, s, b5_db,  
                    Cell.CELL_TYPE_NUMERIC, styles.get("normalcell"));sytle用normalcell  
              
              
              
            //3.G4,B41的公式,  
            //3.1 g4  
            String g4="SUM(B4:F4)",b41="SUM(B4:B40)";  
            POIExcelUtil.writeDataToExcel(3, 6, s, g4,  
                    Cell.CELL_TYPE_FORMULA, styles.get("formula_v"));sytle用formula  
            //3.2 b41  
            POIExcelUtil.writeDataToExcel(40, 1, s, b41,  
                    Cell.CELL_TYPE_FORMULA, styles.get("formula_h"));sytle用formula  
              
              
  
            // Save  
            String filename = "c:/germmy/workbook.xls";  
            if (wb instanceof XSSFWorkbook) {  
                filename = filename + "x";  
            }  
  
            FileOutputStream out = new FileOutputStream(filename);  
            wb.write(out);  
            out.close();  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
    }  
  
    /** 
     * Create a library of cell styles 
     */  
    private static Map<String, CellStyle> createStyles(Workbook wb) {  
        Map<String, CellStyle> styles = new HashMap<String, CellStyle>();  
        CellStyle style;  
        Font titleFont = wb.createFont();  
        titleFont.setFontHeightInPoints((short) 18);  
        titleFont.setBoldweight(Font.BOLDWEIGHT_BOLD);  
        style = wb.createCellStyle();  
        style.setAlignment(CellStyle.ALIGN_CENTER);  
        style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);  
        style.setFont(titleFont);  
        styles.put("title", style);  
  
        Font monthFont = wb.createFont();  
        monthFont.setFontHeightInPoints((short) 11);  
        monthFont.setColor(IndexedColors.WHITE.getIndex());  
        style = wb.createCellStyle();  
        style.setAlignment(CellStyle.ALIGN_CENTER);  
        style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);  
        style.setFillForegroundColor(IndexedColors.GREY_50_PERCENT.getIndex());  
        style.setFillPattern(CellStyle.SOLID_FOREGROUND);  
        style.setFont(monthFont);  
        style.setWrapText(true);  
        styles.put("header", style);  
  
        style = wb.createCellStyle();  
        style.setAlignment(CellStyle.ALIGN_CENTER);  
        style.setWrapText(true);  
        style.setBorderRight(CellStyle.BORDER_THIN);  
        style.setRightBorderColor(IndexedColors.BLACK.getIndex());  
        style.setBorderLeft(CellStyle.BORDER_THIN);  
        style.setLeftBorderColor(IndexedColors.BLACK.getIndex());  
        style.setBorderTop(CellStyle.BORDER_THIN);  
        style.setTopBorderColor(IndexedColors.BLACK.getIndex());  
        style.setBorderBottom(CellStyle.BORDER_THIN);  
        style.setBottomBorderColor(IndexedColors.BLACK.getIndex());  
        styles.put("cell", style);  
  
        style = wb.createCellStyle();  
        style.setAlignment(CellStyle.ALIGN_CENTER);  
        style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);  
        style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());  
        style.setFillPattern(CellStyle.SOLID_FOREGROUND);  
        style.setDataFormat(wb.createDataFormat().getFormat("0.00"));  
        styles.put("formula", style);  
  
          
          
        //*********************add by germmy@20131013 start************************  
        //普通单元格,四周有黑线  
        style = wb.createCellStyle();  
        style.setAlignment(CellStyle.ALIGN_RIGHT);  
        style.setWrapText(true);  
        style.setBorderRight(CellStyle.BORDER_THIN);  
        style.setRightBorderColor(IndexedColors.BLACK.getIndex());  
        style.setBorderLeft(CellStyle.BORDER_THIN);  
        style.setLeftBorderColor(IndexedColors.BLACK.getIndex());  
        style.setBorderTop(CellStyle.BORDER_THIN);  
        style.setTopBorderColor(IndexedColors.BLACK.getIndex());  
        style.setBorderBottom(CellStyle.BORDER_THIN);  
        style.setBottomBorderColor(IndexedColors.BLACK.getIndex());  
        style.setDataFormat(wb.createDataFormat().getFormat("#,##0"));//这样写百分百变成货币  
        styles.put("normalcell", style);  
          
        //横向求和公式,粗体,有淡紫色背景,四周有黑色  
        style = wb.createCellStyle();  
        XSSFCellStyle styleTemp=((XSSFCellStyle)style);  
        styleTemp.setAlignment(CellStyle.ALIGN_RIGHT);  
        styleTemp.setVerticalAlignment(CellStyle.VERTICAL_CENTER);  
        Font formulaFont = wb.createFont();  
        formulaFont.setFontName("宋体");  
        formulaFont.setFontHeightInPoints((short) 11);  
        formulaFont.setBoldweight(Font.BOLDWEIGHT_BOLD);  
        styleTemp.setFont(formulaFont);  
        //控制颜色  
        styleTemp.setFillForegroundColor(new XSSFColor( new Color(220, 230, 241)));  
//      style.setFillForegroundColor(IndexedColors.LIGHT_TURQUOISE.getIndex());  
        styleTemp.setFillPattern(CellStyle.SOLID_FOREGROUND);  
          
        styleTemp.setBorderRight(CellStyle.BORDER_THIN);  
        styleTemp.setRightBorderColor(IndexedColors.BLACK.getIndex());  
        styleTemp.setBorderLeft(CellStyle.BORDER_THIN);  
        styleTemp.setLeftBorderColor(IndexedColors.BLACK.getIndex());  
        styleTemp.setBorderTop(CellStyle.BORDER_THIN);  
        styleTemp.setTopBorderColor(IndexedColors.BLACK.getIndex());  
        styleTemp.setBorderBottom(CellStyle.BORDER_THIN);  
        styleTemp.setBottomBorderColor(IndexedColors.BLACK.getIndex());  
        styleTemp.setDataFormat(wb.createDataFormat().getFormat("#,##0"));  
        styles.put("formula_h", styleTemp);//横向的公式颜色  
          
        //纵向求和公式,四周有黑线  
        style = wb.createCellStyle();  
        style.setAlignment(CellStyle.ALIGN_RIGHT);  
        style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);  
        style.setBorderRight(CellStyle.BORDER_THIN);  
        style.setRightBorderColor(IndexedColors.BLACK.getIndex());  
        style.setBorderLeft(CellStyle.BORDER_THIN);  
        style.setLeftBorderColor(IndexedColors.BLACK.getIndex());  
        style.setBorderTop(CellStyle.BORDER_THIN);  
        style.setTopBorderColor(IndexedColors.BLACK.getIndex());  
        style.setBorderBottom(CellStyle.BORDER_THIN);  
        style.setBottomBorderColor(IndexedColors.BLACK.getIndex());  
        style.setDataFormat(wb.createDataFormat().getFormat("#,##0"));  
        styles.put("formula_v", style);//纵向的公式颜色  
          
          
          
        //*********************add by germmy@20131013 end************************  
        style = wb.createCellStyle();  
        style.setAlignment(CellStyle.ALIGN_CENTER);  
        style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);  
        style.setFillForegroundColor(IndexedColors.GREY_40_PERCENT.getIndex());  
        style.setFillPattern(CellStyle.SOLID_FOREGROUND);  
        style.setDataFormat(wb.createDataFormat().getFormat("0.00"));  
        styles.put("formula_2", style);  
  
          
          
          
        return styles;  
    }  
  
}  
 
 
2、ExcelUtil文件:
Java代码  收藏代码
package com.poi.excel.util;  
  
import org.apache.poi.ss.usermodel.Cell;  
import org.apache.poi.ss.usermodel.CellStyle;  
import org.apache.poi.ss.usermodel.Row;  
import org.apache.poi.ss.usermodel.Sheet;  
  
public class POIExcelUtil {  
  
    /** 
     *  
     * @param row 
     * @param column 
     * @param sheet 
     * @param content 
     * @param cellTypes 
     * @param cellStyle 
     * @throws Exception 
     */  
    public static void writeDataToExcel(int row, int column, Sheet sheet,  
            Object content, int cellType, CellStyle cellStyle) throws Exception {  
        Row r1 = sheet.getRow(row);  
        Cell c1 = r1.getCell(column);  
        if (null != cellStyle) {  
            c1.setCellStyle(cellStyle);  
        }  
        switch (cellType) {  
        case Cell.CELL_TYPE_NUMERIC:  
            c1.setCellValue((double) content);  
            break;  
        case Cell.CELL_TYPE_STRING:  
            c1.setCellValue((String) content);  
            break;  
        case Cell.CELL_TYPE_FORMULA:  
            c1.setCellFormula((String) content);  
            break;  
        default:  
            c1.setCellValue((String) content);//默认的先暂时全用这个  
            System.out.println("未匹配到东西!");  
            break;  
        }  
    }  
  
}  
 
 
3、JAR包下载地址:http://www.apache.org/dyn/closer.cgi/poi/release/bin/poi-bin-3.9-20121203.zip
 
-----------------------------------------------------------------------------------------------------------------
其他参考文档:
1、http://poi.apache.org/spreadsheet/examples.html
2、http://blog.sina.com.cn/s/blog_62c89b450100lxnh.html
3、http://kxjhlele.iteye.com/blog/321392
4、http://www.docin.com/p-69674027.html
5、http://bbs.csdn.net/topics/360031211
6、http://fangwei.iteye.com/blog/1161085
 
 
--------------------------------------------------------------------------------------------------------------
ps:颜色提取器 http://www.douban.com/group/topic/6338619/
  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
提供的源码资源涵盖了Java应用等多个领域,每个领域都包含了丰富的实例和项目。这些源码都是基于各自平台的最新技术和标准编写,确保了在对应环境下能够无缝运行。同时,源码中配备了详细的注释和文档,帮助用户快速理解代码结构和实现逻辑。 适用人群: 适合毕业设计、课程设计作业。这些源码资源特别适合大学生群体。无论你是计算机相关专业的学生,还是对其他领域编程感兴趣的学生,这些资源都能为你提供宝贵的学习和实践机会。通过学习和运行这些源码,你可以掌握各平台开发的基础知识,提升编程能力和项目实战经验。 使用场景及目标: 在学习阶段,你可以利用这些源码资源进行课程实践、课外项目或毕业设计。通过分析和运行源码,你将深入了解各平台开发的技术细节和最佳实践,逐步培养起自己的项目开发和问题解决能力。此外,在求职或创业过程中,具备跨平台开发能力的大学生将更具竞争力。 其他说明: 为了确保源码资源的可运行性和易用性,特别注意了以下几点:首先,每份源码都提供了详细的运行环境和依赖说明,确保用户能够轻松搭建起开发环境;其次,源码中的注释和文档都非常完善,方便用户快速上手和理解代码;最后,我会定期更新这些源码资源,以适应各平台技术的最新发展和市场需求。 所有源码均经过严格测试,可以直接运行,可以放心下载使用。有任何使用问题欢迎随时与博主沟通,第一时间进行解答!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值