![](/img/trans.png)
[英]Export dataframe as excel sheet in r using openxlsx and recognize numeric cells as numbers (get rid of numbers formatted as text error)
[英]R: Export data as “text” using openxlsx
我正在尝试使用openxlsx
(或xlsx
或其他包)包将数据框导出到excel电子表格。 我遇到的一个问题是,我想将某些列设置为“文本”而不是“常规”,因为Excel倾向于自动格式化基因名称(即SEPT16 -> 16-Sep
(日期格式))。
openxlsx
文档提供了一些示例,用于将列类设置为“ currency”,“ accounting”,“ hyperlink”,“ percentage”或“ scientific”,但未明确设置为“ text”。 我尝试将类设置为“文本”或“字符”,但输出Excel列仍为“常规”。 最初,正确的文本在那里,但是如果我在单元格中编辑任何内容,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
确实允许文本格式设置,但是它需要几个步骤:
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.