openxlsx::writeData写数据框时仅表头生效样式,如何为内容设置缩进、加粗、字号类自定义格式
全表格自定义单元格样式实现方案
问题根源
- 现有
writeData()调用中,headerStyle参数仅对表头行生效,数据单元格未绑定自定义样式,因此沿用Excel默认格式。
实现步骤
1. 定义数据单元格专属样式
使用openxlsx::createStyle()创建数据区域样式,可直接配置缩进、字号、加粗等所需属性,示例:
# 数据单元格样式示例,可按需修改参数 data_style = openxlsx::createStyle( indent = 1, # 缩进级别,为整数,对应Excel单元格缩进设置 fontSize = 11, # 数据字号 fontColour = "#000000", halign = "left", # 水平对齐,可选center/right valign = "center", # 垂直对齐 border = "TopBottomLeftRight", borderColour = "black", textDecoration = "normal", # 数据若需加粗改为"bold"即可 wrapText = TRUE # 按需开启自动换行 )
两个工作表样式一致的话,仅需创建一次该样式对象即可复用。
2. 计算数据区域范围
写入数据后,需先明确数据区域的行列边界,再绑定样式:
- 行范围:表头行对应设置的
startRow,数据行从startRow + 1(表头下一行)开始,到startRow + nrow(目标数据框)结束 - 列范围:从设置的
startCol开始,到startCol + ncol(目标数据框) - 1结束
3. 调整后完整代码示例
# 原有表头样式保留 h1 = openxlsx::createStyle( fontSize = 12, fontColour = "#FFFFFF", halign = "center", fgFill = "#4F81BD", border = "TopBottomLeftRight", borderColour = "#4F81BD", valign = "center", textDecoration = "bold", wrapText = FALSE ) # 新增数据单元格自定义样式 data_style = openxlsx::createStyle( indent = 1, fontSize = 11, halign = "left", valign = "center", border = "TopBottomLeftRight", borderColour = "black", textDecoration = "normal" ) # 写入sheet1的df1 openxlsx::writeData( wb1, 'sheet1', df1, startCol = 4, startRow = 6, headerStyle = h1 ) # 为sheet1数据区域应用样式 openxlsx::addStyle( wb = wb1, sheet = 'sheet1', style = data_style, cols = 4:(4 + ncol(df1) - 1), rows = 7:(6 + nrow(df1)) ) # 写入sheet2的df2 openxlsx::writeData( wb1, 'sheet2', df2, startCol = 5, startRow = 6, headerStyle = h1 ) # 为sheet2数据区域复用同一样式 openxlsx::addStyle( wb = wb1, sheet = 'sheet2', style = data_style, cols = 5:(5 + ncol(df2) - 1), rows = 7:(6 + nrow(df2)) )
样式调整对应参数
- 缩进层级:修改
indent参数值,整数越大缩进越深 - 数据加粗:将
data_style中textDecoration改为"bold" - 字号调整:修改
fontSize参数数值 - 对齐方式:调整
halign(水平)、valign(垂直)的参数值 - 自动换行:按需设置
wrapText = TRUE/FALSE
内容的提问来源于stack exchange,提问作者MSM
相关产品推荐
相关产品推荐

