如何 使用POI 设置docx文档中table cellcell文本的颜色

关于POI操作xlsx文件,获取字体颜色
[问题点数:40分,结帖人soft53ears]
本版专家分:92
结帖率 100%
CSDN今日推荐
本版专家分:92
结帖率 100%
本版专家分:1709
本版专家分:92
结帖率 100%
本版专家分:92
结帖率 100%
本版专家分:538
本版专家分:538
本版专家分:538
本版专家分:92
结帖率 100%
本版专家分:92
结帖率 100%
匿名用户不能发表回复!|
CSDN今日推荐POI中怎么使用自定义字体颜色_百度知道
POI中怎么使用自定义字体颜色
我有更好的答案
String str = &#3366FF&;//处理把它转换成十六进制并放入一个数int[] color=new int[3];color[0]=Integer.parseInt(str.substring(1, 3), 16);color[1]=Integer.parseInt(str.substring(3, 5), 16);color[2]=Integer.parseInt(str.substring(5, 7), 16);//自定义颜色HSSFPalette palette = workbook.getCustomPalette();palette.setColorAtIndex(HSSFColor.BLACK.index,(byte)color[0], (byte)color[1], (byte)color[2]);//将自定义的颜色引入进来HSSFFont font=workbook.createFont();font.setColor(HSSFColor.BLACK.index);HSSFCellStyle cellStyle=workbook.createCellStyle();cellStyle.setFont(font);
采纳率:96%
来自团队:
为您推荐:
其他类似问题
换一换
回答问题,赢新手礼包
个人、企业类
违法有害信息,请在下方选择后提交
色情、暴力
我们会通过消息、邮箱等方式尽快将举报结果通知您。转:POI操作Excel : cell的背景颜色参考
POI中背景颜色设置方法如下:
HSSFCellStyle style = workbook.createCellStyle();
style.setFillBackgroundColor(HSSFColor.AQUA.index);
cell.setCellStyle(style);
颜色类型是在HSSFColor里面定义的.
HSSFColor.ROYAL_BLUE
HSSFColor.TEAL
HSSFColor.LIME
HSSFColor.PALE_BLUE
HSSFColor.AQUA
HSSFColor.GREEN
HSSFColor.TURQUOISE
HSSFColor.DARK_BLUE
HSSFColor.CORNFLOWER_BLUE
HSSFColor.OLIVE_GREEN
HSSFColor.WHITE
HSSFColor.LIGHT_TURQUOISE
HSSFColor.LEMON_CHIFFON
HSSFColor.LIGHT_GREEN
HSSFColor.BLUE
HSSFColor.DARK_RED
HSSFColor.CORAL
HSSFColor.RED
HSSFColor.LIGHT_YELLOW
HSSFColor.SKY_BLUE
HSSFColor.BROWN
HSSFColor.SEA_GREEN
HSSFColor.INDIGO
HSSFColor.MAROON
HSSFColor.GREY_80_PERCENT
HSSFColor.GREY_25_PERCENT
HSSFColor.DARK_GREEN
HSSFColor.YELLOW
HSSFColor.GOLD
HSSFColor.GREY_40_PERCENT
HSSFColor.DARK_TEAL
HSSFColor.PINK
HSSFColor.ORCHID
HSSFColor.LIGHT_BLUE
HSSFColor.LIGHT_CORNFLOWER_BLUE
HSSFColor.BLACK
HSSFColor.DARK_YELLOW
HSSFColor.VIOLET
HSSFColor.LAVENDER
HSSFColor.ROSE
HSSFColor.BLUE_GREY
HSSFColor.LIGHT_ORANGE
HSSFColor.ORANGE
HSSFColor.GREY_50_PERCENT
没有更多推荐了,希望能通过自己的分享,让更多人在软件行业中少走弯路
POI对EXCEL的操作 (重点:如何设置CELL格式为文本格式)
本例使用POI3.8,具体下载地址就不奉上了,网上一搜全是
1. 首先先创建一个Student类(此处不管是内部类,外部类都行)
class Student {
private String idCardN
/** default constructor */
public Student() {
/** full constructor */
public Student(int id, String name, String idCardNumber) {
this.name =
this.idCardNumber = idCardN
public int getId() {
public void setId(int id) {
public String getName() {
public void setName(String name) {
this.name =
public String getIdCardNumber() {
return idCardN
public void setIdCardNumber(String idCardNumber) {
this.idCardNumber = idCardN
2. 具体生成Ecel的代码和算法,此处并没有连接数据库,如果想连接数据库,在getDate()方法里改变代码就行
import java.io.FileOutputS
import java.io.IOE
import java.io.OutputS
import java.sql.SQLE
import java.util.ArrayL
import java.util.L
import javax.swing.JOptionP
import org.apache.poi.hssf.usermodel.HSSFC
import org.apache.poi.hssf.usermodel.HSSFCellS
import org.apache.poi.hssf.usermodel.HSSFDataF
import org.apache.poi.hssf.usermodel.HSSFF
import org.apache.poi.hssf.usermodel.HSSFH
import org.apache.poi.hssf.usermodel.HSSFR
import org.apache.poi.hssf.usermodel.HSSFS
import org.apache.poi.hssf.usermodel.HSSFW
public class Test {
public static final String[] tableHeader = { "序号", "学生姓名", "学生学号" };
// 创建工作本 TOS
public static HSSFWorkbook demoWorkBook = new HSSFWorkbook();
public static HSSFSheet demoSheet = demoWorkBook
.createSheet("学生信息");
// 表头的单元格个数目
public static final short cellNumber = (short) tableHeader.
// 数据库表的列数
public static final int columNumber = 1;
* 创建表头
public static void createTableHeader() {
HSSFHeader header = demoSheet.getHeader();
header.setCenter("学生信息");
HSSFRow headerRow = demoSheet.createRow(0);
for (int i = 0; i & cellN i++) {
HSSFCell headerCell = headerRow.createCell(i);
headerCell.setCellType(HSSFCell.CELL_TYPE_STRING);
headerCell.setCellValue(tableHeader[i]);
* @param cells
* @param rowIndex
public static void createTableRow(List&String& cells, short rowIndex) {
// 创建第rowIndex行
HSSFRow row = demoSheet.createRow(rowIndex);
for (int i = 0; i & cells.size(); i++) {
// 创建第i个单元格
HSSFCell cell = row.createCell(i);
if (cell.getCellType() != 1) {
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
// 新增的四句话,设置CELL格式为文本格式
HSSFCellStyle cellStyle2 = demoWorkBook.createCellStyle();
HSSFDataFormat format = demoWorkBook.createDataFormat();
cellStyle2.setDataFormat(format.getFormat("@"));
cell.setCellStyle(cellStyle2);
cell.setCellValue(cells.get(i));
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
* USE:用于获取Student的数据。。。假数据。到时候:你连接数据库的到List&Student&的数据就行了。 共生成
* 100条数据.相当于100行
public List&Student& getDate() {
List&Student& cacheList = new ArrayList&Student&();
for (int j = 0; j & 10; j++) {
Student tb = new Student();
tb.setId(j + 1);
tb.setName("张三");
tb.setIdCardNumber("");
cacheList.add(tb);
return cacheL
* 创建整个Excel表
* @throws SQLException
public void createExcelSheet() throws SQLException {
createTableHeader();
int rowIndex = 1;
List&Student& list = getDate();
for (int j = 0; j & list.size(); j++) {
List&String& listRead = new ArrayList&String&();
for (int i = 1; i &= columN i++) {
listRead.add(list.get(i).getId() + "");
listRead.add(list.get(i).getName());
listRead.add(list.get(i).getIdCardNumber());
listRead.add(rowIndex + "");
createTableRow(listRead, (short) rowIndex);
rowIndex++;
* 导出表格
* @param sheet
* @param os
* @throws IOException
public void exportExcel(HSSFSheet sheet, OutputStream os)
throws IOException {
sheet.setGridsPrinted(true);
HSSFFooter footer = sheet.getFooter();
footer.setRight("Page " + HSSFFooter.page() + " of "
+ HSSFFooter.numPages());
demoWorkBook.write(os);
public static void main(String[] args) {
String fileName = "e:\\学生信息.xls";
FileOutputStream fos =
Test pd = new Test();
pd.createExcelSheet();
fos = new FileOutputStream(fileName);
pd.exportExcel(demoSheet, fos);
JOptionPane.showMessageDialog(null, "表格已成功导出到 : " + fileName);
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "表格导出出错,错误信息 :" + e
+ "\n错误原因可能是表格已经打开。");
e.printStackTrace();
} finally {
fos.close();
} catch (Exception e) {
e.printStackTrace();
有关涉及更改EXCEL的CELL格式为字符串,如图一般情况下大家导出的EXCEL表格CELL格式通常是常规的
这个问题,通常大家都是想到既然是设置CELL格式肯定是通过cell.setCellType(HSSFCell.CELL_TYPE_STRING)然后插入数据再导出,诚然这种想法是对的,实际上不能起到任何作用,因为这个方法就是EXCEL默认的格式,写不写都一样。
第一段:Excel的单元格格式 图中的数据有数值、货币、时间、日期、文本等格式。这些数据格式在POI中的HSSFDataFormat类里都有相应的定义。
HSSFDataFormat是HSSF子项目里面定义的一个类。类HSSFDataFormat允许用户新建数据格式类型。HSSFDataFormat类包含静态方法static java.lang.String getBuiltinFormat(short index),它可以根据编号返回内置数据类型。另外static short getBuiltinFormat(java.lang.String format)方法则可以根据数据类型返回其编号,static java.util.List getBuiltinFormats()可以返回整个内置的数据格式列表。
在HSSFDataFormat里一共定义了49种内置的数据格式,如下面所示。
HSSFDataFormat的数据格式
内置数据类型
"#,##0.00"
"($#,##0_);($#,##0)"
"($#,##0_);[Red]($#,##0)"
"($#,##0.00);($#,##0.00)"
"($#,##0.00_);[Red]($#,##0.00)"
"0.00E+00"
"d-mmm-yy"
"h:mm AM/PM"
"h:mm:ss AM/PM"
"m/d/yy h:mm"
保留为过国际化用
0x17 - 0x24
"(#,##0_);(#,##0)"
"(#,##0_);[Red](#,##0)"
"(#,##0.00_);(#,##0.00)"
"(#,##0.00_);[Red](#,##0.00)"
"_($*#,##0_);_($*(#,##0);_($* \"-\"_);_(@_)"
"_(*#,##0.00_);_(*(#,##0.00);_(*\"-\"??_);_(@_)"
"_($*#,##0.00_);_($*(#,##0.00);_($*\"-\"??_);_(@_)"
"_($*#,##0.00_);_($*(#,##0.00);_($*\"-\"??_);_(@_)"
"[h]:mm:ss"
"##0.0E+0"
"@" - This is text format
在上面表中,字符串类型所对应的是数据格式为"@"(最后一行),也就是HSSFDataFormat中定义的值为0x31(49)的那行。Date类型的值的范围是0xe-0x11。
第二段:POI中Excel文件Cell的类型 在读取每一个Cell的值的时候,通过getCellType方法获得当前Cell的类型,在Excel中Cell有6种类型,如下面所示。
Cell的类型
CELL_TYPE_BLANK
CELL_TYPE_BOOLEAN
CELL_TYPE_ERROR
CELL_TYPE_FORMULA
CELL_TYPE_STRING
CELL_TYPE_NUMERIC
一般都采用CELL_TYPE_STRING和CELL_TYPE_NUMERIC类型,因为在Excel文件中只有字符串和数字。如果Cell的Type为CELL_TYPE_NUMERIC时,还需要进一步判断该Cell的数据格式,因为它有可能是Date类型,在Excel中的Date类型也是以Double类型的数字存储的。Excel中的Date表示当前时间与日相隔的天数,所以需要调用HSSFDateUtil的isCellDateFormatted方法,判断该Cell的数据格式是否是Excel Date类型。如果是,则调用getDateCellValue方法,返回一个Java类型的Date。
好了读完上面两段文字我想大家关于CELL类型和格式应该清楚了,更应该清楚的是到底怎么才能将‘设置单元格格式’改成文本然后再导出
解决方案:就是上面代码中的ExcelOut类里面createTableRow方法中的一段代码
HSSFCellStyle cellStyle2 = demoWorkBook.createCellStyle();
HSSFDataFormat format = demoWorkBook.createDataFormat();
cellStyle2.setDataFormat(format.getFormat("@"));
cell.setCellStyle(cellStyle2);
看最终导出效果图吧,点击任何一个CELL右键设置单元格格式
没有更多推荐了,By some libraries like
, we could create word document with any text color, but for background or highlight of the text, I didn't find any solution.
Page color for word in manual way!:
Here is my main code to create word document by poi.apache
// Blank Document
@SuppressWarnings("resource")
XWPFDocument document = new XWPFDocument();
// Write the Document in file system
FileOutputStream out = new FileOutputStream(new File(file_address));
// create Paragraph
XWPFParagraph paragraph = document.createParagraph();
paragraph.setAlignment(ParagraphAlignment.RIGHT);
XWPFRun run = paragraph.createRun();
run.setFontFamily(font_name);
run.setFontSize(font_size);
// This only set text color not background!
run.setColor(hex_color);
for (String s : text_array) {
run.setText(s);
run.addCarriageReturn();
document.write(out);
out.close();
解决方案 Update: XWPF is the newest way to create word document files, but setting background only possible by HWPF which is for old format version (.doc)
For *.doc (i.e. POI's HWPF component):
Highlighting of text:
Background color:
I suppose you mean the background of a paragraph (AFAIK, Word also allows to color the entire page which is a different matter)
which allows you to provide a foreground and background color (through setCvFore() and setCvBack() of SHDAbstractType) for a Paragraph. IIRC, it is the foreground that you would want to set in order to color your Paragraph. The background is only relevant for shadings which are composed of two (alternating) colors.
The underlying data structure is named Shd80 ([MS-DOC], 2.9.248). There is also SHDOperand ([MS-DOC], 2.9.249) that reflects the functionality of Word prior to Word97. [MS-DOC] is the Binary Word File format specification which is freely available on MSDN.
Here is some code to illustrate the above:
HWPFDocument document = [...]; // comes from somewhere
Range range = document.getRange();
// Background shading of a paragraph
ParagraphProperties pprops = new ParagraphProperties();
ShadingDescriptor shd = new ShadingDescriptor();
shd.setCvFore(Colorref.valueOfIco(0x07)); // ICO
shd.setIpat(0x0001); // IPAT
pprops.setShading(shd);
Paragraph p1 = range.insertBefore(pprops, StyleSheet.NIL_STYLE);
p1.insertBefore("shaded paragraph");
// Highlighting of individual characters
Paragraph p2 = range.insertBefore(new ParagraphProperties(), StyleSheet.NIL_STYLE);
CharacterRun cr = p2.insertBefore("highlighted text\r");
cr.setHighlighted((byte) 0x06); // ICO
document.write([...]); // document goes to somewhere
} catch (IOException e) {
e.printStackTrace();
is a color structure
is a list of predefined shading styles
本文地址: &
通过如一些库,我们可以创建 word文档用任何文本颜色,但对于背景或文本的亮点,我没有找到任何解决方案。页颜色以手动方式一句话: https://support.office.com/en-us/article/Change-the-background-or-color-of-a-document-6ce0b23e-b833--b3d637e62524下面是我的主要code创建由poi.apache word文档
//空白文档
@燮pressWarnings(“资源”)
XWPFDocument文档=新XWPFDocument();
//写在文件系统中的文件
FileOutputStream中出=新的FileOutputStream(新文件(file_address));
//创建段落
XWPFParagraph段= document.createParagraph();
paragraph.setAlignment(ParagraphAlignment.RIGHT);
XWPFRun运行= paragraph.createRun();
run.setFontFamily(font_name首);
run.setFontSize(FONT_SIZE);
//这个只设置文本颜色不是背景!
run.setColor(hex_color);
对于(一个String:text_array){
run.setText(多个);
run.addCarriageReturn();
文件撰写(出);
out.close(); 解决方案
更新:XWPF是创建Word文档文件的最新方法,但设置背景只能通过HWPF这是旧格式的版本( .DOC)的
有关的* .doc(即POI的HWPF分量):
文本高亮:看看
setHighlighted()
背景颜色:的我想你指的是第(据我所知,Word还允许彩色整个页面是另当别论)的背景的有
setShading() 它允许您提供一个前景色和背景色(通过 setCvFore()和 setCvBack()
SHDAbstractType )的一个段落。 IIRC,它是的前景的,你想,以你的色彩段进行设置。在背景的是仅适用于由两(交替)颜色阴影有关。底层的数据结构被命名为 Shd80 ([MS-DOC] 2.9.248)。也有反映的Word之前Word97的功能 SHDOperand ([MS-DOC] 2.9.249)。 [MS-DOC]是二进制字的文件格式规范是MSDN上免费提供的。
编辑: 下面是一些code来说明上述
HWPFDocument文件= []; //来自某处
范围范围= document.getRange();
//段落的背景底纹
ParagraphProperties pprops =新ParagraphProperties();
ShadingDescriptor SHD =新ShadingDescriptor();
shd.setCvFore(Colorref.valueOfIco(0×07)); // 黄色; ICO
shd.setIpat(0×0001); //纯色背景; IPAT
pprops.setShading(SHD);
第P1 = range.insertBefore(pprops,StyleSheet.NIL_STYLE);
p1.insertBefore(“阴影段落”);
//单个字符的突出
段P2 = range.insertBefore(新ParagraphProperties(),StyleSheet.NIL_STYLE);
CharacterRun CR = p2.insertBefore(“高亮文本\\ r”);
cr.setHighlighted((字节)0×06); //红色; ICO
的document.write([...]); //文件去的地方
}赶上(IOException异常五){
e.printStackTrace();
是一个色彩结构 是predefined底纹样式列表
本文地址: &
扫一扫关注IT屋
微信公众号搜索 “ IT屋 ” ,选择关注
与百万开发者在一起
(window.slotbydup = window.slotbydup || []).push({
id: '5828425',
container: s,
size: '300,250',
display: 'inlay-fix'

我要回帖

更多关于 自定义tableviewcell 的文章

 

随机推荐