en Table Operations - ZeroHawkeye/wordZero GitHub Wiki
Table Operations
WordZero provides comprehensive table functionality for creating and managing structured data in Word documents. This chapter covers table creation, styling, cell operations, and advanced features like table iterators.
📊 Basic Table Creation
Creating Simple Tables
import "github.com/ZeroHawkeye/wordZero/pkg/document"
doc := document.New()
// Create a 3x4 table (3 rows, 4 columns)
table := doc.AddTable(3, 4)
// Create table with initial data
data := [][]string{
{"Name", "Age", "City", "Country"},
{"Alice", "25", "New York", "USA"},
{"Bob", "30", "London", "UK"},
}
tableWithData := doc.AddTableWithData(data)
Setting Cell Content
// Set individual cell content
table.SetCellText(0, 0, "Header 1")
table.SetCellText(0, 1, "Header 2")
table.SetCellText(1, 0, "Data 1")
table.SetCellText(1, 1, "Data 2")
// Get cell content
content := table.GetCellText(0, 0)
fmt.Println(content) // "Header 1"
🎨 Table Styling
Default Table Styling
WordZero applies default styling that follows Word standards:
// Default table includes:
// - Single line borders (4 * 1/8 points thickness)
// - Auto-fit layout
// - Standard cell margins (108 dxa)
table := doc.AddTable(3, 3)
// Table has default styling applied automatically
Custom Table Borders
// Set table borders
table.SetBorders(&document.TableBorders{
Top: &document.Border{Style: "single", Size: 4, Color: "000000"},
Bottom: &document.Border{Style: "single", Size: 4, Color: "000000"},
Left: &document.Border{Style: "single", Size: 4, Color: "000000"},
Right: &document.Border{Style: "single", Size: 4, Color: "000000"},
InsideH: &document.Border{Style: "single", Size: 2, Color: "CCCCCC"},
InsideV: &document.Border{Style: "single", Size: 2, Color: "CCCCCC"},
})
// Remove all borders
table.RemoveBorders()
// Set only outer borders
table.SetOuterBorders(&document.Border{Style: "single", Size: 6, Color: "000000"})
Cell Background Colors
// Set cell background color
table.SetCellBackgroundColor(0, 0, "E6F3FF") // Light blue
// Set alternating row colors
table.SetAlternatingRowColors("FFFFFF", "F8F8F8") // White and light gray
// Set entire row background
table.SetRowBackgroundColor(0, "4472C4") // Blue header row
📐 Table Layout and Sizing
Table Width Settings
// Set fixed table width (in DXA units, 1 inch = 1440 DXA)
table.SetWidth(7200) // 5 inches
// Set table width as percentage of page width
table.SetWidthPercent(80) // 80% of page width
// Auto-fit table to content
table.SetAutoFit(true)
Column Width Management
// Set specific column widths
columnWidths := []int{1440, 2160, 1440, 2160} // In DXA units
table.SetColumnWidths(columnWidths)
// Set column width percentages
columnPercentages := []float64{25, 35, 20, 20} // Must sum to 100
table.SetColumnWidthsPercent(columnPercentages)
Row Height Settings
// Set minimum row height
table.SetRowHeight(0, 360) // 0.25 inches minimum
// Set exact row height
table.SetRowHeightExact(0, 720) // Exactly 0.5 inches
// Auto-fit row height to content
table.SetRowHeightAuto(0)
🔧 Advanced Cell Operations
Cell Merging
// Merge cells horizontally (merge columns)
table.MergeCellsHorizontal(0, 0, 2) // Merge row 0, columns 0-2
// Merge cells vertically (merge rows)
table.MergeCellsVertical(0, 0, 2) // Merge column 0, rows 0-2
// Merge rectangular area
table.MergeCellsArea(0, 0, 2, 2) // Merge 2x2 area starting at (0,0)
// Unmerge cells
table.UnmergeCells(0, 0)
// Check if cell is merged
isMerged := table.IsCellMerged(0, 0)
Cell Alignment
// Set horizontal alignment
table.SetCellAlignment(0, 0, document.AlignmentCenter)
// Set vertical alignment
table.SetCellVerticalAlignment(0, 0, document.VerticalAlignmentMiddle)
// Set text direction
table.SetCellTextDirection(0, 0, document.TextDirectionVertical)
Cell Formatting
// Format cell text
table.SetCellTextFormat(0, 0, &document.TextFormat{
Bold: true,
FontSize: 14,
FontColor: "FFFFFF",
})
// Set cell margins
table.SetCellMargins(0, 0, &document.CellMargins{
Top: 108, // DXA units
Bottom: 108,
Left: 144,
Right: 144,
})
🔄 Table Structure Management
Adding and Removing Rows
// Add row at the end
table.AddRow()
// Insert row at specific position
table.InsertRow(1) // Insert at position 1
// Add multiple rows
table.AddRows(3) // Add 3 rows
// Delete specific row
table.DeleteRow(2) // Delete row at index 2
// Delete multiple rows
table.DeleteRows(1, 3) // Delete rows 1, 2, and 3
Adding and Removing Columns
// Add column at the end
table.AddColumn()
// Insert column at specific position
table.InsertColumn(1) // Insert at position 1
// Delete specific column
table.DeleteColumn(2) // Delete column at index 2
🔍 Table Iterators and Queries
Cell Iterator
WordZero provides powerful iteration capabilities:
// Create cell iterator
iterator := table.NewCellIterator()
// Iterate through all cells
for iterator.HasNext() {
cellInfo := iterator.Next()
fmt.Printf("Cell [%d,%d]: %s\n",
cellInfo.Row, cellInfo.Col, cellInfo.Content)
}
// Reset iterator
iterator.Reset()
// Get iteration progress
progress := iterator.Progress() // Returns percentage (0-100)
Advanced Iterator Methods
// ForEach batch processing
table.ForEachCell(func(row, col int, content string) {
fmt.Printf("Processing cell [%d,%d]: %s\n", row, col, content)
})
// Iterate by row
table.ForEachInRow(0, func(col int, content string) {
fmt.Printf("Header column %d: %s\n", col, content)
})
// Iterate by column
table.ForEachInColumn(0, func(row int, content string) {
fmt.Printf("First column row %d: %s\n", row, content)
})
// Get cell range
cellRange := table.GetCellRange(0, 0, 2, 2) // Get 2x2 area
for _, cellInfo := range cellRange {
fmt.Printf("Cell: %s\n", cellInfo.Content)
}
Finding Cells
// Find cells by text (exact match)
matches := table.FindCellsByText("Sales", false) // case-sensitive
// Find cells by text (fuzzy match)
fuzzyMatches := table.FindCellsByText("sal", true) // case-insensitive
// Find cells with custom condition
condition := func(row, col int, content string) bool {
return strings.Contains(content, "Total")
}
totalCells := table.FindCells(condition)
📋 Complete Table Example
Here's a comprehensive example demonstrating various table features:
package main
import (
"fmt"
"log"
"github.com/ZeroHawkeye/wordZero/pkg/document"
"github.com/ZeroHawkeye/wordZero/pkg/style"
)
func createAdvancedTable() error {
doc := document.New()
// Add title
title := doc.AddParagraph("Sales Report Q4 2023")
title.SetStyle(style.StyleTitle)
// Create table with headers and data
tableData := [][]string{
{"Product", "Q1 Sales", "Q2 Sales", "Q3 Sales", "Q4 Sales", "Total"},
{"Laptop", "$50,000", "$55,000", "$60,000", "$65,000", "$230,000"},
{"Desktop", "$30,000", "$32,000", "$35,000", "$38,000", "$135,000"},
{"Tablet", "$20,000", "$22,000", "$25,000", "$28,000", "$95,000"},
{"Phone", "$40,000", "$45,000", "$48,000", "$52,000", "$185,000"},
{"Total", "$140,000", "$154,000", "$168,000", "$183,000", "$645,000"},
}
table := doc.AddTableWithData(tableData)
// Style the header row
table.SetRowBackgroundColor(0, "4472C4") // Blue background
for col := 0; col < 6; col++ {
table.SetCellTextFormat(0, col, &document.TextFormat{
Bold: true,
FontColor: "FFFFFF", // White text
})
table.SetCellAlignment(0, col, document.AlignmentCenter)
}
// Style the total row
lastRow := len(tableData) - 1
table.SetRowBackgroundColor(lastRow, "D9E2F3") // Light blue
for col := 0; col < 6; col++ {
table.SetCellTextFormat(lastRow, col, &document.TextFormat{
Bold: true,
})
}
// Set column widths
columnWidths := []int{1800, 1200, 1200, 1200, 1200, 1400} // DXA units
table.SetColumnWidths(columnWidths)
// Center align all data cells
for row := 1; row < len(tableData); row++ {
for col := 1; col < 6; col++ { // Skip product name column
table.SetCellAlignment(row, col, document.AlignmentCenter)
}
}
// Add borders
table.SetBorders(&document.TableBorders{
Top: &document.Border{Style: "single", Size: 8, Color: "000000"},
Bottom: &document.Border{Style: "single", Size: 8, Color: "000000"},
Left: &document.Border{Style: "single", Size: 8, Color: "000000"},
Right: &document.Border{Style: "single", Size: 8, Color: "000000"},
InsideH: &document.Border{Style: "single", Size: 4, Color: "666666"},
InsideV: &document.Border{Style: "single", Size: 4, Color: "666666"},
})
// Add notes paragraph
notes := doc.AddParagraph("")
notes.AddFormattedText("Note: ", &document.TextFormat{Bold: true})
notes.AddFormattedText("All figures are in USD and represent gross sales before taxes and fees.", nil)
notes.SetStyle(style.StyleNormal)
// Demonstrate iterator usage
fmt.Println("Table Analysis:")
totalCells := table.FindCellsByText("Total", false)
fmt.Printf("Found %d cells containing 'Total'\n", len(totalCells))
// Find highest sales quarter
iterator := table.NewCellIterator()
maxSales := 0
maxCell := ""
for iterator.HasNext() {
cellInfo := iterator.Next()
if cellInfo.Row > 0 && cellInfo.Col > 0 && cellInfo.Col < 5 { // Data cells only
// Parse sales figures (simplified)
if len(cellInfo.Content) > 1 && cellInfo.Content[0] == '$' {
fmt.Printf("Analyzing: %s\n", cellInfo.Content)
}
}
}
return doc.Save("sales_report.docx")
}
func main() {
if err := createAdvancedTable(); err != nil {
log.Fatalf("Error creating table: %v", err)
}
fmt.Println("Sales report created successfully!")
}
💡 Best Practices
1. Table Design
- Use consistent column widths for better appearance
- Apply appropriate headers and styling
- Keep tables readable with proper spacing
2. Data Organization
- Place headers in the first row
- Use consistent data formatting
- Group related data logically
3. Styling Guidelines
- Use subtle colors for better readability
- Highlight important rows (headers, totals)
- Maintain consistent alignment
4. Performance Tips
- Use batch operations when possible
- Avoid excessive cell merging
- Set table properties before adding content
⚠️ Common Issues
Table Layout Problems
- Ensure column widths sum appropriately
- Check page margins when setting table width
- Use auto-fit for dynamic content
Cell Merging Issues
- Verify merge ranges don't overlap
- Check cell indexes are valid
- Unmerge before re-merging cells
Next Steps
Continue learning about related features:
- Page Settings - Document layout and margins
- Advanced Features - Complex document features
- Best Practices - Optimization and tips
Master table operations to create professional data presentations!