我正在尝试使用openxlsx
(或xlsx
或其他包)包将数据框导出到Excel电子表格。我遇到的一个问题是我想将某些列设置为" text"而不是"一般"因为Excel倾向于自动格式化基因名称(即SEPT16 -> 16-Sep
(日期格式))。
openxlsx
文档提供了一些示例,用于将列类设置为" currency"," accounting"," hyperlink"," percentage& #34;,或"科学",但没有明确指出" text"。我已经尝试将课程设置为" text"或"字符",但输出的Excel列仍然是" general"。最初,正确的文本存在,但如果我在单元格中编辑任何内容,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")
答案 0 :(得分:2)
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")