简体   繁体   English

R:使用openxlsx将数据导出为“文本”

[英]R: Export data as “text” using openxlsx

I am trying to use openxlsx (or xlsx or other package) package to export data frames to excel spreadsheets. 我正在尝试使用openxlsx (或xlsx或其他包)包将数据框导出到excel电子表格。 One problem that I have is that I want to set certain columns to "text" rather than "general" because Excel has a tendency to automatically format gene names (ie SEPT16 -> 16-Sep (date format)). 我遇到的一个问题是,我想将某些列设置为“文本”而不​​是“常规”,因为Excel倾向于自动格式化基因名称(即SEPT16 -> 16-Sep (日期格式))。

The openxlsx documentation has some examples for setting column classes to "currency", "accounting", "hyperlink", "percentage", or "scientific", but not explicitly to "text". openxlsx文档提供了一些示例,用于将列类设置为“ currency”,“ accounting”,“ hyperlink”,“ percentage”或“ scientific”,但未明确设置为“ text”。 I've tried setting the class to "text" or "character", but the output Excel column is still "general". 我尝试将类设置为“文本”或“字符”,但输出Excel列仍为“常规”。 Initially, the correct text is there, but if I edit anything in the cell, Excel automatically formats these cells. 最初,正确的文本在那里,但是如果我在单元格中编辑任何内容,Excel会自动设置这些单元格的格式。

library(openxlsx)

df <- data.frame(gene   = c("SEPT16", "MARCH10", "GATA4"),
                 pvalue = c(0.0123, 0.2315, 0.00001),
                 stringsAsFactors = FALSE)

class(df$gene)   <- "text"         # Doesn't work
class(df$pvalue) <- "scientific"

wb    <- openxlsx::createWorkbook()
sheet <- openxlsx::addWorksheet(wb, "test")
openxlsx::writeDataTable(wb         = wb, 
                         sheet      = "test",
                         x          = df)
openxlsx::saveWorkbook(wb, "example_table.xlsx")

openxlsx does allow for text formatting, but it requires a couple of steps: openxlsx确实允许文本格式设置,但是它需要几个步骤:

  • Create a workbook-object wb and create a tab ( sheet ) for it 创建一个工作簿对象wb并为其创建一个选项卡(工作
  • Create the cell formatting ( cell style ) you wish to use. 创建您要使用的单元格格式( 单元格样式 )。 For text formatting: use numFmt = '@' . 对于文本格式:使用numFmt ='@'
  • Assign ( write ) some data to a sheet in your workbook-object wb 将一些数据分配( 写入 )到工作簿对象wb中的工作表
  • Identify the cell ranges for each cell style and assign the cell style to them 确定每种单元格样式的单元格范围并为其分配单元格样式

Sample code 样例代码

# Create workbook & sheet:
wb    <- openxlsx::createWorkbook()
sheet <- openxlsx::addWorksheet(wb, "test")

# Create the cell style
textstyle <- openxlsx::createStyle(fontName = "Arial", fontSize = 7, numFmt = "@")

# Assign df to workbook
openxlsx::writeDataTable(wb = wb, sheet = "test", x = df)

# First identify the range of the 'text cells':
textcells <- expand.grid(row = c(1,3,5), col = c(1,2,3,4,5))

# Then assign 'textstyle' to the 'textcells-range':
openxlsx::addStyle(wb = wb, sheet = "test", 
                   rows = textcells$row, cols = textcells$col, 
                   style = textstyle) 

# Save the workbook
openxlsx::saveWorkbook(wb, "example_table.xlsx")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM