Merge pull request #433 from unidoc-build/prep-rc-v1.5.0

Release unioffice v1.5.0
This commit is contained in:
Gunnsteinn Hall 2020-08-23 17:49:47 +00:00 committed by GitHub
commit 373b458582
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4043 changed files with 28758 additions and 450845 deletions

1
.gitattributes vendored
View File

@ -1 +0,0 @@
* -crlf

View File

Before

Width:  |  Height:  |  Size: 227 KiB

After

Width:  |  Height:  |  Size: 227 KiB

18
.gitignore vendored
View File

@ -1,18 +0,0 @@
# Binaries for programs and plugins
*.exe
*.dll
*.so
*.dylib
*.swp
coverage*
**/.DS_Store
**/main
# Test binary, build with `go test -c`
*.test
**/.coverprofile
gover.coverprofile
spreadsheet/formula/y.output
.idea

View File

@ -1,29 +0,0 @@
language: go
go:
- 1.12.x
- 1.13.x
- 1.14
install:
- mkdir -p $HOME/gopath/src/unidoc/
- ln -s $HOME/gopath/src/github.com/unidoc/unioffice $HOME/gopath/src/github.com/unidoc/unioffice
- mkdir -p $HOME/dotnet
- cd $HOME/dotnet
- wget https://download.visualstudio.microsoft.com/download/pr/8db2b522-7fa2-4903-97ec-d6d04d297a01/f467006b9098c2de256e40d2e2f36fea/dotnet-sdk-3.1.301-linux-x64.tar.gz
- tar -xf dotnet-sdk-3.1.301-linux-x64.tar.gz
- cd $GOPATH/src/github.com/unidoc/unioffice/.travis
- unzip validator.zip
- cd openxml-validator
- $HOME/dotnet/dotnet build
script:
- cd $HOME/gopath/src/github.com/unidoc/unioffice
- ./build-examples.sh
- cd .travis
- ./validate-examples.sh
- cd $HOME/gopath/src/github.com/unidoc/unioffice
- go vet ./...
- go test ./...
after_success:
- ./test-coverage.sh

View File

@ -1,10 +0,0 @@
#!/bin/bash
output=$(dotnet ./openxml-validator/bin/Debug/netcoreapp3.0/Program.dll --$2 $1)
echo $output
echo ""
if [[ $output == *"is not valid"* ]]; then
if [[ $output != *"main:sz"* ]] && [[ $output != *"main:family"* ]] && [[ $output != *"Attribute 'si' should be present when the value of attribute 't' is 'shared'"* ]] ; then
echo $output >> errors
echo "" >> errors
fi
fi

View File

@ -1 +0,0 @@
values.xlsx

View File

@ -1,12 +0,0 @@
#!/bin/bash
find ../_examples -maxdepth 2 -mindepth 2 -exec sh -c "cd {}; echo running {}; ./main" \;
export PATH=$PATH:$HOME/dotnet
:> errors
find ../_examples -name "*.docx" $(printf "! -name %s " $(cat skip_files)) -exec ./dotnet_run.sh {} docx \;
find ../_examples -name "*.xlsx" $(printf "! -name %s " $(cat skip_files)) -exec ./dotnet_run.sh {} xlsx \;
find ../_examples -name "*.pptx" $(printf "! -name %s " $(cat skip_files)) -exec ./dotnet_run.sh {} pptx \;
if [[ $(wc -l errors) == "0 errors" ]]; then
exit 0
fi
echo "there are errors"
exit 1

Binary file not shown.

View File

