I am trying to use openxlsx (or xlsx or other package) package to export data frames to excel spreadsheets. 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 (i.e SEPT16 -> 16-Sep (date format)).
The openxlsx documentation has some examples for setting column classes to "currency", "accounting", "hyperlink", "percentage", or "scientific", but not explicitly to "text". I've tried setting the class to "text" or "character", but the output Excel column is still "general". Initially, the correct text is there, but if I edit anything in the cell, Excel automatically formats these cells.
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:
wb and create a tab (sheet) for itwb# 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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With