setwd("C:/data/rdata/我的R/openxlsx/")
###################加载包#############################
library(ggplot2)#图层语法数据可视化
library(ggthemes)#ggplot2主题包
library(tidyr)#数据框拉长与拉宽
library(readr)#高性能读写数据包
library(readxl)#高性能读写excel包
library(data.table)#高性能分组计算包
library(plyr)#分组计算包,比data.table速度慢,但是语法方便些
library(xlsx)#读写excel文件包,需要安装java
library(dplyr)#plyr包升级版
library(stringr)#文本处理包,支持正则表达式
#library(maptools)
library(openxlsx)
#已经命名的所有的颜色变量都在colours()中
#read.xlsx Read from an Excel file or Workbook object---------------------
#read.xlsx(xlsxFile, sheet = 1, startRow = 1, colNames = TRUE, rowNames = FALSE, detectDates = FALSE, skipEmptyRows = TRUE, skipEmptyCols = TRUE, rows = NULL, cols = NULL, check.names = FALSE, namedRegion = NULL, na.strings = "NA", fillMergedCells = FALSE)
#write.xlsx -----------------------------
## write to working directory
options("openxlsx.borderColour" = "#4F80BD")
## set default border colour
write.xlsx(iris, file = "writeXLSX1.xlsx", colNames = TRUE, borders = "columns")
write.xlsx(iris, file = "writeXLSX2.xlsx", colNames = TRUE, borders = "surrounding")
hs <- createStyle(textDecoration = "BOLD", fontColour = "#FFFFFF", fontSize=12, fontName="Arial Narrow", fgFill = "#4F80BD")
write.xlsx(iris, file = "writeXLSX3.xlsx", colNames = TRUE, borders = "rows", headerStyle = hs)
## Lists elements are written to individual worksheets, using list names as sheet names if available
l <- list("IRIS" = iris, "MTCATS" = mtcars, matrix(runif(1000), ncol = 5))
write.xlsx(l, "writeList1.xlsx", colWidths = c(NA, "auto", "auto"))
## different sheets can be given different parameters
write.xlsx(l, "writeList2.xlsx", startCol = c(1,2,3), startRow = 2,asTable = c(TRUE, TRUE, FALSE), withFilter = c(TRUE, FALSE, FALSE))
#writeData Write an object to a worksheet---------------------------
#writeData(wb, sheet, x, startCol = 1, startRow = 1, xy = NULL, colNames = TRUE, rowNames = FALSE, headerStyle = NULL, borders = c("none", "surrounding", "rows", "columns", "all"), borderColour = getOption("openxlsx.borderColour", "black"), borderStyle = getOption("openxlsx.borderStyle", "thin"),withFilter = FALSE, keepNA = FALSE, name = NULL, sep = ", ")
## Create Workbook object and add worksheets
wb <- createWorkbook()
## Add worksheets
addWorksheet(wb, "Cars")
addWorksheet(wb, "Formula")
x <- mtcars[1:6,]
writeData(wb, "Cars", x, startCol = 2, startRow = 3, rowNames = TRUE)
##################################################################################### ## Bordering
writeData(wb, "Cars", x, rowNames = TRUE, startCol = "O", startRow = 3, borders="surrounding", borderColour = "black") ## black border
writeData(wb, "Cars", x, rowNames = TRUE, startCol = 2, startRow = 12, borders="columns")
writeData(wb, "Cars", x, rowNames = TRUE,
startCol="O", startRow = 12, borders="rows")
## Header Styles
hs1 <- createStyle(fgFill = "#DCE6F1", halign = "CENTER", textDecoration = "italic", border = "Bottom")
writeData(wb, "Cars", x, colNames = TRUE, rowNames = TRUE, startCol="B", startRow = 23, borders="rows", headerStyle = hs1, borderStyle = "dashed")
hs2 <- createStyle(fontColour = "#ffffff", fgFill = "#4F80BD", halign = "center", valign = "center", textDecoration = "bold", border = "TopBottomLeftRight")
writeData(wb, "Cars", x, colNames = TRUE, rowNames = TRUE,startCol="O", startRow = 23, borders="columns", headerStyle = hs2)
saveWorkbook(wb, "writeDataExample.xlsx", overwrite = TRUE)
#readWorkbook Read from an Excel file or Workbook object----------------------
#readWorkbook(xlsxFile, sheet = 1, startRow = 1, colNames = TRUE, rowNames = FALSE, detectDates = FALSE, skipEmptyRows = TRUE, skipEmptyCols = TRUE, rows = NULL, cols = NULL, check.names = FALSE,namedRegion = NULL, na.strings = "NA", fillMergedCells = FALSE)
xlsxFile <- system.file("readTest.xlsx", package = "openxlsx")
df1 <- readWorkbook(xlsxFile = xlsxFile, sheet = 1)
xlsxFile <- system.file("readTest.xlsx", package = "openxlsx")
df1 <- readWorkbook(xlsxFile = xlsxFile, sheet = 1, rows = c(1, 3, 5), cols = 1:3)
#addStyle Add a style to a set ofcells------------------
#输出的工作本中工作表列有筛选功能
if(file.exists("addFilterExample.xlsx")){
file.remove("addFilterExample.xlsx")
}
wb <- createWorkbook()
addWorksheet(wb, "Sheet 1")
addWorksheet(wb, "Sheet 2")
addWorksheet(wb, "Sheet 3")
writeData(wb, 1, iris)
addFilter(wb, 1, row = 1, cols = 1:ncol(iris))
## Equivalently writeData(wb, 2, x = iris, withFilter = TRUE)
## Similarly
writeDataTable(wb, 3, iris)
saveWorkbook(wb, file = "addFilterExample.xlsx", overwrite = TRUE)
#addStyle Add a style to a set ofcells-------------------
#为excel文件工作表创建主题
## See package vignette for more examples.
## Create a new workbook
wb <- createWorkbook("My name here")
## Add a worksheets
addWorksheet(wb, "Expenditure", gridLines = FALSE)
#gridLines网格线设置,false设置为空
##write data to worksheet 1
writeData(wb, sheet = 1, USPersonalExpenditure, rowNames = TRUE) #rowNames为行名字
## create and add a style to the column headers
#设置第一行的模板
headerStyle <- createStyle(fontSize = 14, fontColour = "#FFFFFF", halign = "center", fgFill = "#4F81BD", border="TopBottom", borderColour = "#4F81BD")
addStyle(wb, sheet = 1, headerStyle, rows = 1, cols = 1:6, gridExpand = TRUE)
## style for body
##设置内容主题的模板
bodyStyle <- createStyle(border="TopBottom", borderColour = "#4F81BD")
addStyle(wb, sheet = 1, bodyStyle, rows = 2:6, cols = 1:6, gridExpand = TRUE)
setColWidths(wb, 1, cols=1, widths = 21)
## set column width for row names column
saveWorkbook(wb, "addStyleExample.xlsx", overwrite = TRUE)
#addStyle Add a style to a set ofcells---------------------
## Create a new workbook
wb <- createWorkbook("Fred")
## Add 3 worksheets
addWorksheet(wb, "Sheet 1")
addWorksheet(wb, "Sheet 2", gridLines = FALSE)
addWorksheet(wb, "Sheet 3", tabColour = "red") #表的底端的tab按钮的颜色
addWorksheet(wb, "Sheet 4", gridLines = FALSE, tabColour = "#4F81BD")
## Headers and Footers
addWorksheet(wb, "Sheet 5", header = c("ODD HEAD LEFT", "ODD HEAD CENTER", "ODD HEAD RIGHT"), footer = c("ODD FOOT RIGHT", "ODD FOOT CENTER", "ODD FOOT RIGHT"), evenHeader = c("EVEN HEAD LEFT", "EVEN HEAD CENTER", "EVEN HEAD RIGHT"), evenFooter = c("EVEN FOOT RIGHT", "EVEN FOOT CENTER", "EVEN FOOT RIGHT"), firstHeader = c("TOP", "OF FIRST", "PAGE"), firstFooter = c("BOTTOM", "OF FIRST", "PAGE"))
addWorksheet(wb, "Sheet 6", header = c("&[Date]", "ALL HEAD CENTER 2", "&[Page] / &[Pages]"), footer = c("&[Path]&[File]", NA, "&[Tab]"), firstHeader = c(NA, "Center Header of First Page", NA), firstFooter = c(NA, "Center Footer of First Page", NA))
addWorksheet(wb, "Sheet 7", header = c("ALL HEAD LEFT 2", "ALL HEAD CENTER 2", "ALL HEAD RIGHT 2"), footer = c("ALL FOOT RIGHT 2", "ALL FOOT CENTER 2", "ALL FOOT RIGHT 2"))
addWorksheet(wb, "Sheet 8", firstHeader = c("FIRST ONLY L", NA, "FIRST ONLY R"),
firstFooter = c("FIRST ONLY L", NA, "FIRST ONLY R"))
## Need data on worksheet to see all headers and footers
writeData(wb, sheet = 5, 1:400)
writeData(wb, sheet = 6, 1:400)
writeData(wb, sheet = 7, 1:400)
writeData(wb, sheet = 8, 1:400)
## Save workbook
saveWorkbook(wb, "addWorksheetExample.xlsx", overwrite = TRUE)
#createStyle Create a cell style----------------------
## See package vignettes for further examples
## Modify default values of border colour and border line style
options("openxlsx.borderColour" = "#4F80BD")
options("openxlsx.borderStyle" = "thin")
## Size 18 Arial, Bold, left horz. aligned, fill colour #1A33CC, all borders,
style <- createStyle(fontSize = 18, fontName = "Arial", textDecoration = "bold", halign = "left", fgFill = "#1A33CC", border= "TopBottomLeftRight")
## Red, size 24, Bold, italic, underline, center aligned Font, bottom border
style <- createStyle(fontSize = 24, fontColour = rgb(1,0,0), textDecoration = c("bold", "italic", "underline"), halign = "center", valign = "center", border = "Bottom")
# borderColour is recycled for each border or all colours can be supplied
# colour is recycled 3 times for "Top", "Bottom" & "Right" sides.
createStyle(border = "TopBottomRight", borderColour = "red")
# supply all colours
createStyle(border = "TopBottomLeft", borderColour = c("red","yellow", "green"))
#createWorkbook Create a new Workbook object---------------
## Create a new workbook
wb <- createWorkbook()
## Save workbook to working directory
saveWorkbook(wb, file = "createWorkbookExample.xlsx", overwrite = TRUE)
#insertPlot Insert the current plot into a worksheet-----------------
## Not run: ## Create a new workbook
wb <- createWorkbook()
## Add a worksheet
addWorksheet(wb, "Sheet 1", gridLines = FALSE)
## create plot objects
require(ggplot2)
p1 <- qplot(mpg, data=mtcars, geom="density", fill=as.factor(gear), alpha=I(.5), main="Distribution of Gas Mileage")
p2 <- qplot(age, circumference, data = Orange, geom = c("point", "line"), colour = Tree)
## Insert currently displayed plot to sheet 1, row 1, column 1
print(p1) #plot needs to be showing
insertPlot(wb, 1, width = 5, height = 3.5, fileType = "png", units = "in")
## Insert plot 2 print(p2)
insertPlot(wb, 1, xy = c("J", 2), width = 16, height = 10, fileType = "png", units = "cm")
## Save workbook
saveWorkbook(wb, "insertPlotExample.xlsx", overwrite = TRUE) ## End(Not run)
#mergeCells Merge cells within a worksheet----------------------------
#合并单元格
## Create a new workbook
wb <- createWorkbook()
## Add a worksheet
addWorksheet(wb, "Sheet 1")
addWorksheet(wb, "Sheet 2")
## Merge cells: Row 2 column C to F (3:6)
mergeCells(wb, "Sheet 1", cols = 2, rows = 3:6)
## Merge cells:Rows 10 to 20 columns A to J (1:10)
mergeCells(wb, 1, cols = 1:10, rows = 10:20)
## Intersecting merges
mergeCells(wb, 2, cols = 1:10, rows = 1)
mergeCells(wb, 2, cols = 5:10, rows = 2)
mergeCells(wb, 2, cols = c(1,10), rows = 12)
## equivalent to 1:10 as only min/max are used #mergeCells(wb, 2, cols = 1, rows = c(1,10))
# Throws error because intersects existing merge
## remove merged cells
removeCellMerge(wb, 2, cols = 1, rows = 1)
# removes any intersecting merges
mergeCells(wb, 2, cols = 1, rows = 1:10)
# Now this works
## Save workbook
saveWorkbook(wb, "mergeCellsExample.xlsx", overwrite = TRUE)
#openXL Open a Microsoft Excel file (xls/xlsx) or an openxlsx Workboo------------------
wb <- createWorkbook()
x <- mtcars[1:6,]
addWorksheet(wb, "Cars")
writeData(wb, "Cars", x, startCol = 2, startRow = 3, rowNames = TRUE)
openXL(wb)
#saveWorkbook save Workbook to file
## Create a new workbook and add a worksheet
wb <- createWorkbook("Creator of workbook")
addWorksheet(wb, sheetName = "My first worksheet")
## Save workbook to working directory
saveWorkbook(wb, file = "saveWorkbookExample.xlsx", overwrite = TRUE)
#setColWidths Set worksheet column widths
#setColWidths(wb, sheet, cols, widths = 8.43, hidden = rep(FALSE, length(cols)), ignoreMergedCells = FALSE)
## Create a new workbook
wb <- createWorkbook()
## Add a worksheet
addWorksheet(wb, "Sheet 1")
## set col widths
setColWidths(wb, 1, cols = c(1,4,6,7,9), widths = c(16,15,12,18,33))
## auto columns
addWorksheet(wb, "Sheet 2")
writeData(wb, sheet = 2, x = iris)
setColWidths(wb, sheet = 2, cols = 1:5, widths = "auto")
## Save workbook
saveWorkbook(wb, "setColWidthsExample.xlsx", overwrite = TRUE)
#setRowHeights Description Set worksheet row heights--------------------------
## Create a new workbook
wb <- createWorkbook()
## Add a worksheet
addWorksheet(wb, "Sheet 1")
## set row heights
setRowHeights(wb, 1, rows = c(1,2,22,2,19), heights = c(24,28,32,42,33))
## overwrite row 1 height
setRowHeights(wb, 1, rows = 1, heights = 40)
setRowHeights(wb,1,rows = 2,heights = "auto")
## Save workbook
saveWorkbook(wb, "setRowHeightsExample.xlsx", overwrite = TRUE)
#sheets Returns names ofworksheets.------------------------------
## Create a new workbook
wb <- createWorkbook()
## Add some worksheets
addWorksheet(wb, "Worksheet Name")
addWorksheet(wb, "This is worksheet 2")
addWorksheet(wb, "The third worksheet")
## Return names of sheets, can not be used for assignment.
names(wb) # openXL(wb)
names(wb) <- c("A", "B", "C")
names(wb)
# openXL(wb)
#showGridLines Set worksheet gridlines to show or hide.-----------------------
wb <- loadWorkbook(file = system.file("loadExample.xlsx", package = "openxlsx"))
names(wb) ## list worksheets in workbook
showGridLines(wb, 1, showGridLines = FALSE)
showGridLines(wb, "testing", showGridLines = FALSE)
saveWorkbook(wb, "showGridLinesExample.xlsx", overwrite = TRUE)