[英]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
确实允许文本格式设置,但是它需要几个步骤:
wb
and create a tab ( sheet ) for it wb
并为其创建一个选项卡(工作表 ) wb
wb
中的工作表 # 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.