POI如何自定义单元格背景颜色
提出問題
POI如何自定義單元格背景顏色???
解決問題
例一:具體的看注釋
import org.apache.poi.hssf.usermodel.*; import org.apache.poi.hssf.util.HSSFColor; ? import java.io.FileOutputStream; ? /** * Created by Ay on 2016/4/29. */ public class PoiBackgroundColorTest { ? public static void main(String[] args) throws Exception{ //創建一份 HSSFWorkbook excel = new HSSFWorkbook(); //創建第一個sheet HSSFSheet sheet = excel.createSheet("我的POI之旅"); //創建第一行 HSSFRow row = sheet.createRow((short) 0); //創建第一個單元格 HSSFCell cell = row.createCell((short) 0); //設置單元格的值 cell.setCellValue("Ay"); //生成單元格樣式 HSSFCellStyle style = excel.createCellStyle(); //設置背景顏色 style.setFillForegroundColor(HSSFColor.LIME.index); //solid 填充 foreground 前景色 style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); cell.setCellStyle(style); //通過流寫到硬盤 FileOutputStream out = new FileOutputStream("D:/old_color.xls"); excel.write(out); out.close(); ? //====== 這里是重點,馬上要自定義單元格的樣式了 ============= cell.setCellValue("Al"); //拿到palette顏色板 HSSFPalette palette = excel.getCustomPalette(); //這個是重點,具體的就是把之前的顏色 HSSFColor.LIME.index //替換為 RGB(51,204,204) 寶石藍這種顏色 //你可以改為 RGB(0,255,127) palette.setColorAtIndex(HSSFColor.LIME.index, (byte) 0, (byte) 255, (byte) 127); //====== 這里是重點,馬上要自定義單元格的樣式了 ============= out = new FileOutputStream("D:/new_color.xls"); excel.write(out); out.close(); } } |
?
D:/old_color.xls 結果
?
D:/new_color.xls 結果
總結
以上是生活随笔為你收集整理的POI如何自定义单元格背景颜色的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java 如何将String转化为Int
- 下一篇: POI操作Excel:cell的背景颜色