@ -7,7 +7,7 @@ library for creation and editing of docx/xlsx/pptx files.
[![License: UniDoc EULA](https://img.shields.io/badge/license-UniDoc%20EULA-blue)](https://unidoc.io/eula/)
[![GoDoc](https://godoc.org/github.com/unidoc/unioffice?status.svg)](https://godoc.org/github.com/unidoc/unioffice)
![https://github.com/unidoc/unioffice/](./_examples/preview.png "unioffice")
![https://github.com/unidoc/unioffice/](./.github/preview.png "unioffice")
## Status ##
@ -33,7 +33,7 @@ library for creation and editing of docx/xlsx/pptx files.
There has been a great deal of interest in performance numbers for spreadsheet
creation/reading lately, so here are unioffice numbers for this
[benchmark](https://github.com/unidoc/unioffice/tree/master/_examples/spreadsheet/lots-of-rows)
[benchmark](https://github.com/unidoc/unioffice-examples/tree/master/spreadsheet/lots-of-rows)
which creates a sheet with 30k rows, each with 100 columns.
creating 30000 rows * 100 cells took 3.92506863s
@ -51,36 +51,36 @@ DOCX/XLSX/PPTX.
## Document Examples ##
- [Simple Text Formatting](https://github.com/unidoc/unioffice/tree/master/_examples/document/simple) Text font colors, sizes, highlighting, etc.
- [Auto Generated Table of Contents](https://github.com/unidoc/unioffice/tree/master/_examples/document/toc) Creating document headings with an auto generated TOC based off of the headingds
- [Floating Image](https://github.com/unidoc/unioffice/tree/master/_examples/document/image) Placing an image somewhere on a page, absolutely positioned with different text wrapping.
- [Header & Footer](https://github.com/unidoc/unioffice/tree/master/_examples/document/header-footer) Creating headers and footers including page numbering.
- [Multiple Headers & Footers](https://github.com/unidoc/unioffice/tree/master/_examples/document/header-footer-multiple) Using different headers and footers depending on document section.
- [Inline Tables](https://github.com/unidoc/unioffice/tree/master/_examples/document/tables) Adding an table with and without borders.
- [Using Existing Word Document as a Template](https://github.com/unidoc/unioffice/tree/master/_examples/document/use-template) Opening a document as a template to re-use the styles created in the document.
- [Filling out Form Fields](https://github.com/unidoc/unioffice/tree/master/_examples/document/fill-out-form) Opening a document with embedded form fields, filling out the fields and saving the result as a new filled form.
- [Editing an existing document](https://github.com/unidoc/unioffice/tree/master/_examples/document/edit-document) Open an existing document and replace/remove text without modifying formatting.
- [Simple Text Formatting](https://github.com/unidoc/unioffice-examples/tree/master/document/simple) Text font colors, sizes, highlighting, etc.
- [Auto Generated Table of Contents](https://github.com/unidoc/unioffice-examples/tree/master/document/toc) Creating document headings with an auto generated TOC based off of the headingds
- [Floating Image](https://github.com/unidoc/unioffice-examples/tree/master/document/image) Placing an image somewhere on a page, absolutely positioned with different text wrapping.
- [Header & Footer](https://github.com/unidoc/unioffice-examples/tree/master/document/header-footer) Creating headers and footers including page numbering.
- [Multiple Headers & Footers](https://github.com/unidoc/unioffice-examples/tree/master/document/header-footer-multiple) Using different headers and footers depending on document section.
- [Inline Tables](https://github.com/unidoc/unioffice-examples/tree/master/document/tables) Adding an table with and without borders.
- [Using Existing Word Document as a Template](https://github.com/unidoc/unioffice-examples/tree/master/document/use-template) Opening a document as a template to re-use the styles created in the document.
- [Filling out Form Fields](https://github.com/unidoc/unioffice-examples/tree/master/document/fill-out-form) Opening a document with embedded form fields, filling out the fields and saving the result as a new filled form.
- [Editing an existing document](https://github.com/unidoc/unioffice-examples/tree/master/document/edit-document) Open an existing document and replace/remove text without modifying formatting.
## Spreadsheet Examples ##
- [Simple](https://github.com/unidoc/unioffice/tree/master/_examples/spreadsheet/simple) A simple sheet with a few cells
- [Named Cells](https://github.com/unidoc/unioffice/tree/master/_examples/spreadsheet/named-cells) Different ways of referencing rows and cells
- [Cell Number/Date/Time Formats](https://github.com/unidoc/unioffice/tree/master/_examples/spreadsheet/number-date-time-formats) Creating cells with various number/date/time formats
- [Line Chart](https://github.com/unidoc/unioffice/tree/master/_examples/spreadsheet/line-chart)/[Line Chart 3D](https://github.com/unidoc/unioffice/tree/master/_examples/spreadsheet/line-chart-3d) Line Charts
- [Bar Chart](https://github.com/unidoc/unioffice/tree/master/_examples/spreadsheet/bar-chart) Bar Charts
- [Mutiple Charts](https://github.com/unidoc/unioffice/tree/master/_examples/spreadsheet/multiple-charts) Multiple charts on a single sheet
- [Named Cell Ranges](https://github.com/unidoc/unioffice/tree/master/_examples/spreadsheet/named-ranges) Naming cell ranges
- [Merged Cells](https://github.com/unidoc/unioffice/tree/master/_examples/spreadsheet/merged) Merge and unmerge cells
- [Conditional Formatting](https://github.com/unidoc/unioffice/tree/master/_examples/spreadsheet/conditional-formatting) Conditionally formatting cells, styling, gradients, icons, data bar
- [Complex](https://github.com/unidoc/unioffice/tree/master/_examples/spreadsheet/complex) Multiple charts, auto filtering and conditional formatting
- [Borders](https://github.com/unidoc/unioffice/tree/master/_examples/spreadsheet/borders) Individual cell borders and rectangular borders around a range of cells.
- [Validation](https://github.com/unidoc/unioffice/tree/master/_examples/spreadsheet/validation) Data validation including combo box dropdowns.
- [Frozen Rows/Cols](https://github.com/unidoc/unioffice/tree/master/_examples/spreadsheet/freeze-rows-cols) A sheet with a frozen header column and row
- [Simple](https://github.com/unidoc/unioffice-examples/tree/master/spreadsheet/simple) A simple sheet with a few cells
- [Named Cells](https://github.com/unidoc/unioffice-examples/tree/master/spreadsheet/named-cells) Different ways of referencing rows and cells
- [Cell Number/Date/Time Formats](https://github.com/unidoc/unioffice-examples/tree/master/spreadsheet/number-date-time-formats) Creating cells with various number/date/time formats
- [Line Chart](https://github.com/unidoc/unioffice-examples/tree/master/spreadsheet/line-chart)/[Line Chart 3D](https://github.com/unidoc/unioffice-examples/tree/master/spreadsheet/line-chart-3d) Line Charts
- [Bar Chart](https://github.com/unidoc/unioffice-examples/tree/master/spreadsheet/bar-chart) Bar Charts
- [Mutiple Charts](https://github.com/unidoc/unioffice-examples/tree/master/spreadsheet/multiple-charts) Multiple charts on a single sheet
- [Named Cell Ranges](https://github.com/unidoc/unioffice-examples/tree/master/spreadsheet/named-ranges) Naming cell ranges
- [Merged Cells](https://github.com/unidoc/unioffice-examples/tree/master/spreadsheet/merged) Merge and unmerge cells
- [Conditional Formatting](https://github.com/unidoc/unioffice-examples/tree/master/spreadsheet/conditional-formatting) Conditionally formatting cells, styling, gradients, icons, data bar
- [Complex](https://github.com/unidoc/unioffice-examples/tree/master/spreadsheet/complex) Multiple charts, auto filtering and conditional formatting
- [Borders](https://github.com/unidoc/unioffice-examples/tree/master/spreadsheet/borders) Individual cell borders and rectangular borders around a range of cells.
- [Validation](https://github.com/unidoc/unioffice-examples/tree/master/spreadsheet/validation) Data validation including combo box dropdowns.
- [Frozen Rows/Cols](https://github.com/unidoc/unioffice-examples/tree/master/spreadsheet/freeze-rows-cols) A sheet with a frozen header column and row
## Presentation Examples ##
- [Simple Text Boxes](https://github.com/unidoc/unioffice/tree/master/_examples/presentation/simple) Simple text boxes and shapes
- [Images](https://github.com/unidoc/unioffice/tree/master/_examples/presentation/image) Simple image insertion
- [Template](https://github.com/unidoc/unioffice/tree/master/_examples/presentation/use-template/simple) Creating a presentation from a template
- [Simple Text Boxes](https://github.com/unidoc/unioffice-examples/tree/master/presentation/simple) Simple text boxes and shapes
- [Images](https://github.com/unidoc/unioffice-examples/tree/master/presentation/image) Simple image insertion
- [Template](https://github.com/unidoc/unioffice-examples/tree/master/presentation/use-template/simple) Creating a presentation from a template
## Raw Types ##

View File

@ -1,50 +0,0 @@
// Copyright 2019 FoxyUtils ehf. All rights reserved.
package main
import (
"fmt"
"log"
"time"
"github.com/unidoc/unioffice/document"
)
func main() {
doc, err := document.Open("document.docx")
if err != nil {
log.Fatalf("error opening document: %s", err)
}
cp := doc.GetOrCreateCustomProperties()
// You can read properties from the document
fmt.Println("AppVersion", *cp.GetPropertyByName("AppVersion").Lpwstr)
fmt.Println("Company", *cp.GetPropertyByName("Company").Lpwstr)
fmt.Println("DocSecurity", *cp.GetPropertyByName("DocSecurity").I4)
fmt.Println("LinksUpToDate", *cp.GetPropertyByName("LinksUpToDate").Bool)
fmt.Println("Non-existent", cp.GetPropertyByName("nonexistentproperty"))
// And change them as well
cp.SetPropertyAsLpwstr("Company", "Another company") // text, existing property
fmt.Println("Company", *cp.GetPropertyByName("Company").Lpwstr)
// Adding new properties
cp.SetPropertyAsLpwstr("Another text property", "My text value") // text
cp.SetPropertyAsI4("Another integer number property", 42) // int32
cp.SetPropertyAsR8("Another float number property", 3.14) // float64
cp.SetPropertyAsDate("Another date property", time.Now()) // date
doc.SaveToFile("document_customized.docx")
// For new documents all is the same
docNew := document.New()
cpNew := docNew.GetOrCreateCustomProperties()
cpNew.SetPropertyAsLpwstr("Another text property", "My text value") // text
cpNew.SetPropertyAsI4("Another integer number property", 42) // int23
cpNew.SetPropertyAsR8("Another float number property", 3.14) // float64
cpNew.SetPropertyAsDate("Another date property", time.Now()) // date
docNew.SaveToFile("document_new.docx")
}

View File

@ -1,39 +0,0 @@
// Copyright 2017 FoxyUtils ehf. All rights reserved.
package main
import (
"fmt"
"log"
"time"
"github.com/unidoc/unioffice/document"
)
func main() {
doc, err := document.Open("document.docx")
if err != nil {
log.Fatalf("error opening document: %s", err)
}
cp := doc.CoreProperties
// You can read properties from the document
fmt.Println("Title:", cp.Title())
fmt.Println("Author:", cp.Author())
fmt.Println("Description:", cp.Description())
fmt.Println("Last Modified By:", cp.LastModifiedBy())
fmt.Println("Category:", cp.Category())
fmt.Println("Content Status:", cp.ContentStatus())
fmt.Println("Created:", cp.Created())
fmt.Println("Modified:", cp.Modified())
// And change them as well
cp.SetTitle("CP Invoices")
cp.SetAuthor("John Doe")
cp.SetCategory("Invoices")
cp.SetContentStatus("Draft")
cp.SetLastModifiedBy("Jane Smith")
cp.SetCreated(time.Now())
cp.SetModified(time.Now())
doc.SaveToFile("document_modified.docx")
}

View File

@ -1,101 +0,0 @@
// Copyright 2017 FoxyUtils ehf. All rights reserved.
package main
import (
"fmt"
"log"
"time"
"github.com/unidoc/unioffice/document"
)
func main() {
doc, err := document.Open("document.docx")
if err != nil {
log.Fatalf("error opening document: %s", err)
}
paragraphs := []document.Paragraph{}
for _, p := range doc.Paragraphs() {
paragraphs = append(paragraphs, p)
}
// This sample document uses structured document tags, which are not common
// except for in document templates. Normally you can just iterate over the
// document's paragraphs.
for _, sdt := range doc.StructuredDocumentTags() {
for _, p := range sdt.Paragraphs() {
paragraphs = append(paragraphs, p)
}
}
for _, p := range paragraphs {
for _, r := range p.Runs() {
switch r.Text() {
case "FIRST NAME":
// ClearContent clears both text and line breaks within a run,
// so we need to add the line break back
r.ClearContent()
r.AddText("John ")
r.AddBreak()
para := doc.InsertParagraphBefore(p)
para.AddRun().AddText("Mr.")
para.SetStyle("Name") // Name is a default style in this template file
para = doc.InsertParagraphAfter(p)
para.AddRun().AddText("III")
para.SetStyle("Name")
case "LAST NAME":
r.ClearContent()
r.AddText("Smith")
case "Address | Phone | Email":
r.ClearContent()
r.AddText("111 Rustic Rd | 123-456-7890 | jsmith@smith.com")
case "Date":
r.ClearContent()
r.AddText(time.Now().Format("Jan 2, 2006"))
case "Recipient Name":
r.ClearContent()
r.AddText("Mrs. Smith")
r.AddBreak()
case "Title":
// we remove the title content entirely
p.RemoveRun(r)
case "Company":
r.ClearContent()
r.AddText("Smith Enterprises")
r.AddBreak()
case "Address":
r.ClearContent()
r.AddText("112 Rustic Rd")
r.AddBreak()
case "City, ST ZIP Code":
r.ClearContent()
r.AddText("San Francisco, CA 94016")
r.AddBreak()
case "Dear Recipient:":
r.ClearContent()
r.AddText("Dear Mrs. Smith:")
r.AddBreak()
case "Your Name":
r.ClearContent()
r.AddText("John Smith")
r.AddBreak()
run := p.InsertRunBefore(r)
run.AddText("---Before----")
run.AddBreak()
run = p.InsertRunAfter(r)
run.AddText("---After----")
default:
fmt.Println("not modifying", r.Text())
}
}
}
doc.SaveToFile("edit-document.docx")
}

View File

@ -1,29 +0,0 @@
// Copyright 2017 FoxyUtils ehf. All rights reserved.
package main
import (
"fmt"
"log"
"github.com/unidoc/unioffice/document"
)
func main() {
doc, err := document.Open("footnotes_endnotes.docx")
if err != nil {
log.Fatalf("error opening document: %s", err)
}
if doc.HasFootnotes() {
fmt.Printf("Document has %02d footnotes.\n", len(doc.Footnotes()))
} else {
fmt.Println("Document has no footnotes")
}
if doc.HasEndnotes() {
fmt.Printf("Document has %02d endnotes.\n", len(doc.Endnotes()))
} else {
fmt.Println("Document has no endnotes")
}
}

View File

@ -1,43 +0,0 @@
// Copyright 2017 FoxyUtils ehf. All rights reserved.
package main
import (
"fmt"
"log"
"github.com/unidoc/unioffice/document"
)
func main() {
doc, err := document.Open("form.docx")
if err != nil {
log.Fatalf("error opening form: %s", err)
}
// FindAllFields is a helper function that traverses the document
// identifying fields
fields := doc.FormFields()
fmt.Println("found", len(fields), "fields")
for _, fld := range fields {
fmt.Println("- Name:", fld.Name(), "Type:", fld.Type(), "Value:", fld.Value())
switch fld.Type() {
case document.FormFieldTypeText:
// you can directly set values on text fields
fld.SetValue("testing 123")
case document.FormFieldTypeCheckBox:
// you can check check boxes
fld.SetChecked(true)
case document.FormFieldTypeDropDown:
// and select items in a dropdown, here the value must be one of the
// fields possible values
lpv := len(fld.PossibleValues())
if lpv > 0 {
fld.SetValue(fld.PossibleValues()[lpv-1])
}
}
}
doc.SaveToFile("filled-form.docx")
}

View File

@ -1,56 +0,0 @@
// Copyright 2017 FoxyUtils ehf. All rights reserved.
package main
import (
"github.com/unidoc/unioffice/document"
"github.com/unidoc/unioffice/measurement"
"github.com/unidoc/unioffice/schema/soo/wml"
)
var lorem = `Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin lobortis, lectus dictum feugiat tempus, sem neque finibus enim, sed eleifend sem nunc ac diam. Vestibulum tempus sagittis elementum`
func main() {
doc := document.New()
// Headers/footers apply to the preceding paragraphs in the document. There
// is a section properties on the document body itself acessible via
// BodySection(). To have multiple different headers (aside from the
// supported even/odd/first), we need to add multiple sections.
// First add some content
for i := 0; i < 5; i++ {
para := doc.AddParagraph()
run := para.AddRun()
run.AddText(lorem)
}
// Construct our header
hdr := doc.AddHeader()
para := hdr.AddParagraph()
para.Properties().AddTabStop(2.5*measurement.Inch, wml.ST_TabJcCenter, wml.ST_TabTlcNone)
run := para.AddRun()
run.AddTab()
run.AddText("My Document Title")
// Create a new section and apply the header
para = doc.AddParagraph()
section := para.Properties().AddSection(wml.ST_SectionMarkNextPage)
section.SetHeader(hdr, wml.ST_HdrFtrDefault)
// Add some more content
for i := 0; i < 5; i++ {
para := doc.AddParagraph()
run := para.AddRun()
run.AddText(lorem)
}
hdr = doc.AddHeader()
para = hdr.AddParagraph()
para.Properties().AddTabStop(2.5*measurement.Inch, wml.ST_TabJcCenter, wml.ST_TabTlcNone)
run = para.AddRun()
run.AddTab()
run.AddText("Different Title")
doc.BodySection().SetHeader(hdr, wml.ST_HdrFtrDefault)
doc.SaveToFile("header-footer-multiple.docx")
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 44 KiB

View File

@ -1,64 +0,0 @@
// Copyright 2017 FoxyUtils ehf. All rights reserved.
package main
import (
"log"
"github.com/unidoc/unioffice/common"
"github.com/unidoc/unioffice/document"
"github.com/unidoc/unioffice/measurement"
"github.com/unidoc/unioffice/schema/soo/wml"
)
func main() {
doc := document.New()
img, err := common.ImageFromFile("gophercolor.png")
if err != nil {
log.Fatalf("unable to create image: %s", err)
}
hdr := doc.AddHeader()
// We need to add a reference of the image to the header instead of to the
// document
iref, err := hdr.AddImage(img)
if err != nil {
log.Fatalf("unable to to add image to document: %s", err)
}
para := hdr.AddParagraph()
para.Properties().AddTabStop(2.5*measurement.Inch, wml.ST_TabJcCenter, wml.ST_TabTlcNone)
run := para.AddRun()
run.AddTab()
run.AddText("My Document Title")
imgInl, _ := para.AddRun().AddDrawingInline(iref)
imgInl.SetSize(1*measurement.Inch, 1*measurement.Inch)
// Headers and footers are not immediately associated with a document as a
// document can have multiple headers and footers for different sections.
doc.BodySection().SetHeader(hdr, wml.ST_HdrFtrDefault)
ftr := doc.AddFooter()
para = ftr.AddParagraph()
para.Properties().AddTabStop(6*measurement.Inch, wml.ST_TabJcRight, wml.ST_TabTlcNone)
run = para.AddRun()
run.AddText("Some subtitle goes here")
run.AddTab()
run.AddText("Pg ")
run.AddField(document.FieldCurrentPage)
run.AddText(" of ")
run.AddField(document.FieldNumberOfPages)
doc.BodySection().SetFooter(ftr, wml.ST_HdrFtrDefault)
lorem := `Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin lobortis, lectus dictum feugiat tempus, sem neque finibus enim, sed eleifend sem nunc ac diam. Vestibulum tempus sagittis elementum`
for i := 0; i < 5; i++ {
para = doc.AddParagraph()
run = para.AddRun()
run.AddText(lorem)
}
doc.SaveToFile("header-footer.docx")
}

View File

@ -1,51 +0,0 @@
package main
import (
"github.com/unidoc/unioffice/color"
"github.com/unidoc/unioffice/document"
"github.com/unidoc/unioffice/schema/soo/wml"
)
func main() {
doc := document.New()
hlStyle := doc.Styles.AddStyle("Hyperlink", wml.ST_StyleTypeCharacter, false)
hlStyle.SetName("Hyperlink")
hlStyle.SetBasedOn("DefaultParagraphFont")
hlStyle.RunProperties().Color().SetThemeColor(wml.ST_ThemeColorHyperlink)
clr := color.FromHex("#0563C1")
hlStyle.RunProperties().Color().SetColor(clr)
hlStyle.RunProperties().SetUnderline(wml.ST_UnderlineSingle, clr)
para := doc.AddParagraph()
run := para.AddRun()
run.AddText("Hello World! ")
bm := para.AddBookmark("_bookmark1")
addBlankLines(para)
// first link to a URL
hl := para.AddHyperLink()
hl.SetTarget("http://www.google.com")
run = hl.AddRun()
run.Properties().SetStyle("Hyperlink")
run.AddText("Click Here to open google.com")
hl.SetToolTip("hover to see this")
addBlankLines(para)
// second link to a bookmark
hl = para.AddHyperLink()
hl.SetTargetBookmark(bm)
run = hl.AddRun()
run.AddText("Click Here to jump to the bookmark")
doc.SaveToFile("hyperlink.docx")
}
func addBlankLines(p document.Paragraph) {
run := p.AddRun()
for i := 0; i < 4; i++ {
run.AddBreak()
}
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 44 KiB

View File

@ -1,75 +0,0 @@
// Copyright 2017 FoxyUtils ehf. All rights reserved.
package main
import (
"io/ioutil"
"log"
"github.com/unidoc/unioffice/common"
"github.com/unidoc/unioffice/document"
"github.com/unidoc/unioffice/measurement"
"github.com/unidoc/unioffice/schema/soo/wml"
)
var lorem = `Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin lobortis, lectus dictum feugiat tempus, sem neque finibus enim, sed eleifend sem nunc ac diam. Vestibulum tempus sagittis elementum`
func main() {
doc := document.New()
img1, err := common.ImageFromFile("gophercolor.png")
if err != nil {
log.Fatalf("unable to create image: %s", err)
}
img2data, err := ioutil.ReadFile("gophercolor.png")
if err != nil {
log.Fatalf("unable to read file: %s", err)
}
img2, err := common.ImageFromBytes(img2data)
if err != nil {
log.Fatalf("unable to create image: %s", err)
}
img1ref, err := doc.AddImage(img1)
if err != nil {
log.Fatalf("unable to add image to document: %s", err)
}
img2ref, err := doc.AddImage(img2)
if err != nil {
log.Fatalf("unable to add image to document: %s", err)
}
para := doc.AddParagraph()
anchored, err := para.AddRun().AddDrawingAnchored(img1ref)
if err != nil {
log.Fatalf("unable to add anchored image: %s", err)
}
anchored.SetName("Gopher")
anchored.SetSize(2*measurement.Inch, 2*measurement.Inch)
anchored.SetOrigin(wml.WdST_RelFromHPage, wml.WdST_RelFromVTopMargin)
anchored.SetHAlignment(wml.WdST_AlignHCenter)
anchored.SetYOffset(3 * measurement.Inch)
anchored.SetTextWrapSquare(wml.WdST_WrapTextBothSides)
run := para.AddRun()
for i := 0; i < 16; i++ {
run.AddText(lorem)
// drop an inline image in
if i == 13 {
inl, err := run.AddDrawingInline(img1ref)
if err != nil {
log.Fatalf("unable to add inline image: %s", err)
}
inl.SetSize(1*measurement.Inch, 1*measurement.Inch)
}
if i == 15 {
inl, err := run.AddDrawingInline(img2ref)
if err != nil {
log.Fatalf("unable to add inline image: %s", err)
}
inl.SetSize(1*measurement.Inch, 1*measurement.Inch)
}
}
doc.SaveToFile("image.docx")
}

View File

@ -1,35 +0,0 @@
// Copyright 2017 FoxyUtils ehf. All rights reserved.
package main
import (
"log"
"github.com/unidoc/unioffice/document"
"github.com/unidoc/unioffice/measurement"
"github.com/unidoc/unioffice/schema/soo/wml"
)
func main() {
doc := document.New()
lorem := `Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin lobortis, lectus dictum feugiat tempus, sem neque finibus enim, sed eleifend sem nunc ac diam. Vestibulum tempus sagittis elementum.`
// single spaced
para := doc.AddParagraph()
run := para.AddRun()
run.AddText(lorem)
run.AddText(lorem)
run.AddBreak()
// double spaced is twice the text height (24 points in this case as the text height is 12 points)
para = doc.AddParagraph()
para.Properties().Spacing().SetLineSpacing(24*measurement.Point, wml.ST_LineSpacingRuleAuto)
run = para.AddRun()
run.AddText(lorem)
run.AddText(lorem)
run.AddBreak()
if err := doc.Validate(); err != nil {
log.Fatalf("error during validation: %s", err)
}
doc.SaveToFile("line-spacing.docx")
}

View File

@ -1,22 +0,0 @@
package main
import (
"log"
"github.com/unidoc/unioffice/document"
)
func main() {
d, err := document.Open("mm.docx")
if err != nil {
log.Fatalf("error opening document: %s", err)
}
for _, v := range d.MergeFields() {
log.Println("replacing", v)
}
rep := map[string]string{}
rep["Title"] = "mr." // has a \* Upper attribute on the field
rep["FirstName"] = "JOHN" // has a \* Lower attribute on the field
d.MailMerge(rep)
d.SaveToFile("merged.docx")
}

View File

@ -1,34 +0,0 @@
// Copyright 2018 FoxyUtils ehf. All rights reserved.
package main
import (
"github.com/unidoc/unioffice/document"
"github.com/unidoc/unioffice/measurement"
"github.com/unidoc/unioffice/schema/soo/wml"
)
var lorem = `Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin lobortis, lectus dictum feugiat tempus, sem neque finibus enim, sed eleifend sem nunc ac diam. Vestibulum tempus sagittis elementum`
func main() {
doc := document.New()
ftr := doc.AddFooter()
para := ftr.AddParagraph()
para.Properties().AddTabStop(3*measurement.Inch, wml.ST_TabJcCenter, wml.ST_TabTlcNone)
run := para.AddRun()
run.AddTab()
run.AddFieldWithFormatting(document.FieldCurrentPage, "", false)
run.AddText(" of ")
run.AddFieldWithFormatting(document.FieldNumberOfPages, "", false)
doc.BodySection().SetFooter(ftr, wml.ST_HdrFtrDefault)
for i := 0; i < 20; i++ {
para := doc.AddParagraph()
for j := 0; j < 5; j++ {
run := para.AddRun()
run.AddText(lorem)
}
}
doc.SaveToFile("page-numbers.docx")
}

View File

@ -1,31 +0,0 @@
package main
import (
"github.com/unidoc/unioffice/color"
"github.com/unidoc/unioffice/document"
"github.com/unidoc/unioffice/measurement"
"github.com/unidoc/unioffice/schema/soo/wml"
)
func main() {
doc := document.New()
paraBeforeTable := doc.AddParagraph()
paraBeforeTable.AddRun().AddText("before table")
table := doc.InsertTableAfter(paraBeforeTable)
table.Properties().Borders().SetAll(wml.ST_BorderBasicBlackDots, color.AliceBlue, measurement.Point*2)
tablePara1 := table.AddRow().AddCell().AddParagraph()
tablePara1.AddRun().AddText("table paragraph 1")
paraAfterTable := doc.AddParagraph()
paraAfterTable.AddRun().AddText("after table")
tablePara2 := doc.InsertParagraphAfter(tablePara1)
tablePara2.AddRun().AddText("table paragraph after table paragraph 1")
tablePara3 := doc.InsertParagraphBefore(tablePara1)
tablePara3.AddRun().AddText("table paragraph before table paragraph 1")
doc.SaveToFile("out.docx")
}

View File

@ -1,62 +0,0 @@
// Copyright 2017 FoxyUtils ehf. All rights reserved.
package main
import (
"log"
"os"
"path/filepath"
"github.com/unidoc/unioffice/document"
ole "github.com/go-ole/go-ole"
"github.com/go-ole/go-ole/oleutil"
)
// NOTE: This example can only run on Windows and requires that Word be installed.
func main() {
doc := document.New()
para := doc.AddParagraph()
run := para.AddRun()
para.SetStyle("Title")
run.AddText("Simple Document Formatting")
para = doc.AddParagraph()
para.SetStyle("Heading1")
run = para.AddRun()
run.AddText("Some Heading Text")
para = doc.AddParagraph()
para.SetStyle("Heading2")
run = para.AddRun()
run.AddText("Some Heading Text")
doc.SaveToFile("simple.docx")
cwd, _ := os.Getwd()
ConvertToPDF(filepath.Join(cwd, "simple.docx"), filepath.Join(cwd, "simple.pdf"))
}
// ConvertToPDF uses go-ole to convert a docx to a PDF using the Word application
func ConvertToPDF(source, destination string) {
ole.CoInitialize(0)
defer ole.CoUninitialize()
iunk, err := oleutil.CreateObject("Word.Application")
if err != nil {
log.Fatalf("error creating Word object: %s", err)
}
word := iunk.MustQueryInterface(ole.IID_IDispatch)
defer word.Release()
// opening then saving works due to the call to doc.Settings.SetUpdateFieldsOnOpen(true) above
docs := oleutil.MustGetProperty(word, "Documents").ToIDispatch()
wordDoc := oleutil.MustCallMethod(docs, "Open", source).ToIDispatch()
// file format constant comes from https://msdn.microsoft.com/en-us/vba/word-vba/articles/wdsaveformat-enumeration-word
const wdFormatPDF = 17
oleutil.MustCallMethod(wordDoc, "SaveAs2", destination, wdFormatPDF)
oleutil.MustCallMethod(wordDoc, "Close")
oleutil.MustCallMethod(word, "Quit")
}

View File

@ -1,18 +0,0 @@
// Copyright 2020 FoxyUtils ehf. All rights reserved.
package main
import (
"github.com/unidoc/unioffice/document"
)
func main() {
doc, err := document.Open("document.docx")
if err != nil {
panic(err)
}
doc.SetStrict(false) // document will be saved as Word document (this is a default option for new files)
doc.SaveToFile("conformance_transitional.docx")
doc.SetStrict(true) // document will be saved in the Strict mode
doc.SaveToFile("conformance_strict.docx")
}

View File

@ -1,103 +0,0 @@
// Copyright 2017 FoxyUtils ehf. All rights reserved.
package main
import (
"fmt"
"github.com/unidoc/unioffice/color"
"github.com/unidoc/unioffice/document"
"github.com/unidoc/unioffice/measurement"
"github.com/unidoc/unioffice/schema/soo/wml"
)
func main() {
doc := document.New()
para := doc.AddParagraph()
run := para.AddRun()
para.SetStyle("Title")
run.AddText("Simple Document Formatting")
para = doc.AddParagraph()
para.SetStyle("Heading1")
run = para.AddRun()
run.AddText("Some Heading Text")
para = doc.AddParagraph()
para.SetStyle("Heading2")
run = para.AddRun()
run.AddText("Some Heading Text")
para = doc.AddParagraph()
para.SetStyle("Heading3")
run = para.AddRun()
run.AddText("Some Heading Text")
para = doc.AddParagraph()
para.Properties().SetFirstLineIndent(0.5 * measurement.Inch)
run = para.AddRun()
run.AddText("A run is a string of characters with the same formatting. ")
run = para.AddRun()
run.Properties().SetBold(true)
run.Properties().SetFontFamily("Courier")
run.Properties().SetSize(15)
run.Properties().SetColor(color.Red)
run.AddText("Multiple runs with different formatting can exist in the same paragraph. ")
run = para.AddRun()
run.AddText("Adding breaks to a run will insert line breaks after the run. ")
run.AddBreak()
run.AddBreak()
run = createParaRun(doc, "Runs support styling options:")
run = createParaRun(doc, "small caps")
run.Properties().SetSmallCaps(true)
run = createParaRun(doc, "strike")
run.Properties().SetStrikeThrough(true)
run = createParaRun(doc, "double strike")
run.Properties().SetDoubleStrikeThrough(true)
run = createParaRun(doc, "outline")
run.Properties().SetOutline(true)
run = createParaRun(doc, "emboss")
run.Properties().SetEmboss(true)
run = createParaRun(doc, "shadow")
run.Properties().SetShadow(true)
run = createParaRun(doc, "imprint")
run.Properties().SetImprint(true)
run = createParaRun(doc, "highlighting")
run.Properties().SetHighlight(wml.ST_HighlightColorYellow)
run = createParaRun(doc, "underline")
run.Properties().SetUnderline(wml.ST_UnderlineWavyDouble, color.Red)
run = createParaRun(doc, "text effects")
run.Properties().SetEffect(wml.ST_TextEffectAntsRed)
nd := doc.Numbering.Definitions()[0]
for i := 1; i < 5; i++ {
p := doc.AddParagraph()
p.SetNumberingLevel(i - 1)
p.SetNumberingDefinition(nd)
run := p.AddRun()
run.AddText(fmt.Sprintf("Level %d", i))
}
doc.SaveToFile("simple.docx")
}
func createParaRun(doc *document.Document, s string) document.Run {
para := doc.AddParagraph()
run := para.AddRun()
run.AddText(s)
return run
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 500 KiB

View File

@ -1,260 +0,0 @@
// Copyright 2017 FoxyUtils ehf. All rights reserved.
package main
import (
"fmt"
"log"
"github.com/unidoc/unioffice/color"
"github.com/unidoc/unioffice/document"
"github.com/unidoc/unioffice/measurement"
"github.com/unidoc/unioffice/schema/soo/wml"
)
func main() {
doc := document.New()
// First Table
{
table := doc.AddTable()
// width of the page
table.Properties().SetWidthPercent(100)
// with thick borers
borders := table.Properties().Borders()
borders.SetAll(wml.ST_BorderSingle, color.Auto, 2*measurement.Point)
row := table.AddRow()
run := row.AddCell().AddParagraph().AddRun()
run.AddText("Name")
run.Properties().SetHighlight(wml.ST_HighlightColorYellow)
row.AddCell().AddParagraph().AddRun().AddText("John Smith")
row = table.AddRow()
row.AddCell().AddParagraph().AddRun().AddText("Street Address")
row.AddCell().AddParagraph().AddRun().AddText("111 Country Road")
}
doc.AddParagraph() // break up the consecutive tables
// Second Table
{
table := doc.AddTable()
// 4 inches wide
table.Properties().SetWidth(4 * measurement.Inch)
borders := table.Properties().Borders()
// thin borders
borders.SetAll(wml.ST_BorderSingle, color.Auto, measurement.Zero)
row := table.AddRow()
cell := row.AddCell()
// column span / merged cells
cell.Properties().SetColumnSpan(2)
run := cell.AddParagraph().AddRun()
run.AddText("Cells can span multiple columns")
row = table.AddRow()
cell = row.AddCell()
cell.Properties().SetVerticalMerge(wml.ST_MergeRestart)
cell.AddParagraph().AddRun().AddText("Vertical Merge")
row.AddCell().AddParagraph().AddRun().AddText("")
row = table.AddRow()
cell = row.AddCell()
cell.Properties().SetVerticalMerge(wml.ST_MergeContinue)
cell.AddParagraph().AddRun().AddText("Vertical Merge 2")
row.AddCell().AddParagraph().AddRun().AddText("")
row = table.AddRow()
row.AddCell().AddParagraph().AddRun().AddText("Street Address")
row.AddCell().AddParagraph().AddRun().AddText("111 Country Road")
}
doc.AddParagraph()
// Third Table
{
table := doc.AddTable()
table.Properties().SetWidthPercent(100)
borders := table.Properties().Borders()
borders.SetAll(wml.ST_BorderSingle, color.Auto, 1*measurement.Point)
hdrRow := table.AddRow()
cell := hdrRow.AddCell()
cell.Properties().SetShading(wml.ST_ShdSolid, color.LightGray, color.Auto)
cellPara := cell.AddParagraph()
cellPara.Properties().SetAlignment(wml.ST_JcLeft)
cellPara.AddRun().AddText("Left Align")
cell = hdrRow.AddCell()
cell.Properties().SetShading(wml.ST_ShdThinDiagStripe, color.Red, color.LightGray)
cellPara = cell.AddParagraph()
cellPara.Properties().SetAlignment(wml.ST_JcCenter)
cellPara.AddRun().AddText("Center Align")
cell = hdrRow.AddCell()
cell.Properties().SetShading(wml.ST_ShdPct20, color.Red, color.LightGray)
cellPara = cell.AddParagraph()
cellPara.Properties().SetAlignment(wml.ST_JcRight)
cellPara.AddRun().AddText("Right Align")
veryLightGray := color.RGB(240, 240, 240)
for i := 0; i < 5; i++ {
row := table.AddRow()
for j := 0; j < 3; j++ {
cell := row.AddCell()
// shade every other row
if i%2 == 0 {
cell.Properties().SetShading(wml.ST_ShdSolid, veryLightGray, color.Auto)
}
cell.AddParagraph().AddRun()
}
}
}
doc.AddParagraph()
// Fourth Table
{
table := doc.AddTable()
table.Properties().SetWidthPercent(50)
table.Properties().SetAlignment(wml.ST_JcTableCenter)
borders := table.Properties().Borders()
borders.SetAll(wml.ST_BorderSingle, color.Auto, 1*measurement.Point)
row := table.AddRow()
row.Properties().SetHeight(2*measurement.Inch, wml.ST_HeightRuleExact)
cell := row.AddCell()
cell.Properties().SetVerticalAlignment(wml.ST_VerticalJcCenter)
para := cell.AddParagraph()
para.Properties().SetAlignment(wml.ST_JcCenter)
run := para.AddRun()
run.AddText("hello world")
}
doc.AddParagraph()
// Fifth Table
{
table := doc.AddTable()
table.Properties().SetWidthPercent(90)
table.Properties().SetAlignment(wml.ST_JcTableCenter)
borders := table.Properties().Borders()
borders.SetAll(wml.ST_BorderSingle, color.Auto, 1*measurement.Point)
row := table.AddRow()
cell := row.AddCell()
cell.Properties().SetWidthPercent(25)
para := cell.AddParagraph()
run := para.AddRun()
run.AddText("hello")
cell = row.AddCell()
cell.Properties().SetWidthPercent(75)
para = cell.AddParagraph()
run = para.AddRun()
run.AddText("world")
// start a new table
doc.AddParagraph()
table = doc.AddTable()
table.Properties().SetWidthPercent(90)
table.Properties().SetAlignment(wml.ST_JcTableCenter)
borders = table.Properties().Borders()
borders.SetAll(wml.ST_BorderSingle, color.Auto, 1*measurement.Point)
row = table.AddRow()
cell = row.AddCell()
cell.Properties().SetWidth(0.25 * measurement.Inch)
para = cell.AddParagraph()
run = para.AddRun()
run.AddText("hello")
cell = row.AddCell()
cell.Properties().SetWidth(2.5 * measurement.Inch)
para = cell.AddParagraph()
run = para.AddRun()
run.AddText("world")
}
doc.AddParagraph()
// Seventh Table - Styled
{
// construct a table style
ts := doc.Styles.AddStyle("MyTableStyle", wml.ST_StyleTypeTable, false)
tp := ts.TableProperties()
tp.SetRowBandSize(1)
tp.SetColumnBandSize(1)
tp.SetTableIndent(measurement.Zero)
// horizomntal banding
s := ts.TableConditionalFormatting(wml.ST_TblStyleOverrideTypeBand1Horz)
s.CellProperties().SetShading(wml.ST_ShdSolid, color.LightBlue, color.Red)
// first row bold
s = ts.TableConditionalFormatting(wml.ST_TblStyleOverrideTypeFirstRow)
s.RunProperties().SetBold(true)
// last row bold
s = ts.TableConditionalFormatting(wml.ST_TblStyleOverrideTypeLastRow)
s.RunProperties().SetBold(true)
cb := s.CellProperties().Borders()
cb.SetTop(wml.ST_BorderDouble, color.Black, 0.5*measurement.Point)
tp.Borders().SetAll(wml.ST_BorderSingle, color.Blue, 0.5*measurement.Point)
table := doc.AddTable()
table.Properties().SetLayout(wml.ST_TblLayoutTypeFixed)
table.Properties().SetWidthPercent(90)
table.Properties().SetStyle("MyTableStyle")
look := table.Properties().TableLook()
look.SetFirstColumn(true)
look.SetFirstRow(true)
look.SetHorizontalBanding(true)
for r := 0; r < 5; r++ {
row := table.AddRow()
for c := 0; c < 5; c++ {
cell := row.AddCell()
cell.AddParagraph().AddRun().AddText(fmt.Sprintf("row %d col %d", r+1, c+1))
}
}
}
// Sixth Table - Insert
{
doc.InsertParagraphBefore(doc.Paragraphs()[5])
table := doc.InsertTableBefore(doc.Paragraphs()[5])
table.Properties().SetWidthPercent(90)
table.Properties().SetAlignment(wml.ST_JcTableCenter)
borders := table.Properties().Borders()
borders.SetAll(wml.ST_BorderSingle, color.Auto, 1*measurement.Point)
row := table.AddRow()
cell := row.AddCell()
cell.Properties().SetWidth(0.25 * measurement.Inch)
para := cell.AddParagraph()
run := para.AddRun()
run.AddText("Insert")
cell = row.AddCell()
cell.Properties().SetWidth(0.25 * measurement.Inch)
para = cell.AddParagraph()
run = para.AddRun()
run.AddText("new")
cell = row.AddCell()
cell.Properties().SetWidth(2.75 * measurement.Inch)
para = cell.AddParagraph()
run = para.AddRun()
run.AddText("table")
}
if err := doc.Validate(); err != nil {
log.Fatalf("error during validation: %s", err)
}
doc.SaveToFile("tables.docx")
}

View File

@ -1,96 +0,0 @@
// Copyright 2017 FoxyUtils ehf. All rights reserved.
package main
import (
"log"
"os"
"path/filepath"
"github.com/unidoc/unioffice/document"
"github.com/unidoc/unioffice/measurement"
"github.com/unidoc/unioffice/schema/soo/wml"
ole "github.com/go-ole/go-ole"
"github.com/go-ole/go-ole/oleutil"
)
// NOTE: This example can only run on Windows and requires that Word be installed.
var lorem = `Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin lobortis, lectus dictum feugiat tempus, sem neque finibus enim, sed eleifend sem nunc ac diam. Vestibulum tempus sagittis elementum`
func main() {
doc := document.New()
// Force the TOC to update upon opening the document
doc.Settings.SetUpdateFieldsOnOpen(true)
// Add a TOC
doc.AddParagraph().AddRun().AddField(document.FieldTOC)
// followed by a page break
doc.AddParagraph().Properties().AddSection(wml.ST_SectionMarkNextPage)
nd := doc.Numbering.AddDefinition()
for i := 0; i < 9; i++ {
lvl := nd.AddLevel()
lvl.SetFormat(wml.ST_NumberFormatNone)
lvl.SetAlignment(wml.ST_JcLeft)
if i%2 == 0 {
lvl.SetFormat(wml.ST_NumberFormatBullet)
lvl.RunProperties().SetFontFamily("Symbol")
lvl.SetText("")
}
lvl.Properties().SetLeftIndent(0.5 * measurement.Distance(i) * measurement.Inch)
}
// and finally paragraphs at different heading levels
for i := 0; i < 4; i++ {
para := doc.AddParagraph()
para.SetNumberingDefinition(nd)
para.Properties().SetHeadingLevel(1)
para.AddRun().AddText("First Level")
doc.AddParagraph().AddRun().AddText(lorem)
for i := 0; i < 3; i++ {
para := doc.AddParagraph()
para.SetNumberingDefinition(nd)
para.Properties().SetHeadingLevel(2)
para.AddRun().AddText("Second Level")
doc.AddParagraph().AddRun().AddText(lorem)
para = doc.AddParagraph()
para.SetNumberingDefinition(nd)
para.Properties().SetHeadingLevel(3)
para.AddRun().AddText("Third Level")
doc.AddParagraph().AddRun().AddText(lorem)
}
}
doc.SaveToFile("toc.docx")
cwd, _ := os.Getwd()
UpdateFields(filepath.Join(cwd, "toc.docx"))
}
// UpdateFields uses go-ole to convert a docx to a PDF using the Word application
func UpdateFields(source string) {
ole.CoInitialize(0)
defer ole.CoUninitialize()
iunk, err := oleutil.CreateObject("Word.Application")
if err != nil {
log.Fatalf("error creating Word object: %s", err)
}
defer iunk.Release()
word := iunk.MustQueryInterface(ole.IID_IDispatch)
defer word.Release()
docs := oleutil.MustGetProperty(word, "Documents").ToIDispatch()
defer docs.Release()
wordDoc := oleutil.MustCallMethod(docs, "Open", source).ToIDispatch()
defer wordDoc.Release()
const wdFormatXMLDocument = 12
oleutil.MustCallMethod(wordDoc, "SaveAs2", source, wdFormatXMLDocument)
oleutil.MustCallMethod(wordDoc, "Close")
oleutil.MustCallMethod(word, "Quit")
}

View File

@ -1,59 +0,0 @@
// Copyright 2017 FoxyUtils ehf. All rights reserved.
package main
import (
"github.com/unidoc/unioffice/document"
"github.com/unidoc/unioffice/measurement"
"github.com/unidoc/unioffice/schema/soo/wml"
)
var lorem = `Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin lobortis, lectus dictum feugiat tempus, sem neque finibus enim, sed eleifend sem nunc ac diam. Vestibulum tempus sagittis elementum`
func main() {
doc := document.New()
// Force the TOC to update upon opening the document
doc.Settings.SetUpdateFieldsOnOpen(true)
// Add a TOC
doc.AddParagraph().AddRun().AddField(document.FieldTOC)
// followed by a page break
doc.AddParagraph().Properties().AddSection(wml.ST_SectionMarkNextPage)
nd := doc.Numbering.AddDefinition()
for i := 0; i < 9; i++ {
lvl := nd.AddLevel()
lvl.SetFormat(wml.ST_NumberFormatNone)
lvl.SetAlignment(wml.ST_JcLeft)
if i%2 == 0 {
lvl.SetFormat(wml.ST_NumberFormatBullet)
lvl.RunProperties().SetFontFamily("Symbol")
lvl.SetText("")
}
lvl.Properties().SetLeftIndent(0.5 * measurement.Distance(i) * measurement.Inch)
}
// and finally paragraphs at different heading levels
for i := 0; i < 4; i++ {
para := doc.AddParagraph()
para.SetNumberingDefinition(nd)
para.Properties().SetHeadingLevel(1)
para.AddRun().AddText("First Level")
doc.AddParagraph().AddRun().AddText(lorem)
for i := 0; i < 3; i++ {
para := doc.AddParagraph()
para.SetNumberingDefinition(nd)
para.Properties().SetHeadingLevel(2)
para.AddRun().AddText("Second Level")
doc.AddParagraph().AddRun().AddText(lorem)
para = doc.AddParagraph()
para.SetNumberingDefinition(nd)
para.Properties().SetHeadingLevel(3)
para.AddRun().AddText("Third Level")
doc.AddParagraph().AddRun().AddText(lorem)
}
}
doc.SaveToFile("toc.docx")
}

View File

@ -1,77 +0,0 @@
// Copyright 2017 FoxyUtils ehf. All rights reserved.
package main
import (
"fmt"
"log"
"github.com/unidoc/unioffice/document"
)
var lorem = `Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin lobortis, lectus dictum feugiat tempus, sem neque finibus enim, sed eleifend sem nunc ac diam. Vestibulum tempus sagittis elementum`
func main() {
// When Word saves a document, it removes all unused styles. This means to
// copy the styles from an existing document, you must first create a
// document that contains text in each style of interest. As an example,
// see the template.docx in this directory. It contains a paragraph set in
// each style that Word supports by default.
doc, err := document.OpenTemplate("template.docx")
if err != nil {
log.Fatalf("error opening Windows Word 2016 document: %s", err)
}
// We can now print out all styles in the document, verifying that they
// exist.
for _, s := range doc.Styles.Styles() {
fmt.Println("style", s.Name(), "has ID of", s.StyleID(), "type is", s.Type())
}
// And create documents setting their style to the style ID (not style name).
para := doc.AddParagraph()
para.SetStyle("Title")
para.AddRun().AddText("My Document Title")
para = doc.AddParagraph()
para.SetStyle("Subtitle")
para.AddRun().AddText("Document Subtitle")
para = doc.AddParagraph()
para.SetStyle("Heading1")
para.AddRun().AddText("Major Section")
para = doc.AddParagraph()
para = doc.AddParagraph()
for i := 0; i < 4; i++ {
para.AddRun().AddText(lorem)
}
para = doc.AddParagraph()
para.SetStyle("Heading2")
para.AddRun().AddText("Minor Section")
para = doc.AddParagraph()
for i := 0; i < 4; i++ {
para.AddRun().AddText(lorem)
}
// using a pre-defined table style
table := doc.AddTable()
table.Properties().SetWidthPercent(90)
table.Properties().SetStyle("GridTable4-Accent1")
look := table.Properties().TableLook()
// these have default values in the style, so we manually turn some of them off
look.SetFirstColumn(false)
look.SetFirstRow(true)
look.SetLastColumn(false)
look.SetLastRow(true)
look.SetHorizontalBanding(true)
for r := 0; r < 5; r++ {
row := table.AddRow()
for c := 0; c < 5; c++ {
cell := row.AddCell()
cell.AddParagraph().AddRun().AddText(fmt.Sprintf("row %d col %d", r+1, c+1))
}
}
doc.SaveToFile("use-template.docx")
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 44 KiB

View File

@ -1,70 +0,0 @@
// Copyright 2017 FoxyUtils ehf. All rights reserved.
package main
import (
"log"
"github.com/unidoc/unioffice/schema/soo/dml"
"github.com/unidoc/unioffice/color"
"github.com/unidoc/unioffice/common"
"github.com/unidoc/unioffice/measurement"
"github.com/unidoc/unioffice/presentation"
)
const lorem = "Lorem ipsum dolor sit amet."
func main() {
ppt := presentation.New()
imgColor, err := common.ImageFromFile("gophercolor.png")
if err != nil {
log.Fatalf("unable to create image: %s", err)
}
irefColor, err := ppt.AddImage(imgColor)
if err != nil {
log.Fatal(err)
}
slide := ppt.AddSlide()
img := slide.AddImage(irefColor)
img.Properties().SetWidth(2 * measurement.Inch)
img.Properties().SetHeight(irefColor.RelativeHeight(2 * measurement.Inch))
tb := slide.AddTextBox()
tb.SetTextAnchor(dml.ST_TextAnchoringTypeCtr) // vertical center
para := tb.AddParagraph()
para.Properties().SetAlign(dml.ST_TextAlignTypeCtr) // horizontal center
run := para.AddRun()
run.Properties().SetBold(true)
run.Properties().SetSolidFill(color.Red)
run.SetText("Look a Gopher!")
tb.Properties().SetGeometry(dml.ST_ShapeTypeChevron)
tb.Properties().SetFlipHorizontal(true)
tb.Properties().SetSolidFill(color.LightBlue)
tb.Properties().LineProperties().SetWidth(0.125 * measurement.Inch)
tb.Properties().LineProperties().SetSolidFill(color.DarkBlue)
tb.Properties().SetPosition(2.5*measurement.Inch, 0.5*measurement.Inch)
tb = slide.AddTextBox()
tb.Properties().SetPosition(3.5*measurement.Inch, 2.5*measurement.Inch)
for i := 0; i < 4; i++ {
para = tb.AddParagraph()
para.Properties().SetBulletFont("Wingdings")
para.Properties().SetBulletChar("Ø")
para.Properties().SetLevel(int32(i))
run = para.AddRun()
if i%2 == 1 {
run.Properties().SetSolidFill(color.DarkRed)
}
run.SetText("Foo")
}
if err := ppt.Validate(); err != nil {
log.Fatal(err)
}
ppt.SaveToFile("complex.pptx")
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 44 KiB

View File

@ -1,50 +0,0 @@
// Copyright 2017 FoxyUtils ehf. All rights reserved.
package main
import (
"log"
"github.com/unidoc/unioffice/measurement"
"github.com/unidoc/unioffice/common"
"github.com/unidoc/unioffice/presentation"
)
func main() {
ppt := presentation.New()
imgColor, err := common.ImageFromFile("gophercolor.png")
if err != nil {
log.Fatalf("unable to create image: %s", err)
}
imgBW, err := common.ImageFromFile("gopher.png")
if err != nil {
log.Fatalf("unable to create image: %s", err)
}
irefColor, err := ppt.AddImage(imgColor)
if err != nil {
log.Fatal(err)
}
irefBW, err := ppt.AddImage(imgBW)
if err != nil {
log.Fatal(err)
}
slide := ppt.AddSlide()
ibColor := slide.AddImage(irefColor)
ibColor.Properties().SetWidth(2 * measurement.Inch)
ibColor.Properties().SetHeight(irefColor.RelativeHeight(2 * measurement.Inch))
ibBW := slide.AddImage(irefBW)
ibBW.Properties().SetWidth(2 * measurement.Inch)
ibBW.Properties().SetHeight(irefBW.RelativeHeight(2 * measurement.Inch))
ibBW.Properties().SetPosition(4*measurement.Inch, 4*measurement.Inch)
if err := ppt.Validate(); err != nil {
log.Fatal(err)
}
ppt.SaveToFile("image.pptx")
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 690 KiB

View File

@ -1,41 +0,0 @@
// Copyright 2017 FoxyUtils ehf. All rights reserved.
package main
import (
"log"
"github.com/unidoc/unioffice/color"
"github.com/unidoc/unioffice/measurement"
"github.com/unidoc/unioffice/schema/soo/dml"
"github.com/unidoc/unioffice/presentation"
)
func main() {
ppt := presentation.New()
for i := 0; i < 5; i++ {
slide := ppt.AddSlide()
tb := slide.AddTextBox()
tb.Properties().SetGeometry(dml.ST_ShapeTypeStar10)
tb.Properties().SetWidth(3 * measurement.Inch)
pos := measurement.Distance(i) * measurement.Inch
tb.Properties().SetPosition(pos, pos)
tb.Properties().SetSolidFill(color.AliceBlue)
tb.Properties().LineProperties().SetSolidFill(color.Blue)
p := tb.AddParagraph()
p.Properties().SetAlign(dml.ST_TextAlignTypeCtr)
r := p.AddRun()
r.SetText("gooxml")
r.Properties().SetSize(24 * measurement.Point)
}
if err := ppt.Validate(); err != nil {
log.Fatal(err)
}
ppt.SaveToFile("simple.pptx")
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 44 KiB

View File

@ -1,92 +0,0 @@
package main
import (
"fmt"
"os"
"time"
"github.com/unidoc/unioffice/common"
"github.com/unidoc/unioffice/schema/soo/dml"
"github.com/unidoc/unioffice/schema/soo/pml"
"github.com/unidoc/unioffice/presentation"
)
func main() {
startTime := time.Now()
// Start building pptx
ppt, err := presentation.OpenTemplate("template.potx")
if err != nil {
fmt.Println("presentation.OpenTemplate err ", err)
os.Exit(1)
}
// Clear out example slides
for _, s := range ppt.Slides() {
if err = ppt.RemoveSlide(s); err != nil {
fmt.Println("ppt.RemoveSlide err ", err)
os.Exit(1)
}
}
// Add new slide from template
layout, err := ppt.GetLayoutByName("Picture with Caption")
if err != nil {
fmt.Println("ppt.GetLayoutByName err ", err)
os.Exit(1)
}
// Add local image to pptx
image, err := common.ImageFromFile("gophercolor.png")
if err != nil {
fmt.Println("common.ImageFromFile err ", err)
os.Exit(1)
}
iRef, err := ppt.AddImage(image)
if err != nil {
fmt.Println("ppt.AddImage err ", err)
os.Exit(1)
}
slide, err := ppt.AddDefaultSlideWithLayout(layout)
if err != nil {
fmt.Println("ppt.AddDefaultSlideWithLayout err ", err)
os.Exit(1)
}
// Inject content into placeholders
title, _ := slide.GetPlaceholder(pml.ST_PlaceholderTypeTitle)
title.SetText("New title")
body, _ := slide.GetPlaceholder(pml.ST_PlaceholderTypeBody)
body.SetText("New body text")
imageRelID := slide.AddImageToRels(iRef)
pic, err := slide.GetPlaceholder(pml.ST_PlaceholderTypePic)
if err != nil {
fmt.Println("ppt.AddImage err ", err)
os.Exit(1)
}
spPr := dml.NewCT_ShapeProperties()
spPr.BlipFill = dml.NewCT_BlipFillProperties()
spPr.BlipFill.Blip = dml.NewCT_Blip()
spPr.BlipFill.Blip.EmbedAttr = &imageRelID
spPr.BlipFill.Stretch = dml.NewCT_StretchInfoProperties() // stretch to parent block with default values
pic.X().SpPr = spPr
if err := ppt.Validate(); err != nil {
fmt.Println("ppt.Validate err ", err)
}
if err := ppt.SaveToFile("mod.pptx"); err != nil {
fmt.Println("ppt.SaveToFile err ", err)
}
duration := time.Now().Sub(startTime).Seconds()
fmt.Println("success! took ", duration, " seconds")
}

View File

@ -1,74 +0,0 @@
package main
import (
"fmt"
"log"
"github.com/unidoc/unioffice/color"
"github.com/unidoc/unioffice/schema/soo/pml"
"github.com/unidoc/unioffice/presentation"
)
func main() {
ppt, err := presentation.OpenTemplate("template.pptx")
for i, layout := range ppt.SlideLayouts() {
fmt.Println(i, " LL ", layout.Name(), "/", layout.Type())
}
// remove any existing slides
for _, s := range ppt.Slides() {
ppt.RemoveSlide(s)
}
l, err := ppt.GetLayoutByName("Title and Caption")
if err != nil {
log.Fatalf("error retrieving layout: %s", err)
}
sld, err := ppt.AddDefaultSlideWithLayout(l)
if err != nil {
log.Fatalf("error adding slide: %s", err)
}
ph, _ := sld.GetPlaceholder(pml.ST_PlaceholderTypeTitle)
ph.SetText("Using gooxml")
ph, _ = sld.GetPlaceholder(pml.ST_PlaceholderTypeBody)
ph.SetText("Created with github.com/unidoc/unioffice/")
tac, _ := ppt.GetLayoutByName("Title and Content")
sld, err = ppt.AddDefaultSlideWithLayout(tac)
if err != nil {
log.Fatalf("error adding slide: %s", err)
}
ph, _ = sld.GetPlaceholder(pml.ST_PlaceholderTypeTitle)
ph.SetText("Placeholders")
ph, _ = sld.GetPlaceholderByIndex(1)
ph.ClearAll()
para := ph.AddParagraph()
run := para.AddRun()
run.SetText("Adding paragraphs can create bullets depending on the placeholder")
para.AddBreak()
run = para.AddRun()
run.SetText("Line breaks work as expected within a paragraph")
for i := 1; i < 5; i++ {
para = ph.AddParagraph()
para.Properties().SetLevel(int32(i))
run = para.AddRun()
run.SetText("Level controls indentation")
}
para = ph.AddParagraph()
run = para.AddRun()
run.SetText("One Last Paragraph in a different font")
run.Properties().SetSize(20)
run.Properties().SetFont("Courier")
run.Properties().SetSolidFill(color.Red)
if err != nil {
log.Fatalf("error opening template: %s", err)
}
ppt.SaveToFile("mod.pptx")
}

View File

@ -1,70 +0,0 @@
// Copyright 2017 FoxyUtils ehf. All rights reserved.
package main
import (
"fmt"
"log"
"github.com/unidoc/unioffice/spreadsheet"
)
func main() {
ss := spreadsheet.New()
sheet := ss.AddSheet()
// Create all of our data
row := sheet.AddRow()
row.AddCell().SetString("Item")
row.AddCell().SetString("Price")
row.AddCell().SetString("# Sold")
row.AddCell().SetString("Total")
for r := 0; r < 5; r++ {
row := sheet.AddRow()
row.AddCell().SetString(fmt.Sprintf("Product %d", r+1))
row.AddCell().SetNumber(1.23 * float64(r+1))
row.AddCell().SetNumber(float64(r%3 + 1))
row.AddCell().SetFormulaRaw(fmt.Sprintf("C%d*B%d", r+2, r+2))
}
// Charts need to reside in a drawing
dwng := ss.AddDrawing()
chart, anc := dwng.AddChart(spreadsheet.AnchorTypeTwoCell)
anc.SetWidthCells(10)
lc := chart.AddBarChart()
priceSeries := lc.AddSeries()
priceSeries.SetText("Price")
// Set a category axis reference on the first series to pull the product names
priceSeries.CategoryAxis().SetLabelReference(`'Sheet 1'!A2:A6`)
priceSeries.Values().SetReference(`'Sheet 1'!B2:B6`)
soldSeries := lc.AddSeries()
soldSeries.SetText("Sold")
soldSeries.Values().SetReference(`'Sheet 1'!C2:C6`)
totalSeries := lc.AddSeries()
totalSeries.SetText("Total")
totalSeries.Values().SetReference(`'Sheet 1'!D2:D6`)
// the line chart accepts up to two axes
ca := chart.AddCategoryAxis()
va := chart.AddValueAxis()
lc.AddAxis(ca)
lc.AddAxis(va)
ca.SetCrosses(va)
va.SetCrosses(ca)
// add a title and legend
title := chart.AddTitle()
title.SetText("Items Sold")
chart.AddLegend()
// and finally add the chart to the sheet
sheet.SetDrawing(dwng)
if err := ss.Validate(); err != nil {
log.Fatalf("error validating sheet: %s", err)
}
ss.SaveToFile("bar-chart.xlsx")
}

View File

@ -1,45 +0,0 @@
// Copyright 2017 FoxyUtils ehf. All rights reserved.
package main
import (
"log"
"github.com/unidoc/unioffice/color"
"github.com/unidoc/unioffice/schema/soo/sml"
"github.com/unidoc/unioffice/spreadsheet"
)
func main() {
ss := spreadsheet.New()
sheet := ss.AddSheet()
// set some cell text
sheet.Cell("C4").SetString("all sides")
// create and set a style
cs := ss.StyleSheet.AddCellStyle()
sheet.Cell("C4").SetStyle(cs)
// add some borders to the style (ordering isn't important, we could just as
// easily construct the cell style and then apply it to the cell)
bAll := ss.StyleSheet.AddBorder()
cs.SetBorder(bAll)
bAll.SetLeft(sml.ST_BorderStyleThin, color.Blue)
bAll.SetRight(sml.ST_BorderStyleThin, color.Blue)
bAll.SetTop(sml.ST_BorderStyleThin, color.Blue)
bAll.SetBottom(sml.ST_BorderStyleThin, color.Blue)
// red dashed line from top left down to bottom right
bAll.SetDiagonal(sml.ST_BorderStyleDashed, color.Red, false, true)
// Cell styles and thus border styles only apply to a single cell. This
// means to apply a boxed border around multiple cells, you would need to
// create individual styles for the corners, left, right, top and bottom
// sides. There is a helper that can do this for you, ignoring any diagonal
// borders.
sheet.SetBorder("B6:D10", bAll)
if err := ss.Validate(); err != nil {
log.Fatalf("error validating sheet: %s", err)
}
ss.SaveToFile("borders.xlsx")
}

View File

@ -1,58 +0,0 @@
// Copyright 2017 FoxyUtils ehf. All rights reserved.
package main
import (
"fmt"
"log"
"github.com/unidoc/unioffice/spreadsheet"
)
func main() {
ss := spreadsheet.New()
sheet := ss.AddSheet()
// Create all of our data
row := sheet.AddRow()
row.AddCell().SetString("Item")
row.AddCell().SetString("Price")
row.AddCell().SetString("# Sold")
row.AddCell().SetString("Total")
for r := 0; r < 5; r++ {
row := sheet.AddRow()
row.AddCell().SetString(fmt.Sprintf("Product %d", r+1))
row.AddCell().SetNumber(1.23 * float64(r+1))
row.AddCell().SetNumber(float64(r%3 + 1))
row.AddCell().SetFormulaRaw(fmt.Sprintf("C%d*B%d", r+2, r+2))
}
// Charts need to reside in a drawing
dwng := ss.AddDrawing()
chart, anc := dwng.AddChart(spreadsheet.AnchorTypeTwoCell)
anc.SetWidthCells(10)
lc := chart.AddBubbleChart()
soldSeries := lc.AddSeries()
soldSeries.CategoryAxis().SetLabelReference(`'Sheet 1'!A2:A6`)
soldSeries.SetText("Sold")
soldSeries.Values().SetReference(`'Sheet 1'!C2:C6`)
soldSeries.BubbleSizes().SetReference(`'Sheet 1'!D2:D6`)
// the line chart accepts up to two axes
ca := chart.AddCategoryAxis()
va := chart.AddValueAxis()
lc.AddAxis(ca)
lc.AddAxis(va)
ca.SetCrosses(va)
va.SetCrosses(ca)
// and finally add the chart to the sheet
sheet.SetDrawing(dwng)
if err := ss.Validate(); err != nil {
log.Fatalf("error validating sheet: %s", err)
}
ss.SaveToFile("bubble-chart.xlsx")
}

View File

@ -1,36 +0,0 @@
// Copyright 2017 FoxyUtils ehf. All rights reserved.
package main
// This example demonstrates outputing all cells in a row of an excel spreadsheet, including empty cells.
import (
"fmt"
"log"
"github.com/unidoc/unioffice/spreadsheet"
)
func main() {
ss, err := spreadsheet.Open("test.xlsx")
if err != nil {
log.Fatalf("error opening document: %s", err)
}
s := ss.Sheets()[0]
maxColumnIdx := s.MaxColumnIdx()
for _, row := range s.Rows() {
for _, cell := range row.CellsWithEmpty(maxColumnIdx) {
fmt.Println(cell.Reference(), ":", cell.GetFormattedValue())
}
}
fmt.Print("\n\n\n")
s.Cell("F4").SetString("Hello world")
maxColumnIdx = s.MaxColumnIdx()
for _, row := range s.Rows() {
for _, cell := range row.CellsWithEmpty(maxColumnIdx) {
fmt.Println(cell.Reference(), ":", cell.GetFormattedValue())
}
}
}

View File

@ -1,23 +0,0 @@
// Copyright 2017 FoxyUtils ehf. All rights reserved.
package main
import (
"log"
"github.com/unidoc/unioffice/spreadsheet"
)
func main() {
ss := spreadsheet.New()
sheet := ss.AddSheet()
sheet.Cell("A1").SetString("Hello World!")
sheet.Comments().AddCommentWithStyle("A1", "Gopher", "This looks interesting.")
sheet.Comments().AddCommentWithStyle("C10", "Gopher", "This is a different comment.")
if err := ss.Validate(); err != nil {
log.Fatalf("error validating sheet: %s", err)
}
ss.SaveToFile("comments.xlsx")
}

View File

@ -1,149 +0,0 @@
// Copyright 2017 FoxyUtils ehf. All rights reserved.
package main
import (
"fmt"
"log"
"math/rand"
"github.com/unidoc/unioffice/chart"
"github.com/unidoc/unioffice/color"
"github.com/unidoc/unioffice/measurement"
"github.com/unidoc/unioffice/spreadsheet"
"github.com/unidoc/unioffice/schema/soo/sml"
)
func main() {
ss := spreadsheet.New()
sheet := ss.AddSheet()
hdrStyle := ss.StyleSheet.AddCellStyle()
f := ss.StyleSheet.Fills().AddFill()
pf := f.SetPatternFill()
pf.SetFgColor(color.LightGray)
hdrStyle.SetFill(f)
fnt := ss.StyleSheet.AddFont()
fnt.SetBold(true)
hdrStyle.SetFont(fnt)
row := sheet.AddRow()
row.Cell("A").SetString("Item")
row.Cell("A").SetStyle(hdrStyle)
row.Cell("B").SetString("Price")
row.Cell("B").SetStyle(hdrStyle)
row.Cell("C").SetString("# Sold")
row.Cell("C").SetStyle(hdrStyle)
row.Cell("D").SetString("Total")
row.Cell("D").SetStyle(hdrStyle)
// Set some column widths
sheet.Column(1).SetWidth(1.5 * measurement.Inch)
sheet.Column(4).SetWidth(2 * measurement.Inch)
for r := 0; r < 5; r++ {
row := sheet.AddRow()
row.AddCell().SetString(fmt.Sprintf("Product %d", r+1))
row.AddCell().SetNumber(float64(rand.Intn(50)) / 10.0)
row.AddCell().SetNumber(float64(rand.Intn(50) + 1))
row.AddCell().SetFormulaRaw(fmt.Sprintf("C%d*B%d", r+2, r+2))
}
// add an auto-filter
sheet.SetAutoFilter("A1:D6")
// conditional formatting
// total column
cf := sheet.AddConditionalFormatting([]string{"D2:D6"})
rule := cf.AddRule()
db := rule.SetDataBar()
db.AddFormatValue(sml.ST_CfvoTypeMin, "0")
db.AddFormatValue(sml.ST_CfvoTypeMax, "0")
db.SetColor(color.Blue)
// sold column
cf = sheet.AddConditionalFormatting([]string{"B2:B6"})
rule = cf.AddRule()
cs := rule.SetColorScale()
cs.AddFormatValue(sml.ST_CfvoTypeMin, "0")
cs.AddFormatValue(sml.ST_CfvoTypePercentile, "50")
cs.AddFormatValue(sml.ST_CfvoTypeMax, "0")
cs.AddGradientStop(color.SuccessGreen)
cs.AddGradientStop(color.Orange)
cs.AddGradientStop(color.Red)
// Charts need to reside in a drawing
dwng := ss.AddDrawing()
chrt1, anc1 := dwng.AddChart(spreadsheet.AnchorTypeTwoCell)
chrt2, anc2 := dwng.AddChart(spreadsheet.AnchorTypeTwoCell)
addBar3DChart(chrt1)
addLineChart(chrt2)
anc1.SetWidth(9)
anc1.MoveTo(6, 1)
anc2.MoveTo(0, 9)
// and finally add the chart to the sheet
sheet.SetDrawing(dwng)
if err := ss.Validate(); err != nil {
log.Fatalf("error validating sheet: %s", err)
}
ss.SaveToFile("complex.xlsx")
}
func addBar3DChart(chrt chart.Chart) {
chrt.AddTitle().SetText("Bar Chart")
lc := chrt.AddBar3DChart()
priceSeries := lc.AddSeries()
priceSeries.SetText("Price")
// Set a category axis reference on the first series to pull the product names
priceSeries.CategoryAxis().SetLabelReference(`'Sheet 1'!A2:A6`)
priceSeries.Values().SetReference(`'Sheet 1'!B2:B6`)
soldSeries := lc.AddSeries()
soldSeries.SetText("Sold")
soldSeries.Values().SetReference(`'Sheet 1'!C2:C6`)
totalSeries := lc.AddSeries()
totalSeries.SetText("Total")
totalSeries.Values().SetReference(`'Sheet 1'!D2:D6`)
// the line chart accepts up to two axes
ca := chrt.AddCategoryAxis()
va := chrt.AddValueAxis()
lc.AddAxis(ca)
lc.AddAxis(va)
ca.SetCrosses(va)
va.SetCrosses(ca)
}
func addLineChart(chrt chart.Chart) {
chrt.AddTitle().SetText("Line Chart")
lc := chrt.AddLine3DChart()
priceSeries := lc.AddSeries()
priceSeries.SetText("Price")
// Set a category axis reference on the first series to pull the product names
priceSeries.CategoryAxis().SetLabelReference(`'Sheet 1'!A2:A6`)
priceSeries.Values().SetReference(`'Sheet 1'!B2:B6`)
soldSeries := lc.AddSeries()
soldSeries.SetText("Sold")
soldSeries.Values().SetReference(`'Sheet 1'!C2:C6`)
totalSeries := lc.AddSeries()
totalSeries.SetText("Total")
totalSeries.Values().SetReference(`'Sheet 1'!D2:D6`)
// the 3d line chart accepts three axes
ca := chrt.AddCategoryAxis()
va := chrt.AddValueAxis()
lc.AddAxis(ca)
lc.AddAxis(va)
lc.AddAxis(chart.NullAxis)
ca.SetCrosses(va)
va.SetCrosses(ca)
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 537 KiB

View File

@ -1,89 +0,0 @@
// Copyright 2017 FoxyUtils ehf. All rights reserved.
package main
import (
"log"
"math/rand"
"github.com/unidoc/unioffice/color"
"github.com/unidoc/unioffice/schema/soo/sml"
"github.com/unidoc/unioffice/spreadsheet"
)
func main() {
ss := spreadsheet.New()
sheet := ss.AddSheet()
for r := 0; r < 20; r++ {
if r != 0 && r%5 == 0 {
sheet.AddRow()
}
row := sheet.AddRow()
for c := 0; c < 5; c++ {
cell := row.AddCell()
cell.SetNumber(float64(rand.Intn(1000)) / 100.0)
}
}
{
cfmt := sheet.AddConditionalFormatting([]string{"A1:E5"})
r := cfmt.AddRule()
// cell is
r.SetType(sml.ST_CfTypeCellIs)
// greater than
r.SetOperator(sml.ST_ConditionalFormattingOperatorLessThan)
// four
r.SetConditionValue("4")
// should be formatted with this style
green := ss.StyleSheet.AddDifferentialStyle()
green.Fill().SetPatternFill().SetBgColor(color.SuccessGreen)
r.SetStyle(green)
r = cfmt.AddRule()
// cell is
r.SetType(sml.ST_CfTypeCellIs)
// greater than
r.SetOperator(sml.ST_ConditionalFormattingOperatorGreaterThan)
// four
r.SetConditionValue("7")
// should be formatted with this style
red := ss.StyleSheet.AddDifferentialStyle()
red.Fill().SetPatternFill().SetBgColor(color.Red)
r.SetStyle(red)
}
{
// Color gradient by value
cfmt := sheet.AddConditionalFormatting([]string{"A7:E11"})
r := cfmt.AddRule()
cs := r.SetColorScale()
cs.AddFormatValue(sml.ST_CfvoTypeMin, "0")
cs.AddGradientStop(color.Red)
cs.AddFormatValue(sml.ST_CfvoTypePercentile, "50")
cs.AddGradientStop(color.Yellow)
cs.AddFormatValue(sml.ST_CfvoTypeMax, "0")
cs.AddGradientStop(color.SuccessGreen)
}
{
// Icons
cfmt := sheet.AddConditionalFormatting([]string{"A13:E17"})
r := cfmt.AddRule()
icons := r.SetIcons()
icons.SetIcons(sml.ST_IconSetType3TrafficLights1)
icons.AddFormatValue(sml.ST_CfvoTypePercent, "0")
icons.AddFormatValue(sml.ST_CfvoTypePercent, "040")
icons.AddFormatValue(sml.ST_CfvoTypePercent, "90")
}
{
cfmt := sheet.AddConditionalFormatting([]string{"A19:E23"})
r := cfmt.AddRule()
db := r.SetDataBar()
db.AddFormatValue(sml.ST_CfvoTypeMin, "0")
db.AddFormatValue(sml.ST_CfvoTypeMax, "0")
db.SetColor(color.Blue)
}
if err := ss.Validate(); err != nil {
log.Fatalf("error validating sheet: %s", err)
}
ss.SaveToFile("conditional-formatting.xlsx")
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 476 KiB

View File

@ -1,93 +0,0 @@
// Copyright 2017 FoxyUtils ehf. All rights reserved.
package main
// This example demonstrates flattening all formulas from an input Excel file and outputs the flattened values to a new xlsx.
import (
"log"
"fmt"
"runtime"
"time"
"github.com/unidoc/unioffice/spreadsheet"
"github.com/unidoc/unioffice/spreadsheet/formula"
)
func main() {
ss, err := spreadsheet.Open("formulas.xlsx")
if err != nil {
log.Fatalf("error opening document: %s", err)
}
sheets := ss.Sheets()
start := time.Now().UnixNano()
formEv := formula.NewEvaluator()
for _, sheet := range sheets {
fmt.Println("Sheet name:", sheet.Name())
ctx := sheet.FormulaContext()
for _, row := range sheet.Rows() {
for _, cell := range row.Cells() {
// copying cell style
cellStyle := spreadsheet.CellStyle{}
x := cell.X()
if x.SAttr != nil {
sid := *x.SAttr
cellStyle = ss.StyleSheet.GetCellStyle(sid)
}
// copying value
c := ctx.Cell(cell.Reference(), formEv)
value := ""
if cell.X().V != nil {
value = *cell.X().V
}
cell.Clear()
setValue(cell, c, value)
// setting cell style
if !cellStyle.IsEmpty() {
cell.SetStyle(cellStyle)
}
}
}
}
finish := time.Now().UnixNano()
fmt.Printf("total time: %d ns\n", finish - start)
PrintMemUsage()
ss.SaveToFile("values.xlsx")
}
func setValue(cell spreadsheet.Cell, c formula.Result, value string) {
switch c.Type {
case formula.ResultTypeNumber:
if c.IsBoolean {
cell.SetBool(value != "0")
} else {
cell.SetNumber(c.ValueNumber)
}
case formula.ResultTypeString:
cell.SetString(c.ValueString)
case formula.ResultTypeList:
setValue(cell, c.ValueList[0], value)
case formula.ResultTypeArray:
setValue(cell, c.ValueArray[0][0], value)
case formula.ResultTypeError:
cell.SetError(c.ValueString)
}
}
func PrintMemUsage() {
var m runtime.MemStats
runtime.ReadMemStats(&m)
// For info on each, see: https://golang.org/pkg/runtime/#MemStats
fmt.Println("Memory usage:")
fmt.Printf("Alloc = %v MiB", bToMb(m.Alloc))
fmt.Printf("\tTotalAlloc = %v MiB", bToMb(m.TotalAlloc))
fmt.Printf("\tSys = %v MiB", bToMb(m.Sys))
fmt.Printf("\tNumGC = %v\n", m.NumGC)
}
func bToMb(b uint64) uint64 {
return b / 1024 / 1024
}

View File

@ -1,37 +0,0 @@
// Copyright 2017 FoxyUtils ehf. All rights reserved.
package main
import (
"fmt"
"github.com/unidoc/unioffice/spreadsheet"
"github.com/unidoc/unioffice/spreadsheet/formula"
)
func main() {
fmt.Println("Currently support", len(formula.SupportedFunctions()), "functions")
fmt.Println(formula.SupportedFunctions())
ss := spreadsheet.New()
sheet := ss.AddSheet()
sheet.Cell("A1").SetNumber(1.2)
sheet.Cell("A2").SetNumber(2.3)
sheet.Cell("A3").SetNumber(2.3)
formEv := formula.NewEvaluator()
// the formula context allows the formula evaluator to pull data from a
// sheet
a1Cell := sheet.FormulaContext().Cell("A1", formEv)
fmt.Println("A1 is", a1Cell.Value())
// So that when evaluating formulas, live workbook data is used. Formulas
// can be evaluated directly in the context of a sheet.
result := formEv.Eval(sheet.FormulaContext(), "SUM(A1:A3)")
fmt.Println("SUM(A1:A3) is", result.Value())
// Or, stored in a cell and the cell evaulated.
sheet.Cell("A4").SetFormulaRaw("SUM(A1:A3)+SUM(A1:A3)")
a4Value := formEv.Eval(sheet.FormulaContext(), "A4")
fmt.Println("A4 is", a4Value.Value())
}

View File

@ -1,53 +0,0 @@
// Copyright 2017 FoxyUtils ehf. All rights reserved.
package main
import (
"fmt"
"log"
"github.com/unidoc/unioffice/color"
"github.com/unidoc/unioffice/schema/soo/sml"
"github.com/unidoc/unioffice/spreadsheet"
)
func main() {
ss := spreadsheet.New()
sheet := ss.AddSheet()
hdrStyle := ss.StyleSheet.AddCellStyle()
hdrStyle.SetHorizontalAlignment(sml.ST_HorizontalAlignmentCenter)
lightGray := ss.StyleSheet.Fills().AddFill()
lightGrayPattern := lightGray.SetPatternFill()
lightGrayPattern.SetFgColor(color.LightGray)
hdrStyle.SetFill(lightGray)
hdr := sheet.AddRow()
hdrCell := hdr.AddCell()
hdrCell.SetString("Products")
hdrCell.SetStyle(hdrStyle)
hdrCell = hdr.AddCell()
hdrCell.SetString("# Sold")
hdrCell.SetStyle(hdrStyle)
for i := 0; i < 10; i++ {
row := sheet.AddRow()
cell := row.AddCell()
cell.SetString(fmt.Sprintf("Product %d", i+1))
cell = row.AddCell()
cell.SetNumber(float64(i + 1))
}
totalRow := sheet.AddRow()
totalCell := totalRow.AddCell()
totalCell = totalRow.AddCell()
totalCell.SetFormulaRaw("SUM(B2:B11)")
ss.RecalculateFormulas()
if err := ss.Validate(); err != nil {
log.Fatalf("error validating: %s", err)
}
ss.SaveToFile("formula.xlsx")
}

View File

@ -1,44 +0,0 @@
// Copyright 2017 FoxyUtils ehf. All rights reserved.
package main
import (
"log"
"math/rand"
"github.com/unidoc/unioffice/spreadsheet"
)
func main() {
ss := spreadsheet.New()
sheet := ss.AddSheet()
row := sheet.AddRow()
row.AddCell()
for i := 0; i < 99; i++ {
row.AddCell().SetString("Header")
}
for i := 0; i < 100; i++ {
row = sheet.AddRow()
row.AddCell().SetString("Header")
for j := 0; j < 99; j++ {
row.AddCell().SetNumber(rand.Float64() * 100)
}
}
// freeze the first row and column
sheet.SetFrozen(true, true)
/* this is equivalent to
v := sheet.InitialView()
v.SetState(sml.ST_PaneStateFrozen)
v.SetYSplit(1)
v.SetXSplit(1)
v.SetTopLeft("B2")
*/
if err := ss.Validate(); err != nil {
log.Fatalf("error validating sheet: %s", err)
}
ss.SaveToFile("freeze-rows-cols.xlsx")
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 44 KiB

View File

@ -1,50 +0,0 @@
// Copyright 2017 FoxyUtils ehf. All rights reserved.
package main
import (
"log"
"math"
"github.com/unidoc/unioffice/common"
"github.com/unidoc/unioffice/measurement"
"github.com/unidoc/unioffice/spreadsheet"
)
func main() {
ss := spreadsheet.New()
// add a single sheet
sheet := ss.AddSheet()
img, err := common.ImageFromFile("gophercolor.png")
if err != nil {
log.Fatalf("unable to create image: %s", err)
}
iref, err := ss.AddImage(img)
if err != nil {
log.Fatalf("unable to add image to workbook: %s", err)
}
dwng := ss.AddDrawing()
sheet.SetDrawing(dwng)
for i := float64(0); i < 360; i += 30 {
anc := dwng.AddImage(iref, spreadsheet.AnchorTypeAbsolute)
ang := i * math.Pi / 180
x := 2 + 2*math.Cos(ang)
y := 2 + +2*math.Sin(ang)
anc.SetColOffset(measurement.Distance(x) * measurement.Inch)
anc.SetRowOffset(measurement.Distance(y) * measurement.Inch)
// set the image to 1x1 inches
var w measurement.Distance = 1 * measurement.Inch
anc.SetWidth(w)
anc.SetHeight(iref.RelativeHeight(w))
}
if err := ss.Validate(); err != nil {
log.Fatalf("error validating sheet: %s", err)
}
ss.SaveToFile("image.xlsx")
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 383 KiB

View File

@ -1,36 +0,0 @@
// Copyright 2017 FoxyUtils ehf. All rights reserved.
package main
import (
"fmt"
"log"
"github.com/unidoc/unioffice/spreadsheet"
)
func main() {
ss := spreadsheet.New()
// add a single sheet
sheet := ss.AddSheet()
// rows
for r := 0; r < 5; r++ {
row := sheet.AddRow()
// and cells
for c := 0; c < 5; c++ {
cell := row.AddCell()
cell.SetString(fmt.Sprintf("row %d cell %d", r, c))
}
}
// no insert some rows after row 2
for i := 0; i < 4; i++ {
sheet.InsertRow(2).AddCell().SetString(fmt.Sprintf("inserted at 2, iter %d", i))
}
if err := ss.Validate(); err != nil {
log.Fatalf("error validating sheet: %s", err)
}
ss.SaveToFile("insert-rows.xlsx")
}

View File

@ -1,74 +0,0 @@
// Copyright 2017 FoxyUtils ehf. All rights reserved.
package main
import (
"fmt"
"log"
"github.com/unidoc/unioffice/spreadsheet"
)
func main() {
ss := spreadsheet.New()
sheet := ss.AddSheet()
// Create all of our data
row := sheet.AddRow()
row.AddCell().SetString("Item")
row.AddCell().SetString("Price")
row.AddCell().SetString("# Sold")
row.AddCell().SetString("Total")
for r := 0; r < 5; r++ {
row := sheet.AddRow()
row.AddCell().SetString(fmt.Sprintf("Product %d", r+1))
row.AddCell().SetNumber(1.23 * float64(r+1))
row.AddCell().SetNumber(float64(r%3 + 1))
row.AddCell().SetFormulaRaw(fmt.Sprintf("C%d*B%d", r+2, r+2))
}
// Charts need to reside in a drawing
dwng := ss.AddDrawing()
crt, anc := dwng.AddChart(spreadsheet.AnchorTypeTwoCell)
anc.SetWidthCells(10)
lc := crt.AddLine3DChart()
priceSeries := lc.AddSeries()
priceSeries.SetText("Price")
// Set a category axis reference on the first series to pull the product names
priceSeries.CategoryAxis().SetLabelReference(`'Sheet 1'!A2:A6`)
priceSeries.Values().SetReference(`'Sheet 1'!B2:B6`)
soldSeries := lc.AddSeries()
soldSeries.SetText("Sold")
soldSeries.Values().SetReference(`'Sheet 1'!C2:C6`)
totalSeries := lc.AddSeries()
totalSeries.SetText("Total")
totalSeries.Values().SetReference(`'Sheet 1'!D2:D6`)
// the line chart accepts up to two axes
ca := crt.AddCategoryAxis()
va := crt.AddValueAxis()
lc.AddAxis(ca)
lc.AddAxis(va)
sax := crt.AddSeriesAxis()
lc.AddAxis(sax)
ca.SetCrosses(va)
va.SetCrosses(ca)
sax.SetCrosses(va)
// add a title and legend
title := crt.AddTitle()
title.SetText("Items Sold")
crt.AddLegend()
// and finally add the chart to the sheet
sheet.SetDrawing(dwng)
if err := ss.Validate(); err != nil {
log.Fatalf("error validating sheet: %s", err)
}
ss.SaveToFile("line-chart-3d.xlsx")
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 451 KiB

View File

@ -1,55 +0,0 @@
// Copyright 2017 FoxyUtils ehf. All rights reserved.
package main
import (
"log"
"github.com/unidoc/unioffice/spreadsheet"
)
func main() {
ss := spreadsheet.New()
sheet := ss.AddSheet()
dwng := ss.AddDrawing()
chart, anc := dwng.AddChart(spreadsheet.AnchorTypeTwoCell)
anc.MoveTo(0, 0)
anc.SetWidth(10)
// No cell data needed, we can supply data directly to the chart
lc := chart.AddLineChart()
priceSeries := lc.AddSeries()
priceSeries.SetText("Price")
priceSeries.CategoryAxis().SetValues([]string{"Prod 1", "Prod 2", "Prod 3", "Prod 4", "Prod 5"})
priceSeries.Values().SetValues([]float64{5, 4, 3, 9, 2})
soldSeries := lc.AddSeries()
soldSeries.SetText("Sold")
soldSeries.Values().SetValues([]float64{1, 2, 3, 4, 5})
totalSeries := lc.AddSeries()
totalSeries.SetText("Total")
totalSeries.Values().SetValues([]float64{9, 2, 1, 8, 1})
// the line chart accepts up to two axes
ca := chart.AddCategoryAxis()
va := chart.AddValueAxis()
lc.AddAxis(ca)
lc.AddAxis(va)
ca.SetCrosses(va)
va.SetCrosses(ca)
// add a title and legend
title := chart.AddTitle()
title.SetText("Items Sold")
chart.AddLegend()
// and finally add the chart to the sheet
sheet.SetDrawing(dwng)
if err := ss.Validate(); err != nil {
log.Fatalf("error validating sheet: %s", err)
}
ss.SaveToFile("line-chart-no-data.xlsx")
}

View File

@ -1,71 +0,0 @@
// Copyright 2017 FoxyUtils ehf. All rights reserved.
package main
import (
"fmt"
"log"
"github.com/unidoc/unioffice/spreadsheet"
)
func main() {
ss := spreadsheet.New()
sheet := ss.AddSheet()
// Create all of our data
row := sheet.AddRow()
row.AddCell().SetString("Item")
row.AddCell().SetString("Price")
row.AddCell().SetString("# Sold")
row.AddCell().SetString("Total")
for r := 0; r < 5; r++ {
row := sheet.AddRow()
row.AddCell().SetString(fmt.Sprintf("Product %d", r+1))
row.AddCell().SetNumber(1.23 * float64(r+1))
row.AddCell().SetNumber(float64(r%3 + 1))
row.AddCell().SetFormulaRaw(fmt.Sprintf("C%d*B%d", r+2, r+2))
}
// Charts need to reside in a drawing
dwng := ss.AddDrawing()
chart, anc := dwng.AddChart(spreadsheet.AnchorTypeTwoCell)
// make it a bit wider than the default
anc.SetWidthCells(10)
lc := chart.AddLineChart()
priceSeries := lc.AddSeries()
priceSeries.SetText("Price")
// Set a category axis reference on the first series to pull the product names
priceSeries.CategoryAxis().SetLabelReference(`'Sheet 1'!A2:A6`)
priceSeries.Values().SetReference(`'Sheet 1'!B2:B6`)
soldSeries := lc.AddSeries()
soldSeries.SetText("Sold")
soldSeries.Values().SetReference(`'Sheet 1'!C2:C6`)
totalSeries := lc.AddSeries()
totalSeries.SetText("Total")
totalSeries.Values().SetReference(`'Sheet 1'!D2:D6`)
// the line chart accepts up to two axes
ca := chart.AddCategoryAxis()
va := chart.AddValueAxis()
lc.AddAxis(ca)
lc.AddAxis(va)
ca.SetCrosses(va)
va.SetCrosses(ca)
// add a title and legend
title := chart.AddTitle()
title.SetText("Items Sold")
chart.AddLegend()
// and finally add the chart to the sheet
sheet.SetDrawing(dwng)
if err := ss.Validate(); err != nil {
log.Fatalf("error validating sheet: %s", err)
}
ss.SaveToFile("line-chart.xlsx")
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 364 KiB

View File

@ -1,60 +0,0 @@
// Copyright 2017 FoxyUtils ehf. All rights reserved.
package main
import (
"flag"
"fmt"
"log"
"os"
"runtime/pprof"
"time"
"github.com/unidoc/unioffice/spreadsheet"
)
var cpuprofile = flag.String("cpuprofile", "", "write cpu profile to file")
func main() {
flag.Parse()
if *cpuprofile != "" {
f, err := os.Create(*cpuprofile)
if err != nil {
log.Fatal(err)
}
pprof.StartCPUProfile(f)
defer pprof.StopCPUProfile()
}
start := time.Now()
ss := spreadsheet.New()
nRows := 30000
nCols := 100
sheet := ss.AddSheet()
// rows
for r := 0; r < nRows; r++ {
row := sheet.AddRow()
// and cells
for c := 0; c < nCols; c++ {
cell := row.AddCell()
cell.SetNumber(float64(r + c))
}
}
if err := ss.Validate(); err != nil {
log.Fatalf("error validating sheet: %s", err)
}
fmt.Printf("creating %d rows * %d cells took %s\n", nRows, nCols, time.Now().Sub(start))
ss.SaveToFile("lots-of-rows.xlsx")
start = time.Now()
fmt.Printf("saving took %s\n", time.Now().Sub(start))
start = time.Now()
_, err := spreadsheet.Open("lots-of-rows.xlsx")
if err != nil {
log.Fatalf("error opening sheet: %s", err)
}
fmt.Printf("reading took %s\n", time.Now().Sub(start))
}

View File

@ -1,35 +0,0 @@
// Copyright 2017 FoxyUtils ehf. All rights reserved.
package main
import (
"fmt"
"log"
"github.com/unidoc/unioffice/spreadsheet"
"github.com/unidoc/unioffice/schema/soo/sml"
)
func main() {
ss := spreadsheet.New()
sheet := ss.AddSheet()
sheet.Cell("A1").SetString("Hello World!")
sheet.Cell("B1").SetString("will not be visible") // as it's not the first cell within a merged range Excel warns you when you do this through the UI
sheet.AddMergedCells("A1", "C2")
centered := ss.StyleSheet.AddCellStyle()
centered.SetHorizontalAlignment(sml.ST_HorizontalAlignmentCenter)
centered.SetVerticalAlignment(sml.ST_VerticalAlignmentCenter)
sheet.Cell("A1").SetStyle(centered)
for _, m := range sheet.MergedCells() {
fmt.Println("merged region", m.Reference(), "has contents", m.Cell().GetString())
}
if err := ss.Validate(); err != nil {
log.Fatalf("error validating sheet: %s", err)
}
ss.SaveToFile("merged.xlsx")
}

View File

@ -1,101 +0,0 @@
// Copyright 2017 FoxyUtils ehf. All rights reserved.
package main
import (
"fmt"
"log"
"github.com/unidoc/unioffice/chart"
"github.com/unidoc/unioffice/spreadsheet"
)
func main() {
ss := spreadsheet.New()
sheet := ss.AddSheet()
// Create all of our data
row := sheet.AddRow()
row.AddCell().SetString("Item")
row.AddCell().SetString("Price")
row.AddCell().SetString("# Sold")
row.AddCell().SetString("Total")
for r := 0; r < 5; r++ {
row := sheet.AddRow()
row.AddCell().SetString(fmt.Sprintf("Product %d", r+1))
row.AddCell().SetNumber(1.23 * float64(r+1))
row.AddCell().SetNumber(float64(r%3 + 1))
row.AddCell().SetFormulaRaw(fmt.Sprintf("C%d*B%d", r+2, r+2))
}
// Charts need to reside in a drawing
dwng := ss.AddDrawing()
chrt1, anc1 := dwng.AddChart(spreadsheet.AnchorTypeTwoCell)
chrt2, anc2 := dwng.AddChart(spreadsheet.AnchorTypeTwoCell)
addBarChart(chrt1)
addLineChart(chrt2)
anc1.SetWidth(9)
anc1.MoveTo(5, 1)
anc2.MoveTo(1, 23)
// and finally add the chart to the sheet
sheet.SetDrawing(dwng)
if err := ss.Validate(); err != nil {
log.Fatalf("error validating sheet: %s", err)
}
ss.SaveToFile("multiple-chart.xlsx")
}
func addBarChart(chrt chart.Chart) {
chrt.AddTitle().SetText("Bar Chart")
lc := chrt.AddBarChart()
priceSeries := lc.AddSeries()
priceSeries.SetText("Price")
// Set a category axis reference on the first series to pull the product names
priceSeries.CategoryAxis().SetLabelReference(`'Sheet 1'!A2:A6`)
priceSeries.Values().SetReference(`'Sheet 1'!B2:B6`)
soldSeries := lc.AddSeries()
soldSeries.SetText("Sold")
soldSeries.Values().SetReference(`'Sheet 1'!C2:C6`)
totalSeries := lc.AddSeries()
totalSeries.SetText("Total")
totalSeries.Values().SetReference(`'Sheet 1'!D2:D6`)
// the line chart accepts up to two axes
ca := chrt.AddCategoryAxis()
va := chrt.AddValueAxis()
lc.AddAxis(ca)
lc.AddAxis(va)
ca.SetCrosses(va)
va.SetCrosses(ca)
}
func addLineChart(chrt chart.Chart) {
chrt.AddTitle().SetText("Line Chart")
lc := chrt.AddLineChart()
priceSeries := lc.AddSeries()
priceSeries.SetText("Price")
// Set a category axis reference on the first series to pull the product names
priceSeries.CategoryAxis().SetLabelReference(`'Sheet 1'!A2:A6`)
priceSeries.Values().SetReference(`'Sheet 1'!B2:B6`)
soldSeries := lc.AddSeries()
soldSeries.SetText("Sold")
soldSeries.Values().SetReference(`'Sheet 1'!C2:C6`)
totalSeries := lc.AddSeries()
totalSeries.SetText("Total")
totalSeries.Values().SetReference(`'Sheet 1'!D2:D6`)
// the line chart accepts up to two axes
ca := chrt.AddCategoryAxis()
va := chrt.AddValueAxis()
lc.AddAxis(ca)
lc.AddAxis(va)
ca.SetCrosses(va)
va.SetCrosses(ca)
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 506 KiB

View File

@ -1,53 +0,0 @@
// Copyright 2017 FoxyUtils ehf. All rights reserved.
package main
import (
"fmt"
"log"
"github.com/unidoc/unioffice/spreadsheet"
)
func main() {
ss := spreadsheet.New()
sheet := ss.AddSheet()
for r := 0; r < 5; r++ {
row := sheet.AddRow()
// can't add an un-named cell to row zero here as we also add cell 'A1',
// meaning the un-naned cell must come before 'A1' which is invalid.
if r != 0 {
// an unnamed cell displays in the first available column
row.AddCell().SetString("unnamed-before")
}
// setting these to A, B, C, specifically
cell := row.AddNamedCell(fmt.Sprintf("%c", 'A'+r))
cell.SetString(fmt.Sprintf("row %d", r))
// an un-named cell after a named cell is display immediately after a named cell
row.AddCell().SetString("unnamed-after")
}
sheet.AddNumberedRow(26).AddNamedCell("C").SetString("Cell C26")
// This line would create an invalid sheet with two identically ID'd rows
// which would fail validation below
// sheet.AddNumberedRow(26).AddNamedCell("C27").SetString("Cell C27")
// so instead use Row which will create or retrieve an existing row
sheet.Row(26).AddNamedCell("E").SetString("Cell E26")
sheet.Row(26).Cell("F").SetString("Cell F26")
// You can also reference cells fully from the sheet.
sheet.Cell("H1").SetString("Cell H1")
sheet.Cell("H2").SetString("Cell H2")
sheet.Cell("H3").SetString("Cell H3")
if err := ss.Validate(); err != nil {
log.Fatalf("error validating sheet: %s", err)
}
ss.SaveToFile("named-cells.xlsx")
}

View File

@ -1,81 +0,0 @@
// Copyright 2017 FoxyUtils ehf. All rights reserved.
package main
import (
"fmt"
"log"
"github.com/unidoc/unioffice/spreadsheet"
)
func main() {
ss := spreadsheet.New()
sheet := ss.AddSheet()
// Create all of our data
row := sheet.AddRow()
row.AddCell().SetString("Item")
row.AddCell().SetString("Price")
row.AddCell().SetString("# Sold")
row.AddCell().SetString("Total")
for r := 0; r < 5; r++ {
row := sheet.AddRow()
row.AddCell().SetString(fmt.Sprintf("Product %d", r+1))
row.AddCell().SetNumber(1.23 * float64(r+1))
row.AddCell().SetNumber(float64(r%3 + 1))
row.AddCell().SetFormulaRaw(fmt.Sprintf("C%d*B%d", r+2, r+2))
}
// create some defined names for various ranges that we can use
// instead of the sheet/cell references
productNames := ss.AddDefinedName("ProductNames", sheet.RangeReference("A2:A6"))
prices := ss.AddDefinedName("Prices", sheet.RangeReference("B2:B6"))
sold := ss.AddDefinedName("Sold", sheet.RangeReference("C2:C6"))
total := ss.AddDefinedName("Total", sheet.RangeReference("D2:D6"))
for _, dn := range ss.DefinedNames() {
fmt.Println("- defined name", dn.Name(), "=", dn.Content())
}
// Charts need to reside in a drawing
dwng := ss.AddDrawing()
chart, anc := dwng.AddChart(spreadsheet.AnchorTypeTwoCell)
anc.SetWidthCells(10)
lc := chart.AddLineChart()
priceSeries := lc.AddSeries()
priceSeries.SetText("Price")
// Set a category axis reference on the first series to pull the product names
priceSeries.CategoryAxis().SetLabelReference(`'Sheet 1'!` + productNames.Name())
priceSeries.Values().SetReference(`'Sheet 1'!` + prices.Name())
soldSeries := lc.AddSeries()
soldSeries.SetText("Sold")
soldSeries.Values().SetReference(`'Sheet 1'!` + sold.Name())
totalSeries := lc.AddSeries()
totalSeries.SetText("Total")
totalSeries.Values().SetReference(`'Sheet 1'!` + total.Name())
// the line chart accepts up to two axes
ca := chart.AddCategoryAxis()
va := chart.AddValueAxis()
lc.AddAxis(ca)
lc.AddAxis(va)
ca.SetCrosses(va)
va.SetCrosses(ca)
// add a title and legend
title := chart.AddTitle()
title.SetText("Items Sold")
chart.AddLegend()
// and finally add the chart to the sheet
sheet.SetDrawing(dwng)
if err := ss.Validate(); err != nil {
log.Fatalf("error validating sheet: %s", err)
}
ss.SaveToFile("named-ranges.xlsx")
}

View File

@ -1,60 +0,0 @@
// Copyright 2017 FoxyUtils ehf. All rights reserved.
package main
import (
"log"
"time"
"github.com/unidoc/unioffice/spreadsheet"
)
func main() {
ss := spreadsheet.New()
sheet := ss.AddSheet()
row := sheet.AddRow()
cell := row.AddCell()
// If no formatting/styles are applied, then the 'general' format is used.
cell.SetNumber(1.234)
// You can also apply a format at the same time you are setting a number.
cell = row.AddCell()
cell.SetNumberWithStyle(0.95, spreadsheet.StandardFormatPercent)
// But that involves a few lookups, so if you're creating many, many cells
// it wil be faster to
cell = row.AddCell()
// create the style
dateStyle := ss.StyleSheet.AddCellStyle()
// set its format
dateStyle.SetNumberFormatStandard(spreadsheet.StandardFormatDate)
// and apply it to a cell
cell.SetDate(time.Now())
cell.SetStyle(dateStyle)
// It's even faster if repeatedly applying a style to apply the style index
// directly. This is probably not worth the hassle most of the time, and
// will generate the same content as calling setXWithStyle
cs := ss.StyleSheet.AddCellStyle()
cs.SetNumberFormatStandard(spreadsheet.StandardFormatTime)
idx := cs.Index()
for i := 0; i < 5; i++ {
cell = row.AddCell()
cell.SetDate(time.Now())
cell.SetStyleIndex(idx)
}
// completely custom number formats can also be used
customStyle := ss.StyleSheet.AddCellStyle()
customStyle.SetNumberFormat("$#,##0.00")
cell = row.AddCell()
cell.SetNumber(1.234)
cell.SetStyle(customStyle)
if err := ss.Validate(); err != nil {
log.Fatalf("error validating sheet: %s", err)
}
ss.SaveToFile("number-date-time-formats.xlsx")
}

View File

@ -1,54 +0,0 @@
// Copyright 2017 FoxyUtils ehf. All rights reserved.
package main
import (
"fmt"
"log"
"github.com/unidoc/unioffice/spreadsheet"
)
func main() {
ss := spreadsheet.New()
sheet := ss.AddSheet()
// Create all of our data
row := sheet.AddRow()
row.AddCell().SetString("Item")
row.AddCell().SetString("Price")
row.AddCell().SetString("# Sold")
row.AddCell().SetString("Total")
for r := 0; r < 5; r++ {
row := sheet.AddRow()
row.AddCell().SetString(fmt.Sprintf("Product %d", r+1))
row.AddCell().SetNumber(1.23 * float64(r+1))
row.AddCell().SetNumber(float64(r%3 + 1))
row.AddCell().SetFormulaRaw(fmt.Sprintf("C%d*B%d", r+2, r+2))
}
// Charts need to reside in a drawing
dwng := ss.AddDrawing()
chart, anc := dwng.AddChart(spreadsheet.AnchorTypeTwoCell)
anc.SetWidthCells(10)
lc := chart.AddPieChart()
priceSeries := lc.AddSeries()
priceSeries.SetText("Price")
// Set a category axis reference on the first series to pull the product names
priceSeries.CategoryAxis().SetLabelReference(`'Sheet 1'!A2:A6`)
priceSeries.Values().SetReference(`'Sheet 1'!B2:B6`)
priceSeries.SetExplosion(3)
// add a title and legend
title := chart.AddTitle()
title.SetText("Items Sold")
chart.AddLegend()
// and finally add the chart to the sheet
sheet.SetDrawing(dwng)
if err := ss.Validate(); err != nil {
log.Fatalf("error validating sheet: %s", err)
}
ss.SaveToFile("pie-chart.xlsx")
}

View File

@ -1,72 +0,0 @@
// Copyright 2017 FoxyUtils ehf. All rights reserved.
package main
import (
"fmt"
"log"
"github.com/unidoc/unioffice/spreadsheet"
)
func main() {
ss := spreadsheet.New()
sheet := ss.AddSheet()
// Create all of our data
row := sheet.AddRow()
row.AddCell().SetString("Item")
row.AddCell().SetString("Price")
row.AddCell().SetString("# Sold")
row.AddCell().SetString("Total")
for r := 0; r < 5; r++ {
row := sheet.AddRow()
row.AddCell().SetString(fmt.Sprintf("Product %d", r+1))
row.AddCell().SetNumber(1.23 * float64(r+1))
row.AddCell().SetNumber(float64(r%3 + 1))
row.AddCell().SetFormulaRaw(fmt.Sprintf("C%d*B%d", r+2, r+2))
}
// Charts need to reside in a drawing
dwng := ss.AddDrawing()
chart, anc := dwng.AddChart(spreadsheet.AnchorTypeTwoCell)
anc.SetWidthCells(10)
lc := chart.AddRadarChart()
priceSeries := lc.AddSeries()
priceSeries.SetText("Price")
// Set a category axis reference on the first series to pull the product names
priceSeries.CategoryAxis().SetLabelReference(`'Sheet 1'!A2:A6`)
priceSeries.Values().SetReference(`'Sheet 1'!B2:B6`)
soldSeries := lc.AddSeries()
soldSeries.SetText("Sold")
soldSeries.CategoryAxis().SetLabelReference(`'Sheet 1'!A2:A6`)
soldSeries.Values().SetReference(`'Sheet 1'!C2:C6`)
totalSeries := lc.AddSeries()
totalSeries.SetText("Total")
totalSeries.CategoryAxis().SetLabelReference(`'Sheet 1'!A2:A6`)
totalSeries.Values().SetReference(`'Sheet 1'!D2:D6`)
// the radar chart accepts two axes
ca := chart.AddCategoryAxis()
va := chart.AddValueAxis()
lc.AddAxis(ca)
lc.AddAxis(va)
ca.SetCrosses(va)
va.SetCrosses(ca)
// add a title and legend
title := chart.AddTitle()
title.SetText("Items Sold")
chart.AddLegend()
// and finally add the chart to the sheet
sheet.SetDrawing(dwng)
if err := ss.Validate(); err != nil {
log.Fatalf("error validating sheet: %s", err)
}
ss.SaveToFile("radar-chart.xlsx")
}

View File

@ -1,38 +0,0 @@
// Copyright 2017 FoxyUtils ehf. All rights reserved.
package main
// This example demonstrates flattening all formulas from an input Excel file and outputs the flattened values to a new xlsx.
import (
"log"
"github.com/unidoc/unioffice/spreadsheet"
)
func main() {
ss, err := spreadsheet.Open("original.xlsx")
if err != nil {
log.Fatalf("error opening document: %s", err)
}
sheet0, err := ss.GetSheet("Cells")
if err != nil {
log.Fatalf("error opening sheet: %s", err)
}
err = sheet0.RemoveColumn("D")
if err != nil {
log.Fatalf("error removing column: %s", err)
}
sheet1, err := ss.GetSheet("MergedCells")
if err != nil {
log.Fatalf("error opening sheet: %s", err)
}
err = sheet1.RemoveColumn("C")
if err != nil {
log.Fatalf("error removing column: %s", err)
}
ss.SaveToFile("removed.xlsx")
}

View File

@ -1,44 +0,0 @@
// Copyright 2017 FoxyUtils ehf. All rights reserved.
package main
import (
"fmt"
"log"
"github.com/unidoc/unioffice/color"
"github.com/unidoc/unioffice/spreadsheet"
)
func main() {
ss := spreadsheet.New()
// add a single sheet
sheet := ss.AddSheet()
// rows
for r := 0; r < 5; r++ {
row := sheet.AddRow()
// and cells
for c := 0; c < 5; c++ {
cell := row.AddCell()
//cell.SetString(fmt.Sprintf("row %d cell %d", r, c))
rt := cell.SetRichTextString()
run := rt.AddRun()
run.SetText(fmt.Sprintf("row %d ", r))
run.SetBold(true)
run.SetColor(color.Red)
run = rt.AddRun()
run.SetSize(16)
run.SetItalic(true)
run.SetFont("Courier")
run.SetText(fmt.Sprintf("cell %d", c))
}
}
if err := ss.Validate(); err != nil {
log.Fatalf("error validating sheet: %s", err)
}
ss.SaveToFile("rich-text.xlsx")
}

View File

@ -1,31 +0,0 @@
// Copyright 2017 FoxyUtils ehf. All rights reserved.
package main
import (
"log"
"github.com/unidoc/unioffice/spreadsheet"
)
var lorem = `Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin lobortis, lectus dictum feugiat tempus, sem neque finibus enim, sed eleifend sem nunc ac diam. Vestibulum tempus sagittis elementum`
func main() {
ss := spreadsheet.New()
// add a single sheet
sheet := ss.AddSheet()
row := sheet.AddRow()
cell := row.AddCell()
rotated := ss.StyleSheet.AddCellStyle()
rotated.SetRotation(45)
cell.SetString(lorem)
cell.SetStyle(rotated)
if err := ss.Validate(); err != nil {
log.Fatalf("error validating sheet: %s", err)
}
ss.SaveToFile("rotated.xlsx")
}

View File

@ -1,36 +0,0 @@
// Copyright 2017 FoxyUtils ehf. All rights reserved.
package main
import (
"log"
"github.com/unidoc/unioffice/spreadsheet"
)
func main() {
ss := spreadsheet.New()
sheet := ss.AddSheet()
sheet.Cell("A1").SetNumber(1)
sheet.Cell("B1").SetNumber(2)
sheet.Cell("C1").SetNumber(3)
sheet.Cell("D1").SetNumber(4)
sheet.Cell("A2").SetNumber(5)
sheet.Cell("B2").SetNumber(6)
sheet.Cell("C2").SetNumber(7)
sheet.Cell("D2").SetNumber(8)
sheet.Cell("A3").SetNumber(9)
sheet.Cell("B3").SetNumber(10)
sheet.Cell("C3").SetNumber(11)
sheet.Cell("D3").SetNumber(12)
sheet.Cell("A5").SetFormulaShared("A1+1", 2, 3)
sheet.Cell("A9").SetFormulaShared("$A1+1", 2, 3)
sheet.Cell("A13").SetFormulaShared("$A$1+1", 2, 3)
ss.RecalculateFormulas()
if err := ss.Validate(); err != nil {
log.Fatalf("error validating: %s", err)
}
ss.SaveToFile("shared-formula.xlsx")
}

View File

@ -1,31 +0,0 @@
// Copyright 2017 FoxyUtils ehf. All rights reserved.
package main
import (
"fmt"
"log"
"github.com/unidoc/unioffice/spreadsheet"
)
func main() {
ss := spreadsheet.New()
// add a single sheet
sheet := ss.AddSheet()
// rows
for r := 0; r < 5; r++ {
row := sheet.AddRow()
// and cells
for c := 0; c < 5; c++ {
cell := row.AddCell()
cell.SetString(fmt.Sprintf("row %d cell %d", r, c))
}
}
if err := ss.Validate(); err != nil {
log.Fatalf("error validating sheet: %s", err)
}
ss.SaveToFile("simple.xlsx")
}

View File

@ -1,38 +0,0 @@
// Copyright 2017 FoxyUtils ehf. All rights reserved.
package main
import (
"fmt"
"log"
"github.com/unidoc/unioffice/spreadsheet"
)
func main() {
ss := spreadsheet.New()
// add a single sheet
sheet := ss.AddSheet()
hdrRow := sheet.AddRow()
hdrRow.AddCell().SetString("Product Name")
hdrRow.AddCell().SetString("Quantity")
hdrRow.AddCell().SetString("Price")
sheet.SetAutoFilter("A1:C6")
// rows
for r := 0; r < 5; r++ {
row := sheet.AddRow()
row.AddCell().SetString(fmt.Sprintf("Product %d", r+1))
row.AddCell().SetNumber(float64(r + 2))
row.AddCell().SetNumber(float64(3*r + 1))
}
// sort column C, starting a row 2 to skip the header row
sheet.Sort("C", 2, spreadsheet.SortOrderDescending)
if err := ss.Validate(); err != nil {
log.Fatalf("error validating sheet: %s", err)
}
ss.SaveToFile("sort-filter.xlsx")
}

View File

@ -1,73 +0,0 @@
// Copyright 2017 FoxyUtils ehf. All rights reserved.
package main
import (
"fmt"
"log"
"github.com/unidoc/unioffice/spreadsheet"
)
func main() {
ss := spreadsheet.New()
sheet := ss.AddSheet()
// Create all of our data
row := sheet.AddRow()
row.AddCell().SetString("Item")
row.AddCell().SetString("Price")
row.AddCell().SetString("# Sold")
row.AddCell().SetString("Total")
for r := 0; r < 5; r++ {
row := sheet.AddRow()
row.AddCell().SetString(fmt.Sprintf("Product %d", r+1))
row.AddCell().SetNumber(1.23 * float64(r+1))
row.AddCell().SetNumber(float64(r%3 + 1))
row.AddCell().SetFormulaRaw(fmt.Sprintf("C%d*B%d", r+2, r+2))
}
// Charts need to reside in a drawing
dwng := ss.AddDrawing()
chart, anc := dwng.AddChart(spreadsheet.AnchorTypeTwoCell)
anc.SetWidthCells(10)
lc := chart.AddSurfaceChart()
priceSeries := lc.AddSeries()
priceSeries.SetText("Price")
// Set a category axis reference on the first series to pull the product names
priceSeries.CategoryAxis().SetLabelReference(`'Sheet 1'!A2:A6`)
priceSeries.Values().SetReference(`'Sheet 1'!B2:B6`)
soldSeries := lc.AddSeries()
soldSeries.SetText("Sold")
soldSeries.CategoryAxis().SetLabelReference(`'Sheet 1'!A2:A6`)
soldSeries.Values().SetReference(`'Sheet 1'!C2:C6`)
totalSeries := lc.AddSeries()
totalSeries.SetText("Total")
totalSeries.CategoryAxis().SetLabelReference(`'Sheet 1'!A2:A6`)
totalSeries.Values().SetReference(`'Sheet 1'!D2:D6`)
ca := chart.AddCategoryAxis()
va := chart.AddValueAxis()
sa := chart.AddSeriesAxis()
lc.AddAxis(ca)
lc.AddAxis(va)
lc.AddAxis(sa)
ca.SetCrosses(va)
va.SetCrosses(ca)
sa.SetCrosses(va)
// add a title and legend
title := chart.AddTitle()
title.SetText("Items Sold")
chart.AddLegend()
// and finally add the chart to the sheet
sheet.SetDrawing(dwng)
if err := ss.Validate(); err != nil {
log.Fatalf("error validating sheet: %s", err)
}
ss.SaveToFile("surface-chart.xlsx")
}

View File

@ -1,48 +0,0 @@
// Copyright 2017 FoxyUtils ehf. All rights reserved.
package main
import (
"log"
"github.com/unidoc/unioffice/spreadsheet"
)
func main() {
ss := spreadsheet.New()
sheet := ss.AddSheet()
// drop-down list that references data from another sheet
vsheet := ss.AddSheet()
vsheet.SetName("Validation Data")
vsheet.Cell("A1").SetString("A")
vsheet.Cell("A2").SetString("B")
vsheet.Cell("A3").SetString("C")
vsheet.Cell("A4").SetString("D")
sheet.Cell("B1").SetString("references sheet")
dvCombo := sheet.AddDataValidation()
dvCombo.SetRange("B2")
dvList := dvCombo.SetList()
dvList.SetRange(vsheet.RangeReference("A1:A4"))
// drop-down list with direct options specified as opposed to referenced
// from a sheet
sheet.Cell("C1").SetString("value list")
dvComboDirect := sheet.AddDataValidation()
dvComboDirect.SetRange("C2")
dvListDirect := dvComboDirect.SetList()
dvListDirect.SetValues([]string{"foo", "bar", "baz"})
// positive whole numbers
sheet.Cell("C1").SetString("positive whole numbers")
dvWhole := sheet.AddDataValidation()
dvWhole.SetRange("D2")
dvWholeCmp := dvWhole.SetComparison(spreadsheet.DVCompareTypeWholeNumber, spreadsheet.DVCompareOpGreaterEqual)
dvWholeCmp.SetValue("0")
if err := ss.Validate(); err != nil {
log.Fatalf("error validating sheet: %s", err)
}
ss.SaveToFile("validation.xlsx")
}

View File

@ -1,30 +0,0 @@
// Copyright 2017 FoxyUtils ehf. All rights reserved.
package main
import (
"log"
"github.com/unidoc/unioffice/spreadsheet"
)
var lorem = `Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin lobortis, lectus dictum feugiat tempus, sem neque finibus enim, sed eleifend sem nunc ac diam. Vestibulum tempus sagittis elementum`
func main() {
ss := spreadsheet.New()
// add a single sheet
sheet := ss.AddSheet()
row := sheet.AddRow()
cell := row.AddCell()
wrapped := ss.StyleSheet.AddCellStyle()
wrapped.SetWrapped(true)
cell.SetString(lorem)
cell.SetStyle(wrapped)
if err := ss.Validate(); err != nil {
log.Fatalf("error validating sheet: %s", err)
}
ss.SaveToFile("wrapped.xlsx")
}

15
algo/algo.go Normal file
View File

@ -0,0 +1,15 @@
//
// Copyright 2020 FoxyUtils ehf. All rights reserved.
//
// This is a commercial product and requires a license to operate.
// A trial license can be obtained at https://unidoc.io
//
// DO NOT EDIT: generated by unitwist Go source code obfuscator.
//
// Use of this source code is governed by the UniDoc End User License Agreement
// terms that can be accessed at https://unidoc.io/eula/
package algo ;import _d "strconv";func _fa (_ga byte )bool {return _ga >='0'&&_ga <='9'};func RepeatString (s string ,cnt int )string {if cnt <=0{return "";};_fd :=make ([]byte ,len (s )*cnt );_egf :=[]byte (s );for _de :=0;_de < cnt ;_de ++{copy (_fd [_de :],_egf );};return string (_fd );};
// NaturalLess compares two strings in a human manner so rId2 sorts less than rId10
func NaturalLess (lhs ,rhs string )bool {_dd ,_ad :=0,0;for _dd < len (lhs )&&_ad < len (rhs ){_ab :=lhs [_dd ];_fb :=rhs [_ad ];_f :=_fa (_ab );_b :=_fa (_fb );switch {case _f &&!_b :return true ;case !_f &&_b :return false ;case !_f &&!_b :if _ab !=_fb {return _ab < _fb ;};_dd ++;_ad ++;default:_e :=_dd +1;_bf :=_ad +1;for _e < len (lhs )&&_fa (lhs [_e ]){_e ++;};for _bf < len (rhs )&&_fa (rhs [_bf ]){_bf ++;};_bd ,_ :=_d .ParseUint (lhs [_dd :_e ],10,64);_g ,_ :=_d .ParseUint (rhs [_dd :_bf ],10,64);if _bd !=_g {return _bd < _g ;};_dd =_e ;_ad =_bf ;};};return len (lhs )< len (rhs );};

View File

@ -1,63 +0,0 @@
// Copyright 2017 FoxyUtils ehf. All rights reserved.
//
// Use of this software package and source code is governed by the terms of the
// UniDoc End User License Agreement (EULA) that is available at:
// https://unidoc.io/eula/
// A trial license code for evaluation can be obtained at https://unidoc.io.
package algo
import (
"strconv"
)
func isdigit(c byte) bool {
return c >= '0' && c <= '9'
}
// NaturalLess compares two strings in a human manner so rId2 sorts less than rId10
func NaturalLess(lhs, rhs string) bool {
lidx, ridx := 0, 0
for lidx < len(lhs) && ridx < len(rhs) {
lc := lhs[lidx]
rc := rhs[ridx]
ldigit := isdigit(lc)
rdigit := isdigit(rc)
switch {
// digits sort before characters
case ldigit && !rdigit:
return true
// characters after digits
case !ldigit && rdigit:
return false
// no digits, so compare the characters
case !ldigit && !rdigit:
if lc != rc {
return lc < rc
}
lidx++
ridx++
// both digits, so parse and compare
default:
lend := lidx + 1
rend := ridx + 1
for lend < len(lhs) && isdigit(lhs[lend]) {
lend++
}
for rend < len(rhs) && isdigit(rhs[rend]) {
rend++
}
lv, _ := strconv.ParseUint(lhs[lidx:lend], 10, 64)
rv, _ := strconv.ParseUint(rhs[lidx:rend], 10, 64)
if lv != rv {
return lv < rv
}
// digits are equal, so keep looking
lidx = lend
ridx = rend
}
}
// fall back to comparing length
return len(lhs) < len(rhs)
}

View File

@ -1,41 +0,0 @@
// Copyright 2017 FoxyUtils ehf. All rights reserved.
//
// Use of this software package and source code is governed by the terms of the
// UniDoc End User License Agreement (EULA) that is available at:
// https://unidoc.io/eula/
// A trial license code for evaluation can be obtained at https://unidoc.io.
package algo_test
import (
"testing"
"github.com/unidoc/unioffice/algo"
)
func TestSort(t *testing.T) {
tests := []struct {
a, b string
}{
{"rId1", "rId2"},
{"rId1", "rId10"},
{"rId2", "rId10"},
{"rId5", "rId10"},
{"rId5", "rId15"},
{"rId5", "rId51"},
{"rId1a", "rId1b"},
}
for _, tc := range tests {
if !algo.NaturalLess(tc.a, tc.b) {
t.Errorf("bad sort, expected %s < %s", tc.a, tc.b)
} else {
// no need to check if it failed the first time
if algo.NaturalLess(tc.b, tc.a) {
t.Errorf("bad sort, expected %s > %s", tc.b, tc.a)
}
}
}
}

View File

@ -1,13 +0,0 @@
package algo
func RepeatString(s string, cnt int) string {
if cnt <= 0 {
return ""
}
buf := make([]byte, len(s)*cnt)
sb := []byte(s)
for i := 0; i < cnt; i++ {
copy(buf[i:], sb)
}
return string(buf)
}

View File

@ -1,9 +0,0 @@
#!/bin/bash
go get -u github.com/go-ole/go-ole/oleutil
:> build_errors
find _examples/ -maxdepth 2 -mindepth 2 -exec sh -c "cd {}; echo building {}; go build -i main.go" 2>>build_errors \;
if [[ $(wc -l build_errors | awk '{print $1}') == "0" ]]; then
exit 0
fi
exit 1

Some files were not shown because too many files have changed in this diff Show More