1

我正在尝试以正确的方式格式化 excel 文件中的列。首先,恐怕Excel会将一些奇怪的基因名称作为科学中经常发生的日期。因此,通常,当从 txt 文件将数据导入 excel 时,我选择基因名称列并将单元格类型从一般更改为文本以保存。当我现在使用 . 创建我的 excel 表xlsx时,恐怕这会发生。目前我试图重现这种行为,但所有列都被格式化为一般格式,但我希望将特定列强制为文本。

这有可能吗?

df <- data.frame(a=c(1,2),
                 b=c('SEPT2', 'MARCH1'),
                 c=c('1,2', '1,4'),
                 d=c('1.2', '1.4'),
                 e=c('2-SEP', '1-MARCH'),
                 f=c('APR-1', 'DEC-1'))
wb <- xlsx::createWorkbook()
sheet1 <- xlsx::createSheet(wb, sheetName='test')
xlsx::addDataFrame(df, sheet1, 
                   col.names=TRUE, row.names=FALSE)
xlsx::saveWorkbook(wb, 'test.xlsx')

我很想将 b、e 和 f 列格式化为文本。

编辑

因为我在评论中询问,如何找到更多格式值,例如科学记数法,我在这里找到了这个。

text_format = CellStyle(wb, dataFormat=DataFormat("@"))
scientific_format <- CellStyle(wb, dataFormat=DataFormat('0.00E+00'))
4

1 回答 1

1

您只需要创建格式规范并将其addDataFramecolStyle参数一起添加。

wb <- xlsx::createWorkbook()
sheet1 <- xlsx::createSheet(wb, sheetName='test')

## Create the format specification
TextFormat = CellStyle(wb, dataFormat=DataFormat("@"))
FormatList = list('2'=TextFormat, '5'=TextFormat,'6' = TextFormat)

xlsx::addDataFrame(df, sheet1, col.names=TRUE, colStyle=FormatList, 
    row.names=FALSE)
xlsx::saveWorkbook(wb, 'test.xlsx')

注意:“@”是文本格式的代码。

于 2017-08-21T18:31:29.740 回答