Here's a comprehensive R script that creates an Excel report with all the components you requested:
# Load required libraries
library(openxlsx)
library(ggplot2)
# Create a new workbook
wb <- createWorkbook()
# Define some consistent styling
header_style <- createStyle(
fontSize = 14,
fontColour = "#FFFFFF",
bgFill = "#366092",
halign = "center",
valign = "center",
textDecoration = "bold",
border = "TopBottomLeftRight"
)
title_style <- createStyle(
fontSize = 24,
fontColour = "#366092",
textDecoration = "bold",
halign = "center",
valign = "center"
)
subtitle_style <- createStyle(
fontSize = 16,
fontColour = "#4472C4",
halign = "center",
valign = "center"
)
toc_link_style <- createStyle(
fontColour = "#0563C1",
textDecoration = "underline"
)
# 1. Create Cover Page
addWorksheet(wb, "Cover")
# Add title and subtitle
writeData(wb, "Cover", "Annual Sales Report 2024", startCol = 1, startRow = 5)
addStyle(wb, "Cover", title_style, rows = 5, cols = 1:6, gridExpand = TRUE)
mergeCells(wb, "Cover", cols = 1:6, rows = 5)
writeData(wb, "Cover", "Comprehensive Analysis of Regional Performance", startCol = 1, startRow = 7)
addStyle(wb, "Cover", subtitle_style, rows = 7, cols = 1:6, gridExpand = TRUE)
mergeCells(wb, "Cover", cols = 1:6, rows = 7)
# Add report metadata
writeData(wb, "Cover", "Report Date:", startCol = 2, startRow = 10)
writeData(wb, "Cover", Sys.Date(), startCol = 3, startRow = 10)
writeData(wb, "Cover", "Prepared By:", startCol = 2, startRow = 11)
writeData(wb, "Cover", "Analytics Department", startCol = 3, startRow = 11)
writeData(wb, "Cover", "Version:", startCol = 2, startRow = 12)
writeData(wb, "Cover", "1.0", startCol = 3, startRow = 12)
# Set column widths for cover page
setColWidths(wb, "Cover", cols = 1:6, widths = 15)
# 2. Create Table of Contents
addWorksheet(wb, "Contents")
# Add TOC title
writeData(wb, "Contents", "Table of Contents", startCol = 1, startRow = 2)
addStyle(wb, "Contents", title_style, rows = 2, cols = 1:3, gridExpand = TRUE)
mergeCells(wb, "Contents", cols = 1:3, rows = 2)
# Add TOC entries with hyperlinks
toc_entries <- data.frame(
Section = c("1. Cover Page", "2. Table of Contents", "3. Sales Data", "4. Sales Chart"),
Description = c(
"Report title and metadata",
"Navigation guide",
"Detailed sales data by region",
"Visual representation of sales trends"
),
Sheet = c("Cover", "Contents", "Sales Data", "Charts")
)
writeData(wb, "Contents", "Section", startCol = 1, startRow = 5)
writeData(wb, "Contents", "Description", startCol = 2, startRow = 5)
addStyle(wb, "Contents", header_style, rows = 5, cols = 1:2)
# Write TOC data
for(i in 1:nrow(toc_entries)) {
row <- 5 + i
# Create hyperlink to each sheet
writeFormula(wb, "Contents",
paste0('HYPERLINK("#\'', toc_entries$Sheet[i], '\'!A1", "', toc_entries$Section[i], '")'),
startCol = 1, startRow = row)
addStyle(wb, "Contents", toc_link_style, rows = row, cols = 1)
writeData(wb, "Contents", toc_entries$Description[i], startCol = 2, startRow = row)
}
setColWidths(wb, "Contents", cols = 1:2, widths = c(25, 40))
# 3. Create Sales Data Table
addWorksheet(wb, "Sales Data")
# Create sample sales data
set.seed(123)
sales_data <- data.frame(
Region = rep(c("North", "South", "East", "West"), each = 12),
Month = rep(month.name, 4),
Sales = round(runif(48, 50000, 150000), 2),
Units = round(runif(48, 100, 500)),
Target = round(runif(48, 60000, 140000), 2)
)
sales_data$Achievement <- round((sales_data$Sales / sales_data$Target) * 100, 1)
# Add title
writeData(wb, "Sales Data", "Regional Sales Performance", startCol = 1, startRow = 1)
addStyle(wb, "Sales Data", title_style, rows = 1, cols = 1:6, gridExpand = TRUE)
mergeCells(wb, "Sales Data", cols = 1:6, rows = 1)
# Write the data table
writeDataTable(wb, "Sales Data", sales_data,
startCol = 1, startRow = 3,
tableStyle = "TableStyleMedium2",
tableName = "SalesTable")
# Format numeric columns
addStyle(wb, "Sales Data",
createStyle(numFmt = "ACCOUNTING"),
rows = 4:(nrow(sales_data)+3),
cols = c(3, 5),
gridExpand = TRUE)
addStyle(wb, "Sales Data",
createStyle(numFmt = "0.0%"),
rows = 4:(nrow(sales_data)+3),
cols = 6,
gridExpand = TRUE)
# Conditional formatting for achievement
conditionalFormatting(wb, "Sales Data",
cols = 6,
rows = 4:(nrow(sales_data)+3),
type = "databar",
gradient = FALSE,
col = "#4472C4")
# Auto-fit columns
setColWidths(wb, "Sales Data", cols = 1:6, widths = "auto")
# 4. Create Charts Tab
addWorksheet(wb, "Charts")
# Add title
writeData(wb, "Charts", "Sales Analysis Charts", startCol = 1, startRow = 1)
addStyle(wb, "Charts", title_style, rows = 1, cols = 1:10, gridExpand = TRUE)
mergeCells(wb, "Charts", cols = 1:10, rows = 1)
# Prepare summary data for chart
monthly_summary <- aggregate(Sales ~ Month, data = sales_data, sum)
monthly_summary$Month <- factor(monthly_summary$Month, levels = month.name)
monthly_summary <- monthly_summary[order(monthly_summary$Month), ]
# Write chart data
writeData(wb, "Charts", "Monthly Sales Summary", startCol = 1, startRow = 3)
writeData(wb, "Charts", monthly_summary, startCol = 1, startRow = 4)
# Create a ggplot chart and save as image
p <- ggplot(monthly_summary, aes(x = Month, y = Sales)) +
geom_bar(stat = "identity", fill = "#4472C4") +
theme_minimal() +
theme(axis.text.x = element_text(angle = 45, hjust = 1)) +
labs(title = "Total Sales by Month",
x = "Month",
y = "Sales ($)") +
scale_y_continuous(labels = scales::dollar_format())
# Save plot temporarily
temp_plot <- tempfile(fileext = ".png")
ggsave(temp_plot, plot = p, width = 10, height = 6, dpi = 300)
# Insert the image
insertImage(wb, "Charts", temp_plot,
startCol = 5, startRow = 4,
width = 6, height = 4)
# Add regional summary
regional_summary <- aggregate(Sales ~ Region, data = sales_data, sum)
writeData(wb, "Charts", "Regional Sales Summary", startCol = 1, startRow = 20)
writeData(wb, "Charts", regional_summary, startCol = 1, startRow = 21)
# Format the summary table
addStyle(wb, "Charts", header_style, rows = 21, cols = 1:2)
addStyle(wb, "Charts",
createStyle(numFmt = "ACCOUNTING"),
rows = 22:25,
cols = 2)
# Clean up temp file
unlink(temp_plot)
# Add "Back to Contents" links on each sheet
sheets <- names(wb)[-2] # All sheets except Contents
for(sheet in sheets) {
max_row <- switch(sheet,
"Cover" = 15,
"Sales Data" = nrow(sales_data) + 5,
"Charts" = 30)
writeFormula(wb, sheet,
'HYPERLINK("#\'Contents\'!A1", "Back to Contents")',
startCol = 1, startRow = max_row)
addStyle(wb, sheet, toc_link_style, rows = max_row, cols = 1)
}
# Set active sheet to Cover
activeSheet(wb) <- 1
# Save the workbook
saveWorkbook(wb, "Sales_Report.xlsx", overwrite = TRUE)
print("Excel report created successfully!")
This script creates a comprehensive Excel report with:
Cover Page: Features a professional title page with report metadata including date, author, and version information.
Table of Contents: Contains clickable hyperlinks to navigate between sheets, with descriptions of each section.
Sales Data Tab: Includes a formatted data table with:
- Regional sales data across months
- Conditional formatting for achievement percentages
- Currency formatting for monetary values
- Professional table styling
Charts Tab: Contains:
- A bar chart showing monthly sales totals (created with ggplot2 and inserted as an image)
- A summary table of regional sales
- Professional formatting throughout
The script also includes navigation features with "Back to Contents" links on each sheet and consistent styling across all pages. The report is saved as "Sales_Report.xlsx" in your working directory.
To run this script, make sure you have the openxlsx and ggplot2 packages installed:
install.packages(c("openxlsx", "ggplot2"))