如何使用flextable包设置表格列的固定宽度
解决Shiny中rhandsontable固定第一列宽度为1.5英寸的问题
你当前代码里的核心问题是:虽然对df1、df2做了flextable的列宽设置,但实际Shiny页面输出的是rhandsontable组件,flextable的配置完全不会作用到rhandsontable上,这就是列宽没按预期生效的原因。
要实现rhandsontable第一列固定为1.5英寸的宽度,需要针对rhandsontable本身做配置——rhandsontable默认用像素作为宽度单位,1英寸≈96像素,所以1.5英寸对应144像素,具体修改方案如下:
修改后的完整代码
library(shinydashboard) library(shiny) library(rhandsontable) library(data.table) # 补充原代码遗漏的依赖包 df1 = data.table( "Column1"= as.character(), "Column2"= as.numeric(), "Column3"= as.character() ) df2 = data.table( "Column1"= as.character(), "Column2"= as.numeric(), "Column3"= as.character() ) ui <- dashboardPage( dashboardHeader(title = "Assets"), dashboardSidebar( menuItem("Home", tabName = "home"), menuItem("Current assets", tabName = "CurrentAssets", menuSubItem("Inventory", tabName = "inventory") ) ), dashboardBody( tabItems( tabItem( tabName = "inventory", column( width = 7, "df1", rHandsontableOutput("Table1") ), column( width = 7, "df2", rHandsontableOutput("Table2") ) ) ) ) ) server <- function(input, output, session) { output$Table1 <- renderRHandsontable({ # 第一列设为144像素(≈1.5英寸),其余列自适应 rhandsontable(df1, stretchH="all") %>% hot_cols(col_widths = c(144, NULL, NULL)) }) output$Table2 <- renderRHandsontable({ # 同样设置第一列宽度为144像素 rhandsontable(df2, stretchH="all") %>% hot_cols(col_widths = c(144, NULL, NULL)) }) } shinyApp(ui, server)
关键说明
- 单位转换:rhandsontable不直接支持英寸单位,所以用
1.5 * 96 = 144像素来对应1.5英寸的宽度。 hot_cols(col_widths = c(144, NULL, NULL)):第一个值指定第一列的固定宽度,后面的NULL表示让剩余列自适应容器宽度,你也可以给其他列设置具体的像素值。- 冗余代码清理:原代码中对df1、df2的flextable操作没有实际作用,直接删除即可。
- 依赖补充:原代码使用了
data.table但未加载,必须添加library(data.table)保证代码正常运行。
内容的提问来源于stack exchange,提问作者firuz.safaev
相关产品推荐
相关产品推荐

