作者 陈志颖

chore:添加vendor目录

要显示太多修改。

为保证性能只显示 12 of 12+ 个文件。

~$*.xlsx
test/Test*.xlsx
*.out
*.test
.idea
... ...
language: go
install:
- go get -d -t -v ./... && go build -v ./...
go:
- 1.11.x
- 1.12.x
- 1.13.x
- 1.14.x
- 1.15.x
os:
- linux
- osx
env:
jobs:
- GOARCH=amd64
- GOARCH=386
script:
- env GO111MODULE=on go vet ./...
- env GO111MODULE=on go test -v -race ./... -coverprofile=coverage.txt -covermode=atomic
after_success:
- bash <(curl -s https://codecov.io/bash)
... ...
# Contributor Covenant Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.
## Scope
This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at [xuri.me](https://xuri.me). The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0, available at [https://www.contributor-covenant.org/version/2/0/code_of_conduct][version]
[homepage]: https://www.contributor-covenant.org
[version]: https://www.contributor-covenant.org/version/2/0/code_of_conduct
... ...
# Contributing to excelize
Want to hack on excelize? Awesome! This page contains information about reporting issues as well as some tips and
guidelines useful to experienced open source contributors. Finally, make sure
you read our [community guidelines](#community-guidelines) before you
start participating.
## Topics
* [Reporting Security Issues](#reporting-security-issues)
* [Design and Cleanup Proposals](#design-and-cleanup-proposals)
* [Reporting Issues](#reporting-other-issues)
* [Quick Contribution Tips and Guidelines](#quick-contribution-tips-and-guidelines)
* [Community Guidelines](#community-guidelines)
## Reporting security issues
The excelize maintainers take security seriously. If you discover a security
issue, please bring it to their attention right away!
Please **DO NOT** file a public issue, instead send your report privately to
[xuri.me](https://xuri.me).
Security reports are greatly appreciated and we will publicly thank you for it.
We currently do not offer a paid security bounty program, but are not
ruling it out in the future.
## Reporting other issues
A great way to contribute to the project is to send a detailed report when you
encounter an issue. We always appreciate a well-written, thorough bug report,
and will thank you for it!
Check that [our issue database](https://github.com/360EntSecGroup-Skylar/excelize/issues)
doesn't already include that problem or suggestion before submitting an issue.
If you find a match, you can use the "subscribe" button to get notified on
updates. Do *not* leave random "+1" or "I have this too" comments, as they
only clutter the discussion, and don't help resolving it. However, if you
have ways to reproduce the issue or have additional information that may help
resolving the issue, please leave a comment.
When reporting issues, always include the output of `go env`.
Also include the steps required to reproduce the problem if possible and
applicable. This information will help us review and fix your issue faster.
When sending lengthy log-files, consider posting them as a gist [https://gist.github.com](https://gist.github.com).
Don't forget to remove sensitive data from your logfiles before posting (you can
replace those parts with "REDACTED").
## Quick contribution tips and guidelines
This section gives the experienced contributor some tips and guidelines.
### Pull requests are always welcome
Not sure if that typo is worth a pull request? Found a bug and know how to fix
it? Do it! We will appreciate it. Any significant improvement should be
documented as [a GitHub issue](https://github.com/360EntSecGroup-Skylar/excelize/issues) before
anybody starts working on it.
We are always thrilled to receive pull requests. We do our best to process them
quickly. If your pull request is not accepted on the first try,
don't get discouraged!
### Design and cleanup proposals
You can propose new designs for existing excelize features. You can also design
entirely new features. We really appreciate contributors who want to refactor or
otherwise cleanup our project.
We try hard to keep excelize lean and focused. Excelize can't do everything for
everybody. This means that we might decide against incorporating a new feature.
However, there might be a way to implement that feature *on top of* excelize.
### Conventions
Fork the repository and make changes on your fork in a feature branch:
* If it's a bug fix branch, name it XXXX-something where XXXX is the number of
the issue.
* If it's a feature branch, create an enhancement issue to announce
your intentions, and name it XXXX-something where XXXX is the number of the
issue.
Submit unit tests for your changes. Go has a great test framework built in; use
it! Take a look at existing tests for inspiration. Run the full test on your branch before
submitting a pull request.
Update the documentation when creating or modifying features. Test your
documentation changes for clarity, concision, and correctness, as well as a
clean documentation build.
Write clean code. Universally formatted code promotes ease of writing, reading,
and maintenance. Always run `gofmt -s -w file.go` on each changed file before
committing your changes. Most editors have plug-ins that do this automatically.
Pull request descriptions should be as clear as possible and include a reference
to all the issues that they address.
### Successful Changes
Before contributing large or high impact changes, make the effort to coordinate
with the maintainers of the project before submitting a pull request. This
prevents you from doing extra work that may or may not be merged.
Large PRs that are just submitted without any prior communication are unlikely
to be successful.
While pull requests are the methodology for submitting changes to code, changes
are much more likely to be accepted if they are accompanied by additional
engineering work. While we don't define this explicitly, most of these goals
are accomplished through communication of the design goals and subsequent
solutions. Often times, it helps to first state the problem before presenting
solutions.
Typically, the best methods of accomplishing this are to submit an issue,
stating the problem. This issue can include a problem statement and a
checklist with requirements. If solutions are proposed, alternatives should be
listed and eliminated. Even if the criteria for elimination of a solution is
frivolous, say so.
Larger changes typically work best with design documents. These are focused on
providing context to the design at the time the feature was conceived and can
inform future documentation contributions.
### Commit Messages
Commit messages must start with a capitalized and short summary
written in the imperative, followed by an optional, more detailed explanatory
text which is separated from the summary by an empty line.
Commit messages should follow best practices, including explaining the context
of the problem and how it was solved, including in caveats or follow up changes
required. They should tell the story of the change and provide readers
understanding of what led to it.
In practice, the best approach to maintaining a nice commit message is to
leverage a `git add -p` and `git commit --amend` to formulate a solid
changeset. This allows one to piece together a change, as information becomes
available.
If you squash a series of commits, don't just submit that. Re-write the commit
message, as if the series of commits was a single stroke of brilliance.
That said, there is no requirement to have a single commit for a PR, as long as
each commit tells the story. For example, if there is a feature that requires a
package, it might make sense to have the package in a separate commit then have
a subsequent commit that uses it.
Remember, you're telling part of the story with the commit message. Don't make
your chapter weird.
### Review
Code review comments may be added to your pull request. Discuss, then make the
suggested modifications and push additional commits to your feature branch. Post
a comment after pushing. New commits show up in the pull request automatically,
but the reviewers are notified only when you comment.
Pull requests must be cleanly rebased on top of master without multiple branches
mixed into the PR.
**Git tip**: If your PR no longer merges cleanly, use `rebase master` in your
feature branch to update your pull request rather than `merge master`.
Before you make a pull request, squash your commits into logical units of work
using `git rebase -i` and `git push -f`. A logical unit of work is a consistent
set of patches that should be reviewed together: for example, upgrading the
version of a vendored dependency and taking advantage of its now available new
feature constitute two separate units of work. Implementing a new function and
calling it in another file constitute a single logical unit of work. The very
high majority of submissions should have a single commit, so if in doubt: squash
down to one.
After every commit, make sure the test passes. Include documentation
changes in the same pull request so that a revert would remove all traces of
the feature or fix.
Include an issue reference like `Closes #XXXX` or `Fixes #XXXX` in commits that
close an issue. Including references automatically closes the issue on a merge.
Please see the [Coding Style](#coding-style) for further guidelines.
### Merge approval
The excelize maintainers use LGTM (Looks Good To Me) in comments on the code review to
indicate acceptance.
### Sign your work
The sign-off is a simple line at the end of the explanation for the patch. Your
signature certifies that you wrote the patch or otherwise have the right to pass
it on as an open-source patch. The rules are pretty simple: if you can certify
the below (from [developercertificate.org](http://developercertificate.org/)):
```text
Developer Certificate of Origin
Version 1.1
Copyright (C) 2004, 2006 The Linux Foundation and its contributors.
1 Letterman Drive
Suite D4700
San Francisco, CA, 94129
Everyone is permitted to copy and distribute verbatim copies of this
license document, but changing it is not allowed.
Developer's Certificate of Origin 1.1
By making a contribution to this project, I certify that:
(a) The contribution was created in whole or in part by me and I
have the right to submit it under the open source license
indicated in the file; or
(b) The contribution is based upon previous work that, to the best
of my knowledge, is covered under an appropriate open source
license and I have the right under that license to submit that
work with modifications, whether created in whole or in part
by me, under the same open source license (unless I am
permitted to submit under a different license), as indicated
in the file; or
(c) The contribution was provided directly to me by some other
person who certified (a), (b) or (c) and I have not modified
it.
(d) I understand and agree that this project and the contribution
are public and that a record of the contribution (including all
personal information I submit with it, including my sign-off) is
maintained indefinitely and may be redistributed consistent with
this project or the open source license(s) involved.
```
Then you just add a line to every git commit message:
```text
Signed-off-by: Ri Xu https://xuri.me
```
Use your real name (sorry, no pseudonyms or anonymous contributions.)
If you set your `user.name` and `user.email` git configs, you can sign your
commit automatically with `git commit -s`.
### How can I become a maintainer
First, all maintainers have 3 things
* They share responsibility in the project's success.
* They have made a long-term, recurring time investment to improve the project.
* They spend that time doing whatever needs to be done, not necessarily what
is the most interesting or fun.
Maintainers are often under-appreciated, because their work is harder to appreciate.
It's easy to appreciate a really cool and technically advanced feature. It's harder
to appreciate the absence of bugs, the slow but steady improvement in stability,
or the reliability of a release process. But those things distinguish a good
project from a great one.
Don't forget: being a maintainer is a time investment. Make sure you
will have time to make yourself available. You don't have to be a
maintainer to make a difference on the project!
If you want to become a meintainer, contact [xuri.me](https://xuri.me) and given a introduction of you.
## Community guidelines
We want to keep the community awesome, growing and collaborative. We need
your help to keep it that way. To help with this we've come up with some general
guidelines for the community as a whole:
* Be nice: Be courteous, respectful and polite to fellow community members:
no regional, racial, gender, or other abuse will be tolerated. We like
nice people way better than mean ones!
* Encourage diversity and participation: Make everyone in our community feel
welcome, regardless of their background and the extent of their
contributions, and do everything possible to encourage participation in
our community.
* Keep it legal: Basically, don't get us in trouble. Share only content that
you own, do not share private or sensitive information, and don't break
the law.
* Stay on topic: Make sure that you are posting to the correct channel and
avoid off-topic discussions. Remember when you update an issue or respond
to an email you are potentially sending to a large number of people. Please
consider this before you update. Also remember that nobody likes spam.
* Don't send email to the maintainers: There's no need to send email to the
maintainers to ask them to investigate an issue or to take a look at a
pull request. Instead of sending an email, GitHub mentions should be
used to ping maintainers to review a pull request, a proposal or an
issue.
### Guideline violations — 3 strikes method
The point of this section is not to find opportunities to punish people, but we
do need a fair way to deal with people who are making our community suck.
1. First occurrence: We'll give you a friendly, but public reminder that the
behavior is inappropriate according to our guidelines.
2. Second occurrence: We will send you a private message with a warning that
any additional violations will result in removal from the community.
3. Third occurrence: Depending on the violation, we may need to delete or ban
your account.
**Notes:**
* Obvious spammers are banned on first occurrence. If we don't do this, we'll
have spam all over the place.
* Violations are forgiven after 6 months of good behavior, and we won't hold a
grudge.
* People who commit minor infractions will get some education, rather than
hammering them in the 3 strikes process.
* The rules apply equally to everyone in the community, no matter how much
you've contributed.
* Extreme violations of a threatening, abusive, destructive or illegal nature
will be addressed immediately and are not subject to 3 strikes or forgiveness.
* Contact [xuri.me](https://xuri.me) to report abuse or appeal violations. In the case of
appeals, we know that mistakes happen, and we'll work with you to come up with a
fair solution if there has been a misunderstanding.
## Coding Style
Unless explicitly stated, we follow all coding guidelines from the Go
community. While some of these standards may seem arbitrary, they somehow seem
to result in a solid, consistent codebase.
It is possible that the code base does not currently comply with these
guidelines. We are not looking for a massive PR that fixes this, since that
goes against the spirit of the guidelines. All new contributions should make a
best effort to clean up and make the code base better than they left it.
Obviously, apply your best judgement. Remember, the goal here is to make the
code base easier for humans to navigate and understand. Always keep that in
mind when nudging others to comply.
The rules:
1. All code should be formatted with `gofmt -s`.
2. All code should pass the default levels of
[`golint`](https://github.com/golang/lint).
3. All code should follow the guidelines covered in [Effective
Go](http://golang.org/doc/effective_go.html) and [Go Code Review
Comments](https://github.com/golang/go/wiki/CodeReviewComments).
4. Comment the code. Tell us the why, the history and the context.
5. Document _all_ declarations and methods, even private ones. Declare
expectations, caveats and anything else that may be important. If a type
gets exported, having the comments already there will ensure it's ready.
6. Variable name length should be proportional to its context and no longer.
`noCommaALongVariableNameLikeThisIsNotMoreClearWhenASimpleCommentWouldDo`.
In practice, short methods will have short variable names and globals will
have longer names.
7. No underscores in package names. If you need a compound name, step back,
and re-examine why you need a compound name. If you still think you need a
compound name, lose the underscore.
8. No utils or helpers packages. If a function is not general enough to
warrant its own package, it has not been written generally enough to be a
part of a util package. Just leave it unexported and well-documented.
9. All tests should run with `go test` and outside tooling should not be
required. No, we don't need another unit testing framework. Assertion
packages are acceptable if they provide _real_ incremental value.
10. Even though we call these "rules" above, they are actually just
guidelines. Since you've read all the rules, you now know that.
If you are having trouble getting into the mood of idiomatic Go, we recommend
reading through [Effective Go](https://golang.org/doc/effective_go.html). The
[Go Blog](https://blog.golang.org) is also a great resource. Drinking the
kool-aid is a lot easier than going thirsty.
## Code Review Comments and Effective Go Guidelines
[CodeLingo](https://codelingo.io) automatically checks every pull request against the following guidelines from [Effective Go](https://golang.org/doc/effective_go.html) and [Code Review Comments](https://github.com/golang/go/wiki/CodeReviewComments).
### Package Comment
Every package should have a package comment, a block comment preceding the package clause.
For multi-file packages, the package comment only needs to be present in one file, and any one will do.
The package comment should introduce the package and provide information relevant to the package as a
whole. It will appear first on the godoc page and should set up the detailed documentation that follows.
### Single Method Interface Name
By convention, one-method interfaces are named by the method name plus an -er suffix
or similar modification to construct an agent noun: Reader, Writer, Formatter, CloseNotifier etc.
There are a number of such names and it's productive to honor them and the function names they capture.
Read, Write, Close, Flush, String and so on have canonical signatures and meanings. To avoid confusion,
don't give your method one of those names unless it has the same signature and meaning. Conversely,
if your type implements a method with the same meaning as a method on a well-known type, give it the
same name and signature; call your string-converter method String not ToString.
### Avoid Annotations in Comments
Comments do not need extra formatting such as banners of stars. The generated output
may not even be presented in a fixed-width font, so don't depend on spacing for alignment—godoc,
like gofmt, takes care of that. The comments are uninterpreted plain text, so HTML and other
annotations such as _this_ will reproduce verbatim and should not be used. One adjustment godoc
does do is to display indented text in a fixed-width font, suitable for program snippets.
The package comment for the fmt package uses this to good effect.
### Comment First Word as Subject
Doc comments work best as complete sentences, which allow a wide variety of automated presentations.
The first sentence should be a one-sentence summary that starts with the name being declared.
### Good Package Name
It's helpful if everyone using the package can use the same name
to refer to its contents, which implies that the package name should
be good: short, concise, evocative. By convention, packages are
given lower case, single-word names; there should be no need for
underscores or mixedCaps. Err on the side of brevity, since everyone
using your package will be typing that name. And don't worry about
collisions a priori. The package name is only the default name for
imports; it need not be unique across all source code, and in the
rare case of a collision the importing package can choose a different
name to use locally. In any case, confusion is rare because the file
name in the import determines just which package is being used.
### Avoid Renaming Imports
Avoid renaming imports except to avoid a name collision; good package names
should not require renaming. In the event of collision, prefer to rename the
most local or project-specific import.
### Context as First Argument
Values of the context.Context type carry security credentials, tracing information,
deadlines, and cancellation signals across API and process boundaries. Go programs
pass Contexts explicitly along the entire function call chain from incoming RPCs
and HTTP requests to outgoing requests.
Most functions that use a Context should accept it as their first parameter.
### Do Not Discard Errors
Do not discard errors using _ variables. If a function returns an error,
check it to make sure the function succeeded. Handle the error, return it, or,
in truly exceptional situations, panic.
### Go Error Format
Error strings should not be capitalized (unless beginning with proper nouns
or acronyms) or end with punctuation, since they are usually printed following
other context. That is, use fmt.Errorf("something bad") not fmt.Errorf("Something bad"),
so that log.Printf("Reading %s: %v", filename, err) formats without a spurious
capital letter mid-message. This does not apply to logging, which is implicitly
line-oriented and not combined inside other messages.
### Use Crypto Rand
Do not use package math/rand to generate keys, even
throwaway ones. Unseeded, the generator is completely predictable.
Seeded with time.Nanoseconds(), there are just a few bits of entropy.
Instead, use crypto/rand's Reader, and if you need text, print to
hexadecimal or base64.
... ...
BSD 3-Clause License
Copyright (c) 2016-2020 The excelize Authors.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
\ No newline at end of file
... ...
# PR Details
<!--- Provide a general summary of your changes in the Title above -->
## Description
<!--- Describe your changes in detail -->
## Related Issue
<!--- This project only accepts pull requests related to open issues -->
<!--- If suggesting a new feature or change, please discuss it in an issue first -->
<!--- If fixing a bug, there should be an issue describing it with steps to reproduce -->
<!--- Please link to the issue here: -->
## Motivation and Context
<!--- Why is this change required? What problem does it solve? -->
## How Has This Been Tested
<!--- Please describe in detail how you tested your changes. -->
<!--- Include details of your testing environment, and the tests you ran to -->
<!--- see how your change affects other areas of the code, etc. -->
## Types of changes
<!--- What types of changes does your code introduce? Put an `x` in all the boxes that apply: -->
- [ ] Docs change / refactoring / dependency upgrade
- [ ] Bug fix (non-breaking change which fixes an issue)
- [ ] New feature (non-breaking change which adds functionality)
- [ ] Breaking change (fix or feature that would cause existing functionality to change)
## Checklist
<!--- Go over all the following points, and put an `x` in all the boxes that apply. -->
<!--- If you're unsure about any of these, don't hesitate to ask. We're here to help! -->
- [ ] My code follows the code style of this project.
- [ ] My change requires a change to the documentation.
- [ ] I have updated the documentation accordingly.
- [ ] I have read the **CONTRIBUTING** document.
- [ ] I have added tests to cover my changes.
- [ ] All new and existing tests passed.
... ...
<p align="center"><img width="650" src="./excelize.svg" alt="Excelize logo"></p>
<p align="center">
<a href="https://travis-ci.org/360EntSecGroup-Skylar/excelize"><img src="https://travis-ci.org/360EntSecGroup-Skylar/excelize.svg?branch=master" alt="Build Status"></a>
<a href="https://codecov.io/gh/360EntSecGroup-Skylar/excelize"><img src="https://codecov.io/gh/360EntSecGroup-Skylar/excelize/branch/master/graph/badge.svg" alt="Code Coverage"></a>
<a href="https://goreportcard.com/report/github.com/360EntSecGroup-Skylar/excelize"><img src="https://goreportcard.com/badge/github.com/360EntSecGroup-Skylar/excelize" alt="Go Report Card"></a>
<a href="https://pkg.go.dev/github.com/360EntSecGroup-Skylar/excelize/v2?tab=doc"><img src="https://img.shields.io/badge/go.dev-reference-007d9c?logo=go&logoColor=white" alt="go.dev"></a>
<a href="https://opensource.org/licenses/BSD-3-Clause"><img src="https://img.shields.io/badge/license-bsd-orange.svg" alt="Licenses"></a>
<a href="https://www.paypal.me/xuri"><img src="https://img.shields.io/badge/Donate-PayPal-green.svg" alt="Donate"></a>
</p>
# Excelize
## Introduction
Excelize is a library written in pure Go providing a set of functions that allow you to write to and read from XLSX / XLSM / XLTM files. Supports reading and writing spreadsheet documents generated by Microsoft Excel&trade; 2007 and later. Supports complex components by high compatibility, and provided streaming API for generating or reading data from a worksheet with huge amounts of data. This library needs Go version 1.10 or later. The full API docs can be seen using go's built-in documentation tool, or online at [go.dev](https://pkg.go.dev/github.com/360EntSecGroup-Skylar/excelize/v2?tab=doc) and [docs reference](https://xuri.me/excelize/).
## Basic Usage
### Installation
```bash
go get github.com/360EntSecGroup-Skylar/excelize
```
- If your package management with [Go Modules](https://blog.golang.org/using-go-modules), please install with following command.
```bash
go get github.com/360EntSecGroup-Skylar/excelize/v2
```
### Create spreadsheet
Here is a minimal example usage that will create spreadsheet file.
```go
package main
import (
"fmt"
"github.com/360EntSecGroup-Skylar/excelize"
)
func main() {
f := excelize.NewFile()
// Create a new sheet.
index := f.NewSheet("Sheet2")
// Set value of a cell.
f.SetCellValue("Sheet2", "A2", "Hello world.")
f.SetCellValue("Sheet1", "B2", 100)
// Set active sheet of the workbook.
f.SetActiveSheet(index)
// Save xlsx file by the given path.
if err := f.SaveAs("Book1.xlsx"); err != nil {
fmt.Println(err)
}
}
```
### Reading spreadsheet
The following constitutes the bare to read a spreadsheet document.
```go
package main
import (
"fmt"
"github.com/360EntSecGroup-Skylar/excelize"
)
func main() {
f, err := excelize.OpenFile("Book1.xlsx")
if err != nil {
fmt.Println(err)
return
}
// Get value from cell by given worksheet name and axis.
cell, err := f.GetCellValue("Sheet1", "B2")
if err != nil {
fmt.Println(err)
return
}
fmt.Println(cell)
// Get all the rows in the Sheet1.
rows, err := f.GetRows("Sheet1")
for _, row := range rows {
for _, colCell := range row {
fmt.Print(colCell, "\t")
}
fmt.Println()
}
}
```
### Add chart to spreadsheet file
With Excelize chart generation and management is as easy as a few lines of code. You can build charts based off data in your worksheet or generate charts without any data in your worksheet at all.
<p align="center"><img width="650" src="./test/images/chart.png" alt="Excelize"></p>
```go
package main
import (
"fmt"
"github.com/360EntSecGroup-Skylar/excelize"
)
func main() {
categories := map[string]string{"A2": "Small", "A3": "Normal", "A4": "Large", "B1": "Apple", "C1": "Orange", "D1": "Pear"}
values := map[string]int{"B2": 2, "C2": 3, "D2": 3, "B3": 5, "C3": 2, "D3": 4, "B4": 6, "C4": 7, "D4": 8}
f := excelize.NewFile()
for k, v := range categories {
f.SetCellValue("Sheet1", k, v)
}
for k, v := range values {
f.SetCellValue("Sheet1", k, v)
}
if err := f.AddChart("Sheet1", "E1", `{"type":"col3DClustered","series":[{"name":"Sheet1!$A$2","categories":"Sheet1!$B$1:$D$1","values":"Sheet1!$B$2:$D$2"},{"name":"Sheet1!$A$3","categories":"Sheet1!$B$1:$D$1","values":"Sheet1!$B$3:$D$3"},{"name":"Sheet1!$A$4","categories":"Sheet1!$B$1:$D$1","values":"Sheet1!$B$4:$D$4"}],"title":{"name":"Fruit 3D Clustered Column Chart"}}`); err != nil {
fmt.Println(err)
return
}
// Save xlsx file by the given path.
if err := f.SaveAs("Book1.xlsx"); err != nil {
fmt.Println(err)
}
}
```
### Add picture to spreadsheet file
```go
package main
import (
"fmt"
_ "image/gif"
_ "image/jpeg"
_ "image/png"
"github.com/360EntSecGroup-Skylar/excelize"
)
func main() {
f, err := excelize.OpenFile("Book1.xlsx")
if err != nil {
fmt.Println(err)
return
}
// Insert a picture.
if err := f.AddPicture("Sheet1", "A2", "image.png", ""); err != nil {
fmt.Println(err)
}
// Insert a picture to worksheet with scaling.
if err := f.AddPicture("Sheet1", "D2", "image.jpg", `{"x_scale": 0.5, "y_scale": 0.5}`); err != nil {
fmt.Println(err)
}
// Insert a picture offset in the cell with printing support.
if err := f.AddPicture("Sheet1", "H2", "image.gif", `{"x_offset": 15, "y_offset": 10, "print_obj": true, "lock_aspect_ratio": false, "locked": false}`); err != nil {
fmt.Println(err)
}
// Save the xlsx file with the origin path.
if err = f.Save(); err != nil {
fmt.Println(err)
}
}
```
## Contributing
Contributions are welcome! Open a pull request to fix a bug, or open an issue to discuss a new feature or change. XML is compliant with [part 1 of the 5th edition of the ECMA-376 Standard for Office Open XML](http://www.ecma-international.org/publications/standards/Ecma-376.htm).
## Licenses
This program is under the terms of the BSD 3-Clause License. See [https://opensource.org/licenses/BSD-3-Clause](https://opensource.org/licenses/BSD-3-Clause).
The Excel logo is a trademark of [Microsoft Corporation](https://aka.ms/trademarks-usage). This artwork is an adaptation.
gopher.{ai,svg,png} was created by [Takuya Ueda](https://twitter.com/tenntenn). Licensed under the [Creative Commons 3.0 Attributions license](http://creativecommons.org/licenses/by/3.0/).
... ...
<p align="center"><img width="650" src="./excelize.svg" alt="Excelize logo"></p>
<p align="center">
<a href="https://travis-ci.org/360EntSecGroup-Skylar/excelize"><img src="https://travis-ci.org/360EntSecGroup-Skylar/excelize.svg?branch=master" alt="Build Status"></a>
<a href="https://codecov.io/gh/360EntSecGroup-Skylar/excelize"><img src="https://codecov.io/gh/360EntSecGroup-Skylar/excelize/branch/master/graph/badge.svg" alt="Code Coverage"></a>
<a href="https://goreportcard.com/report/github.com/360EntSecGroup-Skylar/excelize"><img src="https://goreportcard.com/badge/github.com/360EntSecGroup-Skylar/excelize" alt="Go Report Card"></a>
<a href="https://pkg.go.dev/github.com/360EntSecGroup-Skylar/excelize/v2?tab=doc"><img src="https://img.shields.io/badge/go.dev-reference-007d9c?logo=go&logoColor=white" alt="go.dev"></a>
<a href="https://opensource.org/licenses/BSD-3-Clause"><img src="https://img.shields.io/badge/license-bsd-orange.svg" alt="Licenses"></a>
<a href="https://www.paypal.me/xuri"><img src="https://img.shields.io/badge/Donate-PayPal-green.svg" alt="Donate"></a>
</p>
# Excelize
## 简介
Excelize 是 Go 语言编写的用于操作 Office Excel 文档基础库,基于 ECMA-376,ISO/IEC 29500 国际标准。可以使用它来读取、写入由 Microsoft Excel&trade; 2007 及以上版本创建的电子表格文档。支持 XLSX / XLSM / XLTM 等多种文档格式,高度兼容带有样式、图片(表)、透视表、切片器等复杂组件的文档,并提供流式读写 API,用于处理包含大规模数据的工作簿。可应用于各类报表平台、云计算、边缘计算等系统。使用本类库要求使用的 Go 语言为 1.10 或更高版本,完整的 API 使用文档请访问 [go.dev](https://pkg.go.dev/github.com/360EntSecGroup-Skylar/excelize/v2?tab=doc) 或查看 [参考文档](https://xuri.me/excelize/)
## 快速上手
### 安装
```bash
go get github.com/360EntSecGroup-Skylar/excelize
```
- 如果您使用 [Go Modules](https://blog.golang.org/using-go-modules) 管理软件包,请使用下面的命令来安装最新版本。
```bash
go get github.com/360EntSecGroup-Skylar/excelize/v2
```
### 创建 Excel 文档
下面是一个创建 Excel 文档的简单例子:
```go
package main
import (
"fmt"
"github.com/360EntSecGroup-Skylar/excelize"
)
func main() {
f := excelize.NewFile()
// 创建一个工作表
index := f.NewSheet("Sheet2")
// 设置单元格的值
f.SetCellValue("Sheet2", "A2", "Hello world.")
f.SetCellValue("Sheet1", "B2", 100)
// 设置工作簿的默认工作表
f.SetActiveSheet(index)
// 根据指定路径保存文件
if err := f.SaveAs("Book1.xlsx"); err != nil {
fmt.Println(err)
}
}
```
### 读取 Excel 文档
下面是读取 Excel 文档的例子:
```go
package main
import (
"fmt"
"github.com/360EntSecGroup-Skylar/excelize"
)
func main() {
f, err := excelize.OpenFile("Book1.xlsx")
if err != nil {
fmt.Println(err)
return
}
// 获取工作表中指定单元格的值
cell, err := f.GetCellValue("Sheet1", "B2")
if err != nil {
fmt.Println(err)
return
}
fmt.Println(cell)
// 获取 Sheet1 上所有单元格
rows, err := f.GetRows("Sheet1")
for _, row := range rows {
for _, colCell := range row {
fmt.Print(colCell, "\t")
}
fmt.Println()
}
}
```
### 在 Excel 文档中创建图表
使用 Excelize 生成图表十分简单,仅需几行代码。您可以根据工作表中的已有数据构建图表,或向工作表中添加数据并创建图表。
<p align="center"><img width="650" src="./test/images/chart.png" alt="Excelize"></p>
```go
package main
import (
"fmt"
"github.com/360EntSecGroup-Skylar/excelize"
)
func main() {
categories := map[string]string{"A2": "Small", "A3": "Normal", "A4": "Large", "B1": "Apple", "C1": "Orange", "D1": "Pear"}
values := map[string]int{"B2": 2, "C2": 3, "D2": 3, "B3": 5, "C3": 2, "D3": 4, "B4": 6, "C4": 7, "D4": 8}
f := excelize.NewFile()
for k, v := range categories {
f.SetCellValue("Sheet1", k, v)
}
for k, v := range values {
f.SetCellValue("Sheet1", k, v)
}
if err := f.AddChart("Sheet1", "E1", `{"type":"col3DClustered","series":[{"name":"Sheet1!$A$2","categories":"Sheet1!$B$1:$D$1","values":"Sheet1!$B$2:$D$2"},{"name":"Sheet1!$A$3","categories":"Sheet1!$B$1:$D$1","values":"Sheet1!$B$3:$D$3"},{"name":"Sheet1!$A$4","categories":"Sheet1!$B$1:$D$1","values":"Sheet1!$B$4:$D$4"}],"title":{"name":"Fruit 3D Clustered Column Chart"}}`); err != nil {
fmt.Println(err)
return
}
// 根据指定路径保存文件
if err := f.SaveAs("Book1.xlsx"); err != nil {
fmt.Println(err)
}
}
```
### 向 Excel 文档中插入图片
```go
package main
import (
"fmt"
_ "image/gif"
_ "image/jpeg"
_ "image/png"
"github.com/360EntSecGroup-Skylar/excelize"
)
func main() {
f, err := excelize.OpenFile("Book1.xlsx")
if err != nil {
fmt.Println(err)
return
}
// 插入图片
if err := f.AddPicture("Sheet1", "A2", "image.png", ""); err != nil {
fmt.Println(err)
}
// 在工作表中插入图片,并设置图片的缩放比例
if err := f.AddPicture("Sheet1", "D2", "image.jpg", `{"x_scale": 0.5, "y_scale": 0.5}`); err != nil {
fmt.Println(err)
}
// 在工作表中插入图片,并设置图片的打印属性
if err := f.AddPicture("Sheet1", "H2", "image.gif", `{"x_offset": 15, "y_offset": 10, "print_obj": true, "lock_aspect_ratio": false, "locked": false}`); err != nil {
fmt.Println(err)
}
// 保存文件
if err = f.Save(); err != nil {
fmt.Println(err)
}
}
```
## 社区合作
欢迎您为此项目贡献代码,提出建议或问题、修复 Bug 以及参与讨论对新功能的想法。 XML 符合标准: [part 1 of the 5th edition of the ECMA-376 Standard for Office Open XML](http://www.ecma-international.org/publications/standards/Ecma-376.htm)
## 开源许可
本项目遵循 BSD 3-Clause 开源许可协议,访问 [https://opensource.org/licenses/BSD-3-Clause](https://opensource.org/licenses/BSD-3-Clause) 查看许可协议文件。
Excel 徽标是 [Microsoft Corporation](https://aka.ms/trademarks-usage) 的商标,项目的图片是一种改编。
gopher.{ai,svg,png} 由 [Takuya Ueda](https://twitter.com/tenntenn) 创作,遵循 [Creative Commons 3.0 Attributions license](http://creativecommons.org/licenses/by/3.0/) 创作共用授权条款。
... ...
# Security Policy
## Supported Versions
We will dive into any security-related issue as long as your Excelize version is still supported by us. When reporting an issue, include as much information as possible, but no need to fill fancy forms or answer tedious questions. Just tell us what you found, how to reproduce it, and any concerns you have about it. We will respond as soon as possible and follow up with any missing information.
## Reporting a Vulnerability
Please e-mail us directly at `xuri.me@gmail.com` or use the security issue template on GitHub. In general, public disclosure is made after the issue has been fully identified and a patch is ready to be released. A security issue gets the highest priority assigned and a reply regarding the vulnerability is given within a typical 24 hours. Thank you!
... ...
// Copyright 2016 - 2020 The excelize Authors. All rights reserved. Use of
// this source code is governed by a BSD-style license that can be found in
// the LICENSE file.
//
// Package excelize providing a set of functions that allow you to write to
// and read from XLSX / XLSM / XLTM files. Supports reading and writing
// spreadsheet documents generated by Microsoft Exce™ 2007 and later. Supports
// complex components by high compatibility, and provided streaming API for
// generating or reading data from a worksheet with huge amounts of data. This
// library needs Go version 1.10 or later.
package excelize
import (
"errors"
"strings"
)
type adjustDirection bool
const (
columns adjustDirection = false
rows adjustDirection = true
)
// adjustHelper provides a function to adjust rows and columns dimensions,
// hyperlinks, merged cells and auto filter when inserting or deleting rows or
// columns.
//
// sheet: Worksheet name that we're editing
// column: Index number of the column we're inserting/deleting before
// row: Index number of the row we're inserting/deleting before
// offset: Number of rows/column to insert/delete negative values indicate deletion
//
// TODO: adjustPageBreaks, adjustComments, adjustDataValidations, adjustProtectedCells
//
func (f *File) adjustHelper(sheet string, dir adjustDirection, num, offset int) error {
xlsx, err := f.workSheetReader(sheet)
if err != nil {
return err
}
if dir == rows {
f.adjustRowDimensions(xlsx, num, offset)
} else {
f.adjustColDimensions(xlsx, num, offset)
}
f.adjustHyperlinks(xlsx, sheet, dir, num, offset)
if err = f.adjustMergeCells(xlsx, dir, num, offset); err != nil {
return err
}
if err = f.adjustAutoFilter(xlsx, dir, num, offset); err != nil {
return err
}
if err = f.adjustCalcChain(dir, num, offset); err != nil {
return err
}
checkSheet(xlsx)
_ = checkRow(xlsx)
if xlsx.MergeCells != nil && len(xlsx.MergeCells.Cells) == 0 {
xlsx.MergeCells = nil
}
return nil
}
// adjustColDimensions provides a function to update column dimensions when
// inserting or deleting rows or columns.
func (f *File) adjustColDimensions(xlsx *xlsxWorksheet, col, offset int) {
for rowIdx := range xlsx.SheetData.Row {
for colIdx, v := range xlsx.SheetData.Row[rowIdx].C {
cellCol, cellRow, _ := CellNameToCoordinates(v.R)
if col <= cellCol {
if newCol := cellCol + offset; newCol > 0 {
xlsx.SheetData.Row[rowIdx].C[colIdx].R, _ = CoordinatesToCellName(newCol, cellRow)
}
}
}
}
}
// adjustRowDimensions provides a function to update row dimensions when
// inserting or deleting rows or columns.
func (f *File) adjustRowDimensions(xlsx *xlsxWorksheet, row, offset int) {
for i := range xlsx.SheetData.Row {
r := &xlsx.SheetData.Row[i]
if newRow := r.R + offset; r.R >= row && newRow > 0 {
f.ajustSingleRowDimensions(r, newRow)
}
}
}
// ajustSingleRowDimensions provides a function to ajust single row dimensions.
func (f *File) ajustSingleRowDimensions(r *xlsxRow, num int) {
r.R = num
for i, col := range r.C {
colName, _, _ := SplitCellName(col.R)
r.C[i].R, _ = JoinCellName(colName, num)
}
}
// adjustHyperlinks provides a function to update hyperlinks when inserting or
// deleting rows or columns.
func (f *File) adjustHyperlinks(xlsx *xlsxWorksheet, sheet string, dir adjustDirection, num, offset int) {
// short path
if xlsx.Hyperlinks == nil || len(xlsx.Hyperlinks.Hyperlink) == 0 {
return
}
// order is important
if offset < 0 {
for i := len(xlsx.Hyperlinks.Hyperlink) - 1; i >= 0; i-- {
linkData := xlsx.Hyperlinks.Hyperlink[i]
colNum, rowNum, _ := CellNameToCoordinates(linkData.Ref)
if (dir == rows && num == rowNum) || (dir == columns && num == colNum) {
f.deleteSheetRelationships(sheet, linkData.RID)
if len(xlsx.Hyperlinks.Hyperlink) > 1 {
xlsx.Hyperlinks.Hyperlink = append(xlsx.Hyperlinks.Hyperlink[:i],
xlsx.Hyperlinks.Hyperlink[i+1:]...)
} else {
xlsx.Hyperlinks = nil
}
}
}
}
if xlsx.Hyperlinks == nil {
return
}
for i := range xlsx.Hyperlinks.Hyperlink {
link := &xlsx.Hyperlinks.Hyperlink[i] // get reference
colNum, rowNum, _ := CellNameToCoordinates(link.Ref)
if dir == rows {
if rowNum >= num {
link.Ref, _ = CoordinatesToCellName(colNum, rowNum+offset)
}
} else {
if colNum >= num {
link.Ref, _ = CoordinatesToCellName(colNum+offset, rowNum)
}
}
}
}
// adjustAutoFilter provides a function to update the auto filter when
// inserting or deleting rows or columns.
func (f *File) adjustAutoFilter(xlsx *xlsxWorksheet, dir adjustDirection, num, offset int) error {
if xlsx.AutoFilter == nil {
return nil
}
coordinates, err := f.areaRefToCoordinates(xlsx.AutoFilter.Ref)
if err != nil {
return err
}
x1, y1, x2, y2 := coordinates[0], coordinates[1], coordinates[2], coordinates[3]
if (dir == rows && y1 == num && offset < 0) || (dir == columns && x1 == num && x2 == num) {
xlsx.AutoFilter = nil
for rowIdx := range xlsx.SheetData.Row {
rowData := &xlsx.SheetData.Row[rowIdx]
if rowData.R > y1 && rowData.R <= y2 {
rowData.Hidden = false
}
}
return nil
}
coordinates = f.adjustAutoFilterHelper(dir, coordinates, num, offset)
x1, y1, x2, y2 = coordinates[0], coordinates[1], coordinates[2], coordinates[3]
if xlsx.AutoFilter.Ref, err = f.coordinatesToAreaRef([]int{x1, y1, x2, y2}); err != nil {
return err
}
return nil
}
// adjustAutoFilterHelper provides a function for adjusting auto filter to
// compare and calculate cell axis by the given adjust direction, operation
// axis and offset.
func (f *File) adjustAutoFilterHelper(dir adjustDirection, coordinates []int, num, offset int) []int {
if dir == rows {
if coordinates[1] >= num {
coordinates[1] += offset
}
if coordinates[3] >= num {
coordinates[3] += offset
}
} else {
if coordinates[2] >= num {
coordinates[2] += offset
}
}
return coordinates
}
// areaRefToCoordinates provides a function to convert area reference to a
// pair of coordinates.
func (f *File) areaRefToCoordinates(ref string) ([]int, error) {
rng := strings.Split(ref, ":")
return areaRangeToCoordinates(rng[0], rng[1])
}
// areaRangeToCoordinates provides a function to convert cell range to a
// pair of coordinates.
func areaRangeToCoordinates(firstCell, lastCell string) ([]int, error) {
coordinates := make([]int, 4)
var err error
coordinates[0], coordinates[1], err = CellNameToCoordinates(firstCell)
if err != nil {
return coordinates, err
}
coordinates[2], coordinates[3], err = CellNameToCoordinates(lastCell)
return coordinates, err
}
// sortCoordinates provides a function to correct the coordinate area, such
// correct C1:B3 to B1:C3.
func sortCoordinates(coordinates []int) error {
if len(coordinates) != 4 {
return errors.New("coordinates length must be 4")
}
if coordinates[2] < coordinates[0] {
coordinates[2], coordinates[0] = coordinates[0], coordinates[2]
}
if coordinates[3] < coordinates[1] {
coordinates[3], coordinates[1] = coordinates[1], coordinates[3]
}
return nil
}
// coordinatesToAreaRef provides a function to convert a pair of coordinates
// to area reference.
func (f *File) coordinatesToAreaRef(coordinates []int) (string, error) {
if len(coordinates) != 4 {
return "", errors.New("coordinates length must be 4")
}
firstCell, err := CoordinatesToCellName(coordinates[0], coordinates[1])
if err != nil {
return "", err
}
lastCell, err := CoordinatesToCellName(coordinates[2], coordinates[3])
if err != nil {
return "", err
}
return firstCell + ":" + lastCell, err
}
// adjustMergeCells provides a function to update merged cells when inserting
// or deleting rows or columns.
func (f *File) adjustMergeCells(xlsx *xlsxWorksheet, dir adjustDirection, num, offset int) error {
if xlsx.MergeCells == nil {
return nil
}
for i := 0; i < len(xlsx.MergeCells.Cells); i++ {
areaData := xlsx.MergeCells.Cells[i]
coordinates, err := f.areaRefToCoordinates(areaData.Ref)
if err != nil {
return err
}
x1, y1, x2, y2 := coordinates[0], coordinates[1], coordinates[2], coordinates[3]
if dir == rows {
if y1 == num && y2 == num && offset < 0 {
f.deleteMergeCell(xlsx, i)
i--
}
y1 = f.adjustMergeCellsHelper(y1, num, offset)
y2 = f.adjustMergeCellsHelper(y2, num, offset)
} else {
if x1 == num && x2 == num && offset < 0 {
f.deleteMergeCell(xlsx, i)
i--
}
x1 = f.adjustMergeCellsHelper(x1, num, offset)
x2 = f.adjustMergeCellsHelper(x2, num, offset)
}
if x1 == x2 && y1 == y2 {
f.deleteMergeCell(xlsx, i)
i--
}
if areaData.Ref, err = f.coordinatesToAreaRef([]int{x1, y1, x2, y2}); err != nil {
return err
}
}
return nil
}
// adjustMergeCellsHelper provides a function for adjusting merge cells to
// compare and calculate cell axis by the given pivot, operation axis and
// offset.
func (f *File) adjustMergeCellsHelper(pivot, num, offset int) int {
if pivot >= num {
pivot += offset
if pivot < 1 {
return 1
}
return pivot
}
return pivot
}
// deleteMergeCell provides a function to delete merged cell by given index.
func (f *File) deleteMergeCell(sheet *xlsxWorksheet, idx int) {
if len(sheet.MergeCells.Cells) > idx {
sheet.MergeCells.Cells = append(sheet.MergeCells.Cells[:idx], sheet.MergeCells.Cells[idx+1:]...)
sheet.MergeCells.Count = len(sheet.MergeCells.Cells)
}
}
// adjustCalcChain provides a function to update the calculation chain when
// inserting or deleting rows or columns.
func (f *File) adjustCalcChain(dir adjustDirection, num, offset int) error {
if f.CalcChain == nil {
return nil
}
for index, c := range f.CalcChain.C {
colNum, rowNum, err := CellNameToCoordinates(c.R)
if err != nil {
return err
}
if dir == rows && num <= rowNum {
if newRow := rowNum + offset; newRow > 0 {
f.CalcChain.C[index].R, _ = CoordinatesToCellName(colNum, newRow)
}
}
if dir == columns && num <= colNum {
if newCol := colNum + offset; newCol > 0 {
f.CalcChain.C[index].R, _ = CoordinatesToCellName(newCol, rowNum)
}
}
}
return nil
}
... ...
// Copyright 2016 - 2020 The excelize Authors. All rights reserved. Use of
// this source code is governed by a BSD-style license that can be found in
// the LICENSE file.
//
// Package excelize providing a set of functions that allow you to write to
// and read from XLSX / XLSM / XLTM files. Supports reading and writing
// spreadsheet documents generated by Microsoft Exce™ 2007 and later. Supports
// complex components by high compatibility, and provided streaming API for
// generating or reading data from a worksheet with huge amounts of data. This
// library needs Go version 1.10 or later.
package excelize
import (
"bytes"
"container/list"
"errors"
"fmt"
"math"
"math/rand"
"reflect"
"regexp"
"sort"
"strconv"
"strings"
"time"
"github.com/xuri/efp"
)
// Excel formula errors
const (
formulaErrorDIV = "#DIV/0!"
formulaErrorNAME = "#NAME?"
formulaErrorNA = "#N/A"
formulaErrorNUM = "#NUM!"
formulaErrorVALUE = "#VALUE!"
formulaErrorREF = "#REF!"
formulaErrorNULL = "#NULL"
formulaErrorSPILL = "#SPILL!"
formulaErrorCALC = "#CALC!"
formulaErrorGETTINGDATA = "#GETTING_DATA"
)
// cellRef defines the structure of a cell reference.
type cellRef struct {
Col int
Row int
Sheet string
}
// cellRef defines the structure of a cell range.
type cellRange struct {
From cellRef
To cellRef
}
// formula criteria condition enumeration.
const (
_ byte = iota
criteriaEq
criteriaLe
criteriaGe
criteriaL
criteriaG
criteriaBeg
criteriaEnd
)
// formulaCriteria defined formula criteria parser result.
type formulaCriteria struct {
Type byte
Condition string
}
// ArgType is the type if formula argument type.
type ArgType byte
// Formula argument types enumeration.
const (
ArgUnknown ArgType = iota
ArgString
ArgMatrix
)
// formulaArg is the argument of a formula or function.
type formulaArg struct {
String string
Matrix [][]formulaArg
Type ArgType
}
// formulaFuncs is the type of the formula functions.
type formulaFuncs struct{}
// CalcCellValue provides a function to get calculated cell value. This
// feature is currently in working processing. Array formula, table formula
// and some other formulas are not supported currently.
//
// Supported formulas:
//
// ABS, ACOS, ACOSH, ACOT, ACOTH, ARABIC, ASIN, ASINH, ATAN2, ATANH, BASE,
// CEILING, CEILING.MATH, CEILING.PRECISE, COMBIN, COMBINA, COS, COSH, COT,
// COTH, COUNTA, CSC, CSCH, DECIMAL, DEGREES, EVEN, EXP, FACT, FACTDOUBLE,
// FLOOR, FLOOR.MATH, FLOOR.PRECISE, GCD, INT, ISBLANK, ISERR, ISERROR,
// ISEVEN, ISNA, ISNONTEXT, ISNUMBER, ISO.CEILING, ISODD, LCM, LN, LOG,
// LOG10, MDETERM, MEDIAN, MOD, MROUND, MULTINOMIAL, MUNIT, NA, ODD, PI,
// POWER, PRODUCT, QUOTIENT, RADIANS, RAND, RANDBETWEEN, ROUND, ROUNDDOWN,
// ROUNDUP, SEC, SECH, SIGN, SIN, SINH, SQRT, SQRTPI, SUM, SUMIF, SUMSQ,
// TAN, TANH, TRUNC
//
func (f *File) CalcCellValue(sheet, cell string) (result string, err error) {
var (
formula string
token efp.Token
)
if formula, err = f.GetCellFormula(sheet, cell); err != nil {
return
}
ps := efp.ExcelParser()
tokens := ps.Parse(formula)
if tokens == nil {
return
}
if token, err = f.evalInfixExp(sheet, tokens); err != nil {
return
}
result = token.TValue
return
}
// getPriority calculate arithmetic operator priority.
func getPriority(token efp.Token) (pri int) {
var priority = map[string]int{
"*": 2,
"/": 2,
"+": 1,
"-": 1,
}
pri, _ = priority[token.TValue]
if token.TValue == "-" && token.TType == efp.TokenTypeOperatorPrefix {
pri = 3
}
if token.TSubType == efp.TokenSubTypeStart && token.TType == efp.TokenTypeSubexpression { // (
pri = 0
}
return
}
// evalInfixExp evaluate syntax analysis by given infix expression after
// lexical analysis. Evaluate an infix expression containing formulas by
// stacks:
//
// opd - Operand
// opt - Operator
// opf - Operation formula
// opfd - Operand of the operation formula
// opft - Operator of the operation formula
//
// Evaluate arguments of the operation formula by list:
//
// args - Arguments of the operation formula
//
// TODO: handle subtypes: Nothing, Text, Logical, Error, Concatenation, Intersection, Union
//
func (f *File) evalInfixExp(sheet string, tokens []efp.Token) (efp.Token, error) {
var err error
opdStack, optStack, opfStack, opfdStack, opftStack := NewStack(), NewStack(), NewStack(), NewStack(), NewStack()
argsList := list.New()
for i := 0; i < len(tokens); i++ {
token := tokens[i]
// out of function stack
if opfStack.Len() == 0 {
if err = f.parseToken(sheet, token, opdStack, optStack); err != nil {
return efp.Token{}, err
}
}
// function start
if token.TType == efp.TokenTypeFunction && token.TSubType == efp.TokenSubTypeStart {
opfStack.Push(token)
continue
}
// in function stack, walk 2 token at once
if opfStack.Len() > 0 {
var nextToken efp.Token
if i+1 < len(tokens) {
nextToken = tokens[i+1]
}
// current token is args or range, skip next token, order required: parse reference first
if token.TSubType == efp.TokenSubTypeRange {
if !opftStack.Empty() {
// parse reference: must reference at here
result, err := f.parseReference(sheet, token.TValue)
if err != nil {
return efp.Token{TValue: formulaErrorNAME}, err
}
if result.Type != ArgString {
return efp.Token{}, errors.New(formulaErrorVALUE)
}
opfdStack.Push(efp.Token{
TType: efp.TokenTypeOperand,
TSubType: efp.TokenSubTypeNumber,
TValue: result.String,
})
continue
}
if nextToken.TType == efp.TokenTypeArgument || nextToken.TType == efp.TokenTypeFunction {
// parse reference: reference or range at here
result, err := f.parseReference(sheet, token.TValue)
if err != nil {
return efp.Token{TValue: formulaErrorNAME}, err
}
if result.Type == ArgUnknown {
return efp.Token{}, errors.New(formulaErrorVALUE)
}
argsList.PushBack(result)
continue
}
}
// check current token is opft
if err = f.parseToken(sheet, token, opfdStack, opftStack); err != nil {
return efp.Token{}, err
}
// current token is arg
if token.TType == efp.TokenTypeArgument {
for !opftStack.Empty() {
// calculate trigger
topOpt := opftStack.Peek().(efp.Token)
if err := calculate(opfdStack, topOpt); err != nil {
return efp.Token{}, err
}
opftStack.Pop()
}
if !opfdStack.Empty() {
argsList.PushBack(formulaArg{
String: opfdStack.Pop().(efp.Token).TValue,
Type: ArgString,
})
}
continue
}
// current token is logical
if token.TType == efp.OperatorsInfix && token.TSubType == efp.TokenSubTypeLogical {
}
// current token is text
if token.TType == efp.TokenTypeOperand && token.TSubType == efp.TokenSubTypeText {
argsList.PushBack(formulaArg{
String: token.TValue,
Type: ArgString,
})
}
// current token is function stop
if token.TType == efp.TokenTypeFunction && token.TSubType == efp.TokenSubTypeStop {
for !opftStack.Empty() {
// calculate trigger
topOpt := opftStack.Peek().(efp.Token)
if err := calculate(opfdStack, topOpt); err != nil {
return efp.Token{}, err
}
opftStack.Pop()
}
// push opfd to args
if opfdStack.Len() > 0 {
argsList.PushBack(formulaArg{
String: opfdStack.Pop().(efp.Token).TValue,
Type: ArgString,
})
}
// call formula function to evaluate
result, err := callFuncByName(&formulaFuncs{}, strings.NewReplacer(
"_xlfn", "", ".", "").Replace(opfStack.Peek().(efp.Token).TValue),
[]reflect.Value{reflect.ValueOf(argsList)})
if err != nil {
return efp.Token{}, err
}
argsList.Init()
opfStack.Pop()
if opfStack.Len() > 0 { // still in function stack
opfdStack.Push(efp.Token{TValue: result, TType: efp.TokenTypeOperand, TSubType: efp.TokenSubTypeNumber})
} else {
opdStack.Push(efp.Token{TValue: result, TType: efp.TokenTypeOperand, TSubType: efp.TokenSubTypeNumber})
}
}
}
}
for optStack.Len() != 0 {
topOpt := optStack.Peek().(efp.Token)
if err = calculate(opdStack, topOpt); err != nil {
return efp.Token{}, err
}
optStack.Pop()
}
if opdStack.Len() == 0 {
return efp.Token{}, errors.New("formula not valid")
}
return opdStack.Peek().(efp.Token), err
}
// calcAdd evaluate addition arithmetic operations.
func calcAdd(opdStack *Stack) error {
if opdStack.Len() < 2 {
return errors.New("formula not valid")
}
rOpd := opdStack.Pop().(efp.Token)
lOpd := opdStack.Pop().(efp.Token)
lOpdVal, err := strconv.ParseFloat(lOpd.TValue, 64)
if err != nil {
return err
}
rOpdVal, err := strconv.ParseFloat(rOpd.TValue, 64)
if err != nil {
return err
}
result := lOpdVal + rOpdVal
opdStack.Push(efp.Token{TValue: fmt.Sprintf("%g", result), TType: efp.TokenTypeOperand, TSubType: efp.TokenSubTypeNumber})
return nil
}
// calcSubtract evaluate subtraction arithmetic operations.
func calcSubtract(opdStack *Stack) error {
if opdStack.Len() < 2 {
return errors.New("formula not valid")
}
rOpd := opdStack.Pop().(efp.Token)
lOpd := opdStack.Pop().(efp.Token)
lOpdVal, err := strconv.ParseFloat(lOpd.TValue, 64)
if err != nil {
return err
}
rOpdVal, err := strconv.ParseFloat(rOpd.TValue, 64)
if err != nil {
return err
}
result := lOpdVal - rOpdVal
opdStack.Push(efp.Token{TValue: fmt.Sprintf("%g", result), TType: efp.TokenTypeOperand, TSubType: efp.TokenSubTypeNumber})
return nil
}
// calcMultiply evaluate multiplication arithmetic operations.
func calcMultiply(opdStack *Stack) error {
if opdStack.Len() < 2 {
return errors.New("formula not valid")
}
rOpd := opdStack.Pop().(efp.Token)
lOpd := opdStack.Pop().(efp.Token)
lOpdVal, err := strconv.ParseFloat(lOpd.TValue, 64)
if err != nil {
return err
}
rOpdVal, err := strconv.ParseFloat(rOpd.TValue, 64)
if err != nil {
return err
}
result := lOpdVal * rOpdVal
opdStack.Push(efp.Token{TValue: fmt.Sprintf("%g", result), TType: efp.TokenTypeOperand, TSubType: efp.TokenSubTypeNumber})
return nil
}
// calcDivide evaluate division arithmetic operations.
func calcDivide(opdStack *Stack) error {
if opdStack.Len() < 2 {
return errors.New("formula not valid")
}
rOpd := opdStack.Pop().(efp.Token)
lOpd := opdStack.Pop().(efp.Token)
lOpdVal, err := strconv.ParseFloat(lOpd.TValue, 64)
if err != nil {
return err
}
rOpdVal, err := strconv.ParseFloat(rOpd.TValue, 64)
if err != nil {
return err
}
result := lOpdVal / rOpdVal
if rOpdVal == 0 {
return errors.New(formulaErrorDIV)
}
opdStack.Push(efp.Token{TValue: fmt.Sprintf("%g", result), TType: efp.TokenTypeOperand, TSubType: efp.TokenSubTypeNumber})
return nil
}
// calculate evaluate basic arithmetic operations.
func calculate(opdStack *Stack, opt efp.Token) error {
if opt.TValue == "-" && opt.TType == efp.TokenTypeOperatorPrefix {
if opdStack.Len() < 1 {
return errors.New("formula not valid")
}
opd := opdStack.Pop().(efp.Token)
opdVal, err := strconv.ParseFloat(opd.TValue, 64)
if err != nil {
return err
}
result := 0 - opdVal
opdStack.Push(efp.Token{TValue: fmt.Sprintf("%g", result), TType: efp.TokenTypeOperand, TSubType: efp.TokenSubTypeNumber})
}
if opt.TValue == "+" {
if err := calcAdd(opdStack); err != nil {
return err
}
}
if opt.TValue == "-" && opt.TType == efp.TokenTypeOperatorInfix {
if err := calcSubtract(opdStack); err != nil {
return err
}
}
if opt.TValue == "*" {
if err := calcMultiply(opdStack); err != nil {
return err
}
}
if opt.TValue == "/" {
if err := calcDivide(opdStack); err != nil {
return err
}
}
return nil
}
// parseOperatorPrefixToken parse operator prefix token.
func (f *File) parseOperatorPrefixToken(optStack, opdStack *Stack, token efp.Token) (err error) {
if optStack.Len() == 0 {
optStack.Push(token)
} else {
tokenPriority := getPriority(token)
topOpt := optStack.Peek().(efp.Token)
topOptPriority := getPriority(topOpt)
if tokenPriority > topOptPriority {
optStack.Push(token)
} else {
for tokenPriority <= topOptPriority {
optStack.Pop()
if err = calculate(opdStack, topOpt); err != nil {
return
}
if optStack.Len() > 0 {
topOpt = optStack.Peek().(efp.Token)
topOptPriority = getPriority(topOpt)
continue
}
break
}
optStack.Push(token)
}
}
return
}
// isOperatorPrefixToken determine if the token is parse operator prefix
// token.
func isOperatorPrefixToken(token efp.Token) bool {
if (token.TValue == "-" && token.TType == efp.TokenTypeOperatorPrefix) ||
token.TValue == "+" || token.TValue == "-" || token.TValue == "*" || token.TValue == "/" {
return true
}
return false
}
func (f *File) getDefinedNameRefTo(definedNameName string, currentSheet string) (refTo string) {
for _, definedName := range f.GetDefinedName() {
if definedName.Name == definedNameName {
refTo = definedName.RefersTo
// worksheet scope takes precedence over scope workbook when both definedNames exist
if definedName.Scope == currentSheet {
break
}
}
}
return refTo
}
// parseToken parse basic arithmetic operator priority and evaluate based on
// operators and operands.
func (f *File) parseToken(sheet string, token efp.Token, opdStack, optStack *Stack) error {
// parse reference: must reference at here
if token.TSubType == efp.TokenSubTypeRange {
refTo := f.getDefinedNameRefTo(token.TValue, sheet)
if refTo != "" {
token.TValue = refTo
}
result, err := f.parseReference(sheet, token.TValue)
if err != nil {
return errors.New(formulaErrorNAME)
}
if result.Type != ArgString {
return errors.New(formulaErrorVALUE)
}
token.TValue = result.String
token.TType = efp.TokenTypeOperand
token.TSubType = efp.TokenSubTypeNumber
}
if isOperatorPrefixToken(token) {
if err := f.parseOperatorPrefixToken(optStack, opdStack, token); err != nil {
return err
}
}
if token.TType == efp.TokenTypeSubexpression && token.TSubType == efp.TokenSubTypeStart { // (
optStack.Push(token)
}
if token.TType == efp.TokenTypeSubexpression && token.TSubType == efp.TokenSubTypeStop { // )
for optStack.Peek().(efp.Token).TSubType != efp.TokenSubTypeStart && optStack.Peek().(efp.Token).TType != efp.TokenTypeSubexpression { // != (
topOpt := optStack.Peek().(efp.Token)
if err := calculate(opdStack, topOpt); err != nil {
return err
}
optStack.Pop()
}
optStack.Pop()
}
// opd
if token.TType == efp.TokenTypeOperand && token.TSubType == efp.TokenSubTypeNumber {
opdStack.Push(token)
}
return nil
}
// parseReference parse reference and extract values by given reference
// characters and default sheet name.
func (f *File) parseReference(sheet, reference string) (arg formulaArg, err error) {
reference = strings.Replace(reference, "$", "", -1)
refs, cellRanges, cellRefs := list.New(), list.New(), list.New()
for _, ref := range strings.Split(reference, ":") {
tokens := strings.Split(ref, "!")
cr := cellRef{}
if len(tokens) == 2 { // have a worksheet name
cr.Sheet = tokens[0]
if cr.Col, cr.Row, err = CellNameToCoordinates(tokens[1]); err != nil {
return
}
if refs.Len() > 0 {
e := refs.Back()
cellRefs.PushBack(e.Value.(cellRef))
refs.Remove(e)
}
refs.PushBack(cr)
continue
}
if cr.Col, cr.Row, err = CellNameToCoordinates(tokens[0]); err != nil {
return
}
e := refs.Back()
if e == nil {
cr.Sheet = sheet
refs.PushBack(cr)
continue
}
cellRanges.PushBack(cellRange{
From: e.Value.(cellRef),
To: cr,
})
refs.Remove(e)
}
if refs.Len() > 0 {
e := refs.Back()
cellRefs.PushBack(e.Value.(cellRef))
refs.Remove(e)
}
arg, err = f.rangeResolver(cellRefs, cellRanges)
return
}
// prepareValueRange prepare value range.
func prepareValueRange(cr cellRange, valueRange []int) {
if cr.From.Row < valueRange[0] || valueRange[0] == 0 {
valueRange[0] = cr.From.Row
}
if cr.From.Col < valueRange[2] || valueRange[2] == 0 {
valueRange[2] = cr.From.Col
}
if cr.To.Row > valueRange[1] || valueRange[1] == 0 {
valueRange[1] = cr.To.Row
}
if cr.To.Col > valueRange[3] || valueRange[3] == 0 {
valueRange[3] = cr.To.Col
}
}
// prepareValueRef prepare value reference.
func prepareValueRef(cr cellRef, valueRange []int) {
if cr.Row < valueRange[0] || valueRange[0] == 0 {
valueRange[0] = cr.Row
}
if cr.Col < valueRange[2] || valueRange[2] == 0 {
valueRange[2] = cr.Col
}
if cr.Row > valueRange[1] || valueRange[1] == 0 {
valueRange[1] = cr.Row
}
if cr.Col > valueRange[3] || valueRange[3] == 0 {
valueRange[3] = cr.Col
}
}
// rangeResolver extract value as string from given reference and range list.
// This function will not ignore the empty cell. For example, A1:A2:A2:B3 will
// be reference A1:B3.
func (f *File) rangeResolver(cellRefs, cellRanges *list.List) (arg formulaArg, err error) {
// value range order: from row, to row, from column, to column
valueRange := []int{0, 0, 0, 0}
var sheet string
// prepare value range
for temp := cellRanges.Front(); temp != nil; temp = temp.Next() {
cr := temp.Value.(cellRange)
if cr.From.Sheet != cr.To.Sheet {
err = errors.New(formulaErrorVALUE)
}
rng := []int{cr.From.Col, cr.From.Row, cr.To.Col, cr.To.Row}
sortCoordinates(rng)
cr.From.Col, cr.From.Row, cr.To.Col, cr.To.Row = rng[0], rng[1], rng[2], rng[3]
prepareValueRange(cr, valueRange)
if cr.From.Sheet != "" {
sheet = cr.From.Sheet
}
}
for temp := cellRefs.Front(); temp != nil; temp = temp.Next() {
cr := temp.Value.(cellRef)
if cr.Sheet != "" {
sheet = cr.Sheet
}
prepareValueRef(cr, valueRange)
}
// extract value from ranges
if cellRanges.Len() > 0 {
arg.Type = ArgMatrix
for row := valueRange[0]; row <= valueRange[1]; row++ {
var matrixRow = []formulaArg{}
for col := valueRange[2]; col <= valueRange[3]; col++ {
var cell, value string
if cell, err = CoordinatesToCellName(col, row); err != nil {
return
}
if value, err = f.GetCellValue(sheet, cell); err != nil {
return
}
matrixRow = append(matrixRow, formulaArg{
String: value,
Type: ArgString,
})
}
arg.Matrix = append(arg.Matrix, matrixRow)
}
return
}
// extract value from references
for temp := cellRefs.Front(); temp != nil; temp = temp.Next() {
cr := temp.Value.(cellRef)
var cell string
if cell, err = CoordinatesToCellName(cr.Col, cr.Row); err != nil {
return
}
if arg.String, err = f.GetCellValue(cr.Sheet, cell); err != nil {
return
}
arg.Type = ArgString
}
return
}
// callFuncByName calls the no error or only error return function with
// reflect by given receiver, name and parameters.
func callFuncByName(receiver interface{}, name string, params []reflect.Value) (result string, err error) {
function := reflect.ValueOf(receiver).MethodByName(name)
if function.IsValid() {
rt := function.Call(params)
if len(rt) == 0 {
return
}
if !rt[1].IsNil() {
err = rt[1].Interface().(error)
return
}
result = rt[0].Interface().(string)
return
}
err = fmt.Errorf("not support %s function", name)
return
}
// formulaCriteriaParser parse formula criteria.
func formulaCriteriaParser(exp string) (fc *formulaCriteria) {
fc = &formulaCriteria{}
if exp == "" {
return
}
if match := regexp.MustCompile(`^([0-9]+)$`).FindStringSubmatch(exp); len(match) > 1 {
fc.Type, fc.Condition = criteriaEq, match[1]
return
}
if match := regexp.MustCompile(`^=(.*)$`).FindStringSubmatch(exp); len(match) > 1 {
fc.Type, fc.Condition = criteriaEq, match[1]
return
}
if match := regexp.MustCompile(`^<(.*)$`).FindStringSubmatch(exp); len(match) > 1 {
fc.Type, fc.Condition = criteriaLe, match[1]
return
}
if match := regexp.MustCompile(`^>(.*)$`).FindStringSubmatch(exp); len(match) > 1 {
fc.Type, fc.Condition = criteriaGe, match[1]
return
}
if match := regexp.MustCompile(`^<=(.*)$`).FindStringSubmatch(exp); len(match) > 1 {
fc.Type, fc.Condition = criteriaL, match[1]
return
}
if match := regexp.MustCompile(`^>=(.*)$`).FindStringSubmatch(exp); len(match) > 1 {
fc.Type, fc.Condition = criteriaG, match[1]
return
}
if strings.Contains(exp, "*") {
if strings.HasPrefix(exp, "*") {
fc.Type, fc.Condition = criteriaEnd, strings.TrimPrefix(exp, "*")
}
if strings.HasSuffix(exp, "*") {
fc.Type, fc.Condition = criteriaBeg, strings.TrimSuffix(exp, "*")
}
return
}
fc.Type, fc.Condition = criteriaEq, exp
return
}
// formulaCriteriaEval evaluate formula criteria expression.
func formulaCriteriaEval(val string, criteria *formulaCriteria) (result bool, err error) {
var value, expected float64
var prepareValue = func(val, cond string) (value float64, expected float64, err error) {
value, _ = strconv.ParseFloat(val, 64)
if expected, err = strconv.ParseFloat(criteria.Condition, 64); err != nil {
return
}
return
}
switch criteria.Type {
case criteriaEq:
return val == criteria.Condition, err
case criteriaLe:
if value, expected, err = prepareValue(val, criteria.Condition); err != nil {
return
}
return value <= expected, err
case criteriaGe:
if value, expected, err = prepareValue(val, criteria.Condition); err != nil {
return
}
return value >= expected, err
case criteriaL:
if value, expected, err = prepareValue(val, criteria.Condition); err != nil {
return
}
return value < expected, err
case criteriaG:
if value, expected, err = prepareValue(val, criteria.Condition); err != nil {
return
}
return value > expected, err
case criteriaBeg:
return strings.HasPrefix(val, criteria.Condition), err
case criteriaEnd:
return strings.HasSuffix(val, criteria.Condition), err
}
return
}
// Math and Trigonometric functions
// ABS function returns the absolute value of any supplied number. The syntax
// of the function is:
//
// ABS(number)
//
func (fn *formulaFuncs) ABS(argsList *list.List) (result string, err error) {
if argsList.Len() != 1 {
err = errors.New("ABS requires 1 numeric argument")
return
}
var val float64
if val, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
result = fmt.Sprintf("%g", math.Abs(val))
return
}
// ACOS function calculates the arccosine (i.e. the inverse cosine) of a given
// number, and returns an angle, in radians, between 0 and π. The syntax of
// the function is:
//
// ACOS(number)
//
func (fn *formulaFuncs) ACOS(argsList *list.List) (result string, err error) {
if argsList.Len() != 1 {
err = errors.New("ACOS requires 1 numeric argument")
return
}
var val float64
if val, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
result = fmt.Sprintf("%g", math.Acos(val))
return
}
// ACOSH function calculates the inverse hyperbolic cosine of a supplied number.
// of the function is:
//
// ACOSH(number)
//
func (fn *formulaFuncs) ACOSH(argsList *list.List) (result string, err error) {
if argsList.Len() != 1 {
err = errors.New("ACOSH requires 1 numeric argument")
return
}
var val float64
if val, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
result = fmt.Sprintf("%g", math.Acosh(val))
return
}
// ACOT function calculates the arccotangent (i.e. the inverse cotangent) of a
// given number, and returns an angle, in radians, between 0 and π. The syntax
// of the function is:
//
// ACOT(number)
//
func (fn *formulaFuncs) ACOT(argsList *list.List) (result string, err error) {
if argsList.Len() != 1 {
err = errors.New("ACOT requires 1 numeric argument")
return
}
var val float64
if val, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
result = fmt.Sprintf("%g", math.Pi/2-math.Atan(val))
return
}
// ACOTH function calculates the hyperbolic arccotangent (coth) of a supplied
// value. The syntax of the function is:
//
// ACOTH(number)
//
func (fn *formulaFuncs) ACOTH(argsList *list.List) (result string, err error) {
if argsList.Len() != 1 {
err = errors.New("ACOTH requires 1 numeric argument")
return
}
var val float64
if val, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
result = fmt.Sprintf("%g", math.Atanh(1/val))
return
}
// ARABIC function converts a Roman numeral into an Arabic numeral. The syntax
// of the function is:
//
// ARABIC(text)
//
func (fn *formulaFuncs) ARABIC(argsList *list.List) (result string, err error) {
if argsList.Len() != 1 {
err = errors.New("ARABIC requires 1 numeric argument")
return
}
charMap := map[rune]float64{'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
val, last, prefix := 0.0, 0.0, 1.0
for _, char := range argsList.Front().Value.(formulaArg).String {
digit := 0.0
if char == '-' {
prefix = -1
continue
}
digit, _ = charMap[char]
val += digit
switch {
case last == digit && (last == 5 || last == 50 || last == 500):
result = formulaErrorVALUE
return
case 2*last == digit:
result = formulaErrorVALUE
return
}
if last < digit {
val -= 2 * last
}
last = digit
}
result = fmt.Sprintf("%g", prefix*val)
return
}
// ASIN function calculates the arcsine (i.e. the inverse sine) of a given
// number, and returns an angle, in radians, between -π/2 and π/2. The syntax
// of the function is:
//
// ASIN(number)
//
func (fn *formulaFuncs) ASIN(argsList *list.List) (result string, err error) {
if argsList.Len() != 1 {
err = errors.New("ASIN requires 1 numeric argument")
return
}
var val float64
if val, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
result = fmt.Sprintf("%g", math.Asin(val))
return
}
// ASINH function calculates the inverse hyperbolic sine of a supplied number.
// The syntax of the function is:
//
// ASINH(number)
//
func (fn *formulaFuncs) ASINH(argsList *list.List) (result string, err error) {
if argsList.Len() != 1 {
err = errors.New("ASINH requires 1 numeric argument")
return
}
var val float64
if val, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
result = fmt.Sprintf("%g", math.Asinh(val))
return
}
// ATAN function calculates the arctangent (i.e. the inverse tangent) of a
// given number, and returns an angle, in radians, between -π/2 and +π/2. The
// syntax of the function is:
//
// ATAN(number)
//
func (fn *formulaFuncs) ATAN(argsList *list.List) (result string, err error) {
if argsList.Len() != 1 {
err = errors.New("ATAN requires 1 numeric argument")
return
}
var val float64
if val, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
result = fmt.Sprintf("%g", math.Atan(val))
return
}
// ATANH function calculates the inverse hyperbolic tangent of a supplied
// number. The syntax of the function is:
//
// ATANH(number)
//
func (fn *formulaFuncs) ATANH(argsList *list.List) (result string, err error) {
if argsList.Len() != 1 {
err = errors.New("ATANH requires 1 numeric argument")
return
}
var val float64
if val, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
result = fmt.Sprintf("%g", math.Atanh(val))
return
}
// ATAN2 function calculates the arctangent (i.e. the inverse tangent) of a
// given set of x and y coordinates, and returns an angle, in radians, between
// -π/2 and +π/2. The syntax of the function is:
//
// ATAN2(x_num,y_num)
//
func (fn *formulaFuncs) ATAN2(argsList *list.List) (result string, err error) {
if argsList.Len() != 2 {
err = errors.New("ATAN2 requires 2 numeric arguments")
return
}
var x, y float64
if x, err = strconv.ParseFloat(argsList.Back().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
if y, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
result = fmt.Sprintf("%g", math.Atan2(x, y))
return
}
// BASE function converts a number into a supplied base (radix), and returns a
// text representation of the calculated value. The syntax of the function is:
//
// BASE(number,radix,[min_length])
//
func (fn *formulaFuncs) BASE(argsList *list.List) (result string, err error) {
if argsList.Len() < 2 {
err = errors.New("BASE requires at least 2 arguments")
return
}
if argsList.Len() > 3 {
err = errors.New("BASE allows at most 3 arguments")
return
}
var number float64
var radix, minLength int
if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
if radix, err = strconv.Atoi(argsList.Front().Next().Value.(formulaArg).String); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
if radix < 2 || radix > 36 {
err = errors.New("radix must be an integer >= 2 and <= 36")
return
}
if argsList.Len() > 2 {
if minLength, err = strconv.Atoi(argsList.Back().Value.(formulaArg).String); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
}
result = strconv.FormatInt(int64(number), radix)
if len(result) < minLength {
result = strings.Repeat("0", minLength-len(result)) + result
}
result = strings.ToUpper(result)
return
}
// CEILING function rounds a supplied number away from zero, to the nearest
// multiple of a given number. The syntax of the function is:
//
// CEILING(number,significance)
//
func (fn *formulaFuncs) CEILING(argsList *list.List) (result string, err error) {
if argsList.Len() == 0 {
err = errors.New("CEILING requires at least 1 argument")
return
}
if argsList.Len() > 2 {
err = errors.New("CEILING allows at most 2 arguments")
return
}
number, significance, res := 0.0, 1.0, 0.0
if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
if number < 0 {
significance = -1
}
if argsList.Len() > 1 {
if significance, err = strconv.ParseFloat(argsList.Back().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
}
if significance < 0 && number > 0 {
err = errors.New("negative sig to CEILING invalid")
return
}
if argsList.Len() == 1 {
result = fmt.Sprintf("%g", math.Ceil(number))
return
}
number, res = math.Modf(number / significance)
if res > 0 {
number++
}
result = fmt.Sprintf("%g", number*significance)
return
}
// CEILINGMATH function rounds a supplied number up to a supplied multiple of
// significance. The syntax of the function is:
//
// CEILING.MATH(number,[significance],[mode])
//
func (fn *formulaFuncs) CEILINGMATH(argsList *list.List) (result string, err error) {
if argsList.Len() == 0 {
err = errors.New("CEILING.MATH requires at least 1 argument")
return
}
if argsList.Len() > 3 {
err = errors.New("CEILING.MATH allows at most 3 arguments")
return
}
number, significance, mode := 0.0, 1.0, 1.0
if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
if number < 0 {
significance = -1
}
if argsList.Len() > 1 {
if significance, err = strconv.ParseFloat(argsList.Front().Next().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
}
if argsList.Len() == 1 {
result = fmt.Sprintf("%g", math.Ceil(number))
return
}
if argsList.Len() > 2 {
if mode, err = strconv.ParseFloat(argsList.Back().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
}
val, res := math.Modf(number / significance)
if res != 0 {
if number > 0 {
val++
} else if mode < 0 {
val--
}
}
result = fmt.Sprintf("%g", val*significance)
return
}
// CEILINGPRECISE function rounds a supplied number up (regardless of the
// number's sign), to the nearest multiple of a given number. The syntax of
// the function is:
//
// CEILING.PRECISE(number,[significance])
//
func (fn *formulaFuncs) CEILINGPRECISE(argsList *list.List) (result string, err error) {
if argsList.Len() == 0 {
err = errors.New("CEILING.PRECISE requires at least 1 argument")
return
}
if argsList.Len() > 2 {
err = errors.New("CEILING.PRECISE allows at most 2 arguments")
return
}
number, significance := 0.0, 1.0
if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
if number < 0 {
significance = -1
}
if argsList.Len() == 1 {
result = fmt.Sprintf("%g", math.Ceil(number))
return
}
if argsList.Len() > 1 {
if significance, err = strconv.ParseFloat(argsList.Back().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
significance = math.Abs(significance)
if significance == 0 {
result = "0"
return
}
}
val, res := math.Modf(number / significance)
if res != 0 {
if number > 0 {
val++
}
}
result = fmt.Sprintf("%g", val*significance)
return
}
// COMBIN function calculates the number of combinations (in any order) of a
// given number objects from a set. The syntax of the function is:
//
// COMBIN(number,number_chosen)
//
func (fn *formulaFuncs) COMBIN(argsList *list.List) (result string, err error) {
if argsList.Len() != 2 {
err = errors.New("COMBIN requires 2 argument")
return
}
number, chosen, val := 0.0, 0.0, 1.0
if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
if chosen, err = strconv.ParseFloat(argsList.Back().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
number, chosen = math.Trunc(number), math.Trunc(chosen)
if chosen > number {
err = errors.New("COMBIN requires number >= number_chosen")
return
}
if chosen == number || chosen == 0 {
result = "1"
return
}
for c := float64(1); c <= chosen; c++ {
val *= (number + 1 - c) / c
}
result = fmt.Sprintf("%g", math.Ceil(val))
return
}
// COMBINA function calculates the number of combinations, with repetitions,
// of a given number objects from a set. The syntax of the function is:
//
// COMBINA(number,number_chosen)
//
func (fn *formulaFuncs) COMBINA(argsList *list.List) (result string, err error) {
if argsList.Len() != 2 {
err = errors.New("COMBINA requires 2 argument")
return
}
var number, chosen float64
if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
if chosen, err = strconv.ParseFloat(argsList.Back().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
number, chosen = math.Trunc(number), math.Trunc(chosen)
if number < chosen {
err = errors.New("COMBINA requires number > number_chosen")
return
}
if number == 0 {
result = "0"
return
}
args := list.New()
args.PushBack(formulaArg{
String: fmt.Sprintf("%g", number+chosen-1),
Type: ArgString,
})
args.PushBack(formulaArg{
String: fmt.Sprintf("%g", number-1),
Type: ArgString,
})
return fn.COMBIN(args)
}
// COS function calculates the cosine of a given angle. The syntax of the
// function is:
//
// COS(number)
//
func (fn *formulaFuncs) COS(argsList *list.List) (result string, err error) {
if argsList.Len() != 1 {
err = errors.New("COS requires 1 numeric argument")
return
}
var val float64
if val, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
result = fmt.Sprintf("%g", math.Cos(val))
return
}
// COSH function calculates the hyperbolic cosine (cosh) of a supplied number.
// The syntax of the function is:
//
// COSH(number)
//
func (fn *formulaFuncs) COSH(argsList *list.List) (result string, err error) {
if argsList.Len() != 1 {
err = errors.New("COSH requires 1 numeric argument")
return
}
var val float64
if val, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
result = fmt.Sprintf("%g", math.Cosh(val))
return
}
// COT function calculates the cotangent of a given angle. The syntax of the
// function is:
//
// COT(number)
//
func (fn *formulaFuncs) COT(argsList *list.List) (result string, err error) {
if argsList.Len() != 1 {
err = errors.New("COT requires 1 numeric argument")
return
}
var val float64
if val, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
if val == 0 {
err = errors.New(formulaErrorDIV)
return
}
result = fmt.Sprintf("%g", math.Tan(val))
return
}
// COTH function calculates the hyperbolic cotangent (coth) of a supplied
// angle. The syntax of the function is:
//
// COTH(number)
//
func (fn *formulaFuncs) COTH(argsList *list.List) (result string, err error) {
if argsList.Len() != 1 {
err = errors.New("COTH requires 1 numeric argument")
return
}
var val float64
if val, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
if val == 0 {
err = errors.New(formulaErrorDIV)
return
}
result = fmt.Sprintf("%g", math.Tanh(val))
return
}
// CSC function calculates the cosecant of a given angle. The syntax of the
// function is:
//
// CSC(number)
//
func (fn *formulaFuncs) CSC(argsList *list.List) (result string, err error) {
if argsList.Len() != 1 {
err = errors.New("CSC requires 1 numeric argument")
return
}
var val float64
if val, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
if val == 0 {
err = errors.New(formulaErrorDIV)
return
}
result = fmt.Sprintf("%g", 1/math.Sin(val))
return
}
// CSCH function calculates the hyperbolic cosecant (csch) of a supplied
// angle. The syntax of the function is:
//
// CSCH(number)
//
func (fn *formulaFuncs) CSCH(argsList *list.List) (result string, err error) {
if argsList.Len() != 1 {
err = errors.New("CSCH requires 1 numeric argument")
return
}
var val float64
if val, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
if val == 0 {
err = errors.New(formulaErrorDIV)
return
}
result = fmt.Sprintf("%g", 1/math.Sinh(val))
return
}
// DECIMAL function converts a text representation of a number in a specified
// base, into a decimal value. The syntax of the function is:
//
// DECIMAL(text,radix)
//
func (fn *formulaFuncs) DECIMAL(argsList *list.List) (result string, err error) {
if argsList.Len() != 2 {
err = errors.New("DECIMAL requires 2 numeric arguments")
return
}
var text = argsList.Front().Value.(formulaArg).String
var radix int
if radix, err = strconv.Atoi(argsList.Back().Value.(formulaArg).String); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
if len(text) > 2 && (strings.HasPrefix(text, "0x") || strings.HasPrefix(text, "0X")) {
text = text[2:]
}
val, err := strconv.ParseInt(text, radix, 64)
if err != nil {
err = errors.New(formulaErrorVALUE)
return
}
result = fmt.Sprintf("%g", float64(val))
return
}
// DEGREES function converts radians into degrees. The syntax of the function
// is:
//
// DEGREES(angle)
//
func (fn *formulaFuncs) DEGREES(argsList *list.List) (result string, err error) {
if argsList.Len() != 1 {
err = errors.New("DEGREES requires 1 numeric argument")
return
}
var val float64
if val, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
if val == 0 {
err = errors.New(formulaErrorDIV)
return
}
result = fmt.Sprintf("%g", 180.0/math.Pi*val)
return
}
// EVEN function rounds a supplied number away from zero (i.e. rounds a
// positive number up and a negative number down), to the next even number.
// The syntax of the function is:
//
// EVEN(number)
//
func (fn *formulaFuncs) EVEN(argsList *list.List) (result string, err error) {
if argsList.Len() != 1 {
err = errors.New("EVEN requires 1 numeric argument")
return
}
var number float64
if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
sign := math.Signbit(number)
m, frac := math.Modf(number / 2)
val := m * 2
if frac != 0 {
if !sign {
val += 2
} else {
val -= 2
}
}
result = fmt.Sprintf("%g", val)
return
}
// EXP function calculates the value of the mathematical constant e, raised to
// the power of a given number. The syntax of the function is:
//
// EXP(number)
//
func (fn *formulaFuncs) EXP(argsList *list.List) (result string, err error) {
if argsList.Len() != 1 {
err = errors.New("EXP requires 1 numeric argument")
return
}
var number float64
if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
result = strings.ToUpper(fmt.Sprintf("%g", math.Exp(number)))
return
}
// fact returns the factorial of a supplied number.
func fact(number float64) float64 {
val := float64(1)
for i := float64(2); i <= number; i++ {
val *= i
}
return val
}
// FACT function returns the factorial of a supplied number. The syntax of the
// function is:
//
// FACT(number)
//
func (fn *formulaFuncs) FACT(argsList *list.List) (result string, err error) {
if argsList.Len() != 1 {
err = errors.New("FACT requires 1 numeric argument")
return
}
var number float64
if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
if number < 0 {
err = errors.New(formulaErrorNUM)
}
result = strings.ToUpper(fmt.Sprintf("%g", fact(number)))
return
}
// FACTDOUBLE function returns the double factorial of a supplied number. The
// syntax of the function is:
//
// FACTDOUBLE(number)
//
func (fn *formulaFuncs) FACTDOUBLE(argsList *list.List) (result string, err error) {
if argsList.Len() != 1 {
err = errors.New("FACTDOUBLE requires 1 numeric argument")
return
}
number, val := 0.0, 1.0
if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
if number < 0 {
err = errors.New(formulaErrorNUM)
return
}
for i := math.Trunc(number); i > 1; i -= 2 {
val *= i
}
result = strings.ToUpper(fmt.Sprintf("%g", val))
return
}
// FLOOR function rounds a supplied number towards zero to the nearest
// multiple of a specified significance. The syntax of the function is:
//
// FLOOR(number,significance)
//
func (fn *formulaFuncs) FLOOR(argsList *list.List) (result string, err error) {
if argsList.Len() != 2 {
err = errors.New("FLOOR requires 2 numeric arguments")
return
}
var number, significance float64
if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
if significance, err = strconv.ParseFloat(argsList.Back().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
if significance < 0 && number >= 0 {
err = errors.New(formulaErrorNUM)
return
}
val := number
val, res := math.Modf(val / significance)
if res != 0 {
if number < 0 && res < 0 {
val--
}
}
result = strings.ToUpper(fmt.Sprintf("%g", val*significance))
return
}
// FLOORMATH function rounds a supplied number down to a supplied multiple of
// significance. The syntax of the function is:
//
// FLOOR.MATH(number,[significance],[mode])
//
func (fn *formulaFuncs) FLOORMATH(argsList *list.List) (result string, err error) {
if argsList.Len() == 0 {
err = errors.New("FLOOR.MATH requires at least 1 argument")
return
}
if argsList.Len() > 3 {
err = errors.New("FLOOR.MATH allows at most 3 arguments")
return
}
number, significance, mode := 0.0, 1.0, 1.0
if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
if number < 0 {
significance = -1
}
if argsList.Len() > 1 {
if significance, err = strconv.ParseFloat(argsList.Front().Next().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
}
if argsList.Len() == 1 {
result = fmt.Sprintf("%g", math.Floor(number))
return
}
if argsList.Len() > 2 {
if mode, err = strconv.ParseFloat(argsList.Back().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
}
val, res := math.Modf(number / significance)
if res != 0 && number < 0 && mode > 0 {
val--
}
result = fmt.Sprintf("%g", val*significance)
return
}
// FLOORPRECISE function rounds a supplied number down to a supplied multiple
// of significance. The syntax of the function is:
//
// FLOOR.PRECISE(number,[significance])
//
func (fn *formulaFuncs) FLOORPRECISE(argsList *list.List) (result string, err error) {
if argsList.Len() == 0 {
err = errors.New("FLOOR.PRECISE requires at least 1 argument")
return
}
if argsList.Len() > 2 {
err = errors.New("FLOOR.PRECISE allows at most 2 arguments")
return
}
var number, significance float64
if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
if number < 0 {
significance = -1
}
if argsList.Len() == 1 {
result = fmt.Sprintf("%g", math.Floor(number))
return
}
if argsList.Len() > 1 {
if significance, err = strconv.ParseFloat(argsList.Back().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
significance = math.Abs(significance)
if significance == 0 {
result = "0"
return
}
}
val, res := math.Modf(number / significance)
if res != 0 {
if number < 0 {
val--
}
}
result = fmt.Sprintf("%g", val*significance)
return
}
// gcd returns the greatest common divisor of two supplied integers.
func gcd(x, y float64) float64 {
x, y = math.Trunc(x), math.Trunc(y)
if x == 0 {
return y
}
if y == 0 {
return x
}
for x != y {
if x > y {
x = x - y
} else {
y = y - x
}
}
return x
}
// GCD function returns the greatest common divisor of two or more supplied
// integers. The syntax of the function is:
//
// GCD(number1,[number2],...)
//
func (fn *formulaFuncs) GCD(argsList *list.List) (result string, err error) {
if argsList.Len() == 0 {
err = errors.New("GCD requires at least 1 argument")
return
}
var (
val float64
nums = []float64{}
)
for arg := argsList.Front(); arg != nil; arg = arg.Next() {
token := arg.Value.(formulaArg).String
if token == "" {
continue
}
if val, err = strconv.ParseFloat(token, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
nums = append(nums, val)
}
if nums[0] < 0 {
err = errors.New("GCD only accepts positive arguments")
return
}
if len(nums) == 1 {
result = fmt.Sprintf("%g", nums[0])
return
}
cd := nums[0]
for i := 1; i < len(nums); i++ {
if nums[i] < 0 {
err = errors.New("GCD only accepts positive arguments")
return
}
cd = gcd(cd, nums[i])
}
result = fmt.Sprintf("%g", cd)
return
}
// INT function truncates a supplied number down to the closest integer. The
// syntax of the function is:
//
// INT(number)
//
func (fn *formulaFuncs) INT(argsList *list.List) (result string, err error) {
if argsList.Len() != 1 {
err = errors.New("INT requires 1 numeric argument")
return
}
var number float64
if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
val, frac := math.Modf(number)
if frac < 0 {
val--
}
result = fmt.Sprintf("%g", val)
return
}
// ISOCEILING function rounds a supplied number up (regardless of the number's
// sign), to the nearest multiple of a supplied significance. The syntax of
// the function is:
//
// ISO.CEILING(number,[significance])
//
func (fn *formulaFuncs) ISOCEILING(argsList *list.List) (result string, err error) {
if argsList.Len() == 0 {
err = errors.New("ISO.CEILING requires at least 1 argument")
return
}
if argsList.Len() > 2 {
err = errors.New("ISO.CEILING allows at most 2 arguments")
return
}
var number, significance float64
if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
if number < 0 {
significance = -1
}
if argsList.Len() == 1 {
result = fmt.Sprintf("%g", math.Ceil(number))
return
}
if argsList.Len() > 1 {
if significance, err = strconv.ParseFloat(argsList.Back().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
significance = math.Abs(significance)
if significance == 0 {
result = "0"
return
}
}
val, res := math.Modf(number / significance)
if res != 0 {
if number > 0 {
val++
}
}
result = fmt.Sprintf("%g", val*significance)
return
}
// lcm returns the least common multiple of two supplied integers.
func lcm(a, b float64) float64 {
a = math.Trunc(a)
b = math.Trunc(b)
if a == 0 && b == 0 {
return 0
}
return a * b / gcd(a, b)
}
// LCM function returns the least common multiple of two or more supplied
// integers. The syntax of the function is:
//
// LCM(number1,[number2],...)
//
func (fn *formulaFuncs) LCM(argsList *list.List) (result string, err error) {
if argsList.Len() == 0 {
err = errors.New("LCM requires at least 1 argument")
return
}
var (
val float64
nums = []float64{}
)
for arg := argsList.Front(); arg != nil; arg = arg.Next() {
token := arg.Value.(formulaArg).String
if token == "" {
continue
}
if val, err = strconv.ParseFloat(token, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
nums = append(nums, val)
}
if nums[0] < 0 {
err = errors.New("LCM only accepts positive arguments")
return
}
if len(nums) == 1 {
result = fmt.Sprintf("%g", nums[0])
return
}
cm := nums[0]
for i := 1; i < len(nums); i++ {
if nums[i] < 0 {
err = errors.New("LCM only accepts positive arguments")
return
}
cm = lcm(cm, nums[i])
}
result = fmt.Sprintf("%g", cm)
return
}
// LN function calculates the natural logarithm of a given number. The syntax
// of the function is:
//
// LN(number)
//
func (fn *formulaFuncs) LN(argsList *list.List) (result string, err error) {
if argsList.Len() != 1 {
err = errors.New("LN requires 1 numeric argument")
return
}
var number float64
if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
result = fmt.Sprintf("%g", math.Log(number))
return
}
// LOG function calculates the logarithm of a given number, to a supplied
// base. The syntax of the function is:
//
// LOG(number,[base])
//
func (fn *formulaFuncs) LOG(argsList *list.List) (result string, err error) {
if argsList.Len() == 0 {
err = errors.New("LOG requires at least 1 argument")
return
}
if argsList.Len() > 2 {
err = errors.New("LOG allows at most 2 arguments")
return
}
number, base := 0.0, 10.0
if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
if argsList.Len() > 1 {
if base, err = strconv.ParseFloat(argsList.Back().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
}
if number == 0 {
err = errors.New(formulaErrorNUM)
return
}
if base == 0 {
err = errors.New(formulaErrorNUM)
return
}
if base == 1 {
err = errors.New(formulaErrorDIV)
return
}
result = fmt.Sprintf("%g", math.Log(number)/math.Log(base))
return
}
// LOG10 function calculates the base 10 logarithm of a given number. The
// syntax of the function is:
//
// LOG10(number)
//
func (fn *formulaFuncs) LOG10(argsList *list.List) (result string, err error) {
if argsList.Len() != 1 {
err = errors.New("LOG10 requires 1 numeric argument")
return
}
var number float64
if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
result = fmt.Sprintf("%g", math.Log10(number))
return
}
func minor(sqMtx [][]float64, idx int) [][]float64 {
ret := [][]float64{}
for i := range sqMtx {
if i == 0 {
continue
}
row := []float64{}
for j := range sqMtx {
if j == idx {
continue
}
row = append(row, sqMtx[i][j])
}
ret = append(ret, row)
}
return ret
}
// det determinant of the 2x2 matrix.
func det(sqMtx [][]float64) float64 {
if len(sqMtx) == 2 {
m00 := sqMtx[0][0]
m01 := sqMtx[0][1]
m10 := sqMtx[1][0]
m11 := sqMtx[1][1]
return m00*m11 - m10*m01
}
var res, sgn float64 = 0, 1
for j := range sqMtx {
res += sgn * sqMtx[0][j] * det(minor(sqMtx, j))
sgn *= -1
}
return res
}
// MDETERM calculates the determinant of a square matrix. The
// syntax of the function is:
//
// MDETERM(array)
//
func (fn *formulaFuncs) MDETERM(argsList *list.List) (result string, err error) {
var num float64
var numMtx = [][]float64{}
var strMtx = argsList.Front().Value.(formulaArg).Matrix
if argsList.Len() < 1 {
return
}
var rows = len(strMtx)
for _, row := range argsList.Front().Value.(formulaArg).Matrix {
if len(row) != rows {
err = errors.New(formulaErrorVALUE)
return
}
numRow := []float64{}
for _, ele := range row {
if num, err = strconv.ParseFloat(ele.String, 64); err != nil {
return
}
numRow = append(numRow, num)
}
numMtx = append(numMtx, numRow)
}
result = fmt.Sprintf("%g", det(numMtx))
return
}
// MOD function returns the remainder of a division between two supplied
// numbers. The syntax of the function is:
//
// MOD(number,divisor)
//
func (fn *formulaFuncs) MOD(argsList *list.List) (result string, err error) {
if argsList.Len() != 2 {
err = errors.New("MOD requires 2 numeric arguments")
return
}
var number, divisor float64
if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
if divisor, err = strconv.ParseFloat(argsList.Back().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
if divisor == 0 {
err = errors.New(formulaErrorDIV)
return
}
trunc, rem := math.Modf(number / divisor)
if rem < 0 {
trunc--
}
result = fmt.Sprintf("%g", number-divisor*trunc)
return
}
// MROUND function rounds a supplied number up or down to the nearest multiple
// of a given number. The syntax of the function is:
//
// MOD(number,multiple)
//
func (fn *formulaFuncs) MROUND(argsList *list.List) (result string, err error) {
if argsList.Len() != 2 {
err = errors.New("MROUND requires 2 numeric arguments")
return
}
var number, multiple float64
if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
if multiple, err = strconv.ParseFloat(argsList.Back().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
if multiple == 0 {
err = errors.New(formulaErrorNUM)
return
}
if multiple < 0 && number > 0 ||
multiple > 0 && number < 0 {
err = errors.New(formulaErrorNUM)
return
}
number, res := math.Modf(number / multiple)
if math.Trunc(res+0.5) > 0 {
number++
}
result = fmt.Sprintf("%g", number*multiple)
return
}
// MULTINOMIAL function calculates the ratio of the factorial of a sum of
// supplied values to the product of factorials of those values. The syntax of
// the function is:
//
// MULTINOMIAL(number1,[number2],...)
//
func (fn *formulaFuncs) MULTINOMIAL(argsList *list.List) (result string, err error) {
val, num, denom := 0.0, 0.0, 1.0
for arg := argsList.Front(); arg != nil; arg = arg.Next() {
token := arg.Value.(formulaArg)
if token.String == "" {
continue
}
if val, err = strconv.ParseFloat(token.String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
num += val
denom *= fact(val)
}
result = fmt.Sprintf("%g", fact(num)/denom)
return
}
// MUNIT function returns the unit matrix for a specified dimension. The
// syntax of the function is:
//
// MUNIT(dimension)
//
func (fn *formulaFuncs) MUNIT(argsList *list.List) (result string, err error) {
if argsList.Len() != 1 {
err = errors.New("MUNIT requires 1 numeric argument")
return
}
var dimension int
if dimension, err = strconv.Atoi(argsList.Front().Value.(formulaArg).String); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
matrix := make([][]float64, 0, dimension)
for i := 0; i < dimension; i++ {
row := make([]float64, dimension)
for j := 0; j < dimension; j++ {
if i == j {
row[j] = float64(1.0)
} else {
row[j] = float64(0.0)
}
}
matrix = append(matrix, row)
}
return
}
// ODD function ounds a supplied number away from zero (i.e. rounds a positive
// number up and a negative number down), to the next odd number. The syntax
// of the function is:
//
// ODD(number)
//
func (fn *formulaFuncs) ODD(argsList *list.List) (result string, err error) {
if argsList.Len() != 1 {
err = errors.New("ODD requires 1 numeric argument")
return
}
var number float64
if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
if number == 0 {
result = "1"
return
}
sign := math.Signbit(number)
m, frac := math.Modf((number - 1) / 2)
val := m*2 + 1
if frac != 0 {
if !sign {
val += 2
} else {
val -= 2
}
}
result = fmt.Sprintf("%g", val)
return
}
// PI function returns the value of the mathematical constant π (pi), accurate
// to 15 digits (14 decimal places). The syntax of the function is:
//
// PI()
//
func (fn *formulaFuncs) PI(argsList *list.List) (result string, err error) {
if argsList.Len() != 0 {
err = errors.New("PI accepts no arguments")
return
}
result = fmt.Sprintf("%g", math.Pi)
return
}
// POWER function calculates a given number, raised to a supplied power.
// The syntax of the function is:
//
// POWER(number,power)
//
func (fn *formulaFuncs) POWER(argsList *list.List) (result string, err error) {
if argsList.Len() != 2 {
err = errors.New("POWER requires 2 numeric arguments")
return
}
var x, y float64
if x, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
if y, err = strconv.ParseFloat(argsList.Back().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
if x == 0 && y == 0 {
err = errors.New(formulaErrorNUM)
return
}
if x == 0 && y < 0 {
err = errors.New(formulaErrorDIV)
return
}
result = fmt.Sprintf("%g", math.Pow(x, y))
return
}
// PRODUCT function returns the product (multiplication) of a supplied set of
// numerical values. The syntax of the function is:
//
// PRODUCT(number1,[number2],...)
//
func (fn *formulaFuncs) PRODUCT(argsList *list.List) (result string, err error) {
val, product := 0.0, 1.0
for arg := argsList.Front(); arg != nil; arg = arg.Next() {
token := arg.Value.(formulaArg)
switch token.Type {
case ArgUnknown:
continue
case ArgString:
if token.String == "" {
continue
}
if val, err = strconv.ParseFloat(token.String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
product = product * val
case ArgMatrix:
for _, row := range token.Matrix {
for _, value := range row {
if value.String == "" {
continue
}
if val, err = strconv.ParseFloat(value.String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
product = product * val
}
}
}
}
result = fmt.Sprintf("%g", product)
return
}
// QUOTIENT function returns the integer portion of a division between two
// supplied numbers. The syntax of the function is:
//
// QUOTIENT(numerator,denominator)
//
func (fn *formulaFuncs) QUOTIENT(argsList *list.List) (result string, err error) {
if argsList.Len() != 2 {
err = errors.New("QUOTIENT requires 2 numeric arguments")
return
}
var x, y float64
if x, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
if y, err = strconv.ParseFloat(argsList.Back().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
if y == 0 {
err = errors.New(formulaErrorDIV)
return
}
result = fmt.Sprintf("%g", math.Trunc(x/y))
return
}
// RADIANS function converts radians into degrees. The syntax of the function is:
//
// RADIANS(angle)
//
func (fn *formulaFuncs) RADIANS(argsList *list.List) (result string, err error) {
if argsList.Len() != 1 {
err = errors.New("RADIANS requires 1 numeric argument")
return
}
var angle float64
if angle, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
result = fmt.Sprintf("%g", math.Pi/180.0*angle)
return
}
// RAND function generates a random real number between 0 and 1. The syntax of
// the function is:
//
// RAND()
//
func (fn *formulaFuncs) RAND(argsList *list.List) (result string, err error) {
if argsList.Len() != 0 {
err = errors.New("RAND accepts no arguments")
return
}
result = fmt.Sprintf("%g", rand.New(rand.NewSource(time.Now().UnixNano())).Float64())
return
}
// RANDBETWEEN function generates a random integer between two supplied
// integers. The syntax of the function is:
//
// RANDBETWEEN(bottom,top)
//
func (fn *formulaFuncs) RANDBETWEEN(argsList *list.List) (result string, err error) {
if argsList.Len() != 2 {
err = errors.New("RANDBETWEEN requires 2 numeric arguments")
return
}
var bottom, top int64
if bottom, err = strconv.ParseInt(argsList.Front().Value.(formulaArg).String, 10, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
if top, err = strconv.ParseInt(argsList.Back().Value.(formulaArg).String, 10, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
if top < bottom {
err = errors.New(formulaErrorNUM)
return
}
result = fmt.Sprintf("%g", float64(rand.New(rand.NewSource(time.Now().UnixNano())).Int63n(top-bottom+1)+bottom))
return
}
// romanNumerals defined a numeral system that originated in ancient Rome and
// remained the usual way of writing numbers throughout Europe well into the
// Late Middle Ages.
type romanNumerals struct {
n float64
s string
}
var romanTable = [][]romanNumerals{{{1000, "M"}, {900, "CM"}, {500, "D"}, {400, "CD"}, {100, "C"}, {90, "XC"}, {50, "L"}, {40, "XL"}, {10, "X"}, {9, "IX"}, {5, "V"}, {4, "IV"}, {1, "I"}},
{{1000, "M"}, {950, "LM"}, {900, "CM"}, {500, "D"}, {450, "LD"}, {400, "CD"}, {100, "C"}, {95, "VC"}, {90, "XC"}, {50, "L"}, {45, "VL"}, {40, "XL"}, {10, "X"}, {9, "IX"}, {5, "V"}, {4, "IV"}, {1, "I"}},
{{1000, "M"}, {990, "XM"}, {950, "LM"}, {900, "CM"}, {500, "D"}, {490, "XD"}, {450, "LD"}, {400, "CD"}, {100, "C"}, {99, "IC"}, {90, "XC"}, {50, "L"}, {45, "VL"}, {40, "XL"}, {10, "X"}, {9, "IX"}, {5, "V"}, {4, "IV"}, {1, "I"}},
{{1000, "M"}, {995, "VM"}, {990, "XM"}, {950, "LM"}, {900, "CM"}, {500, "D"}, {495, "VD"}, {490, "XD"}, {450, "LD"}, {400, "CD"}, {100, "C"}, {99, "IC"}, {90, "XC"}, {50, "L"}, {45, "VL"}, {40, "XL"}, {10, "X"}, {9, "IX"}, {5, "V"}, {4, "IV"}, {1, "I"}},
{{1000, "M"}, {999, "IM"}, {995, "VM"}, {990, "XM"}, {950, "LM"}, {900, "CM"}, {500, "D"}, {499, "ID"}, {495, "VD"}, {490, "XD"}, {450, "LD"}, {400, "CD"}, {100, "C"}, {99, "IC"}, {90, "XC"}, {50, "L"}, {45, "VL"}, {40, "XL"}, {10, "X"}, {9, "IX"}, {5, "V"}, {4, "IV"}, {1, "I"}}}
// ROMAN function converts an arabic number to Roman. I.e. for a supplied
// integer, the function returns a text string depicting the roman numeral
// form of the number. The syntax of the function is:
//
// ROMAN(number,[form])
//
func (fn *formulaFuncs) ROMAN(argsList *list.List) (result string, err error) {
if argsList.Len() == 0 {
err = errors.New("ROMAN requires at least 1 argument")
return
}
if argsList.Len() > 2 {
err = errors.New("ROMAN allows at most 2 arguments")
return
}
var number float64
var form int
if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
if argsList.Len() > 1 {
if form, err = strconv.Atoi(argsList.Back().Value.(formulaArg).String); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
if form < 0 {
form = 0
} else if form > 4 {
form = 4
}
}
decimalTable := romanTable[0]
switch form {
case 1:
decimalTable = romanTable[1]
case 2:
decimalTable = romanTable[2]
case 3:
decimalTable = romanTable[3]
case 4:
decimalTable = romanTable[4]
}
val := math.Trunc(number)
buf := bytes.Buffer{}
for _, r := range decimalTable {
for val >= r.n {
buf.WriteString(r.s)
val -= r.n
}
}
result = buf.String()
return
}
type roundMode byte
const (
closest roundMode = iota
down
up
)
// round rounds a supplied number up or down.
func (fn *formulaFuncs) round(number, digits float64, mode roundMode) float64 {
var significance float64
if digits > 0 {
significance = math.Pow(1/10.0, digits)
} else {
significance = math.Pow(10.0, -digits)
}
val, res := math.Modf(number / significance)
switch mode {
case closest:
const eps = 0.499999999
if res >= eps {
val++
} else if res <= -eps {
val--
}
case down:
case up:
if res > 0 {
val++
} else if res < 0 {
val--
}
}
return val * significance
}
// ROUND function rounds a supplied number up or down, to a specified number
// of decimal places. The syntax of the function is:
//
// ROUND(number,num_digits)
//
func (fn *formulaFuncs) ROUND(argsList *list.List) (result string, err error) {
if argsList.Len() != 2 {
err = errors.New("ROUND requires 2 numeric arguments")
return
}
var number, digits float64
if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
if digits, err = strconv.ParseFloat(argsList.Back().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
result = fmt.Sprintf("%g", fn.round(number, digits, closest))
return
}
// ROUNDDOWN function rounds a supplied number down towards zero, to a
// specified number of decimal places. The syntax of the function is:
//
// ROUNDDOWN(number,num_digits)
//
func (fn *formulaFuncs) ROUNDDOWN(argsList *list.List) (result string, err error) {
if argsList.Len() != 2 {
err = errors.New("ROUNDDOWN requires 2 numeric arguments")
return
}
var number, digits float64
if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
if digits, err = strconv.ParseFloat(argsList.Back().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
result = fmt.Sprintf("%g", fn.round(number, digits, down))
return
}
// ROUNDUP function rounds a supplied number up, away from zero, to a
// specified number of decimal places. The syntax of the function is:
//
// ROUNDUP(number,num_digits)
//
func (fn *formulaFuncs) ROUNDUP(argsList *list.List) (result string, err error) {
if argsList.Len() != 2 {
err = errors.New("ROUNDUP requires 2 numeric arguments")
return
}
var number, digits float64
if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
if digits, err = strconv.ParseFloat(argsList.Back().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
result = fmt.Sprintf("%g", fn.round(number, digits, up))
return
}
// SEC function calculates the secant of a given angle. The syntax of the
// function is:
//
// SEC(number)
//
func (fn *formulaFuncs) SEC(argsList *list.List) (result string, err error) {
if argsList.Len() != 1 {
err = errors.New("SEC requires 1 numeric argument")
return
}
var number float64
if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
result = fmt.Sprintf("%g", math.Cos(number))
return
}
// SECH function calculates the hyperbolic secant (sech) of a supplied angle.
// The syntax of the function is:
//
// SECH(number)
//
func (fn *formulaFuncs) SECH(argsList *list.List) (result string, err error) {
if argsList.Len() != 1 {
err = errors.New("SECH requires 1 numeric argument")
return
}
var number float64
if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
result = fmt.Sprintf("%g", 1/math.Cosh(number))
return
}
// SIGN function returns the arithmetic sign (+1, -1 or 0) of a supplied
// number. I.e. if the number is positive, the Sign function returns +1, if
// the number is negative, the function returns -1 and if the number is 0
// (zero), the function returns 0. The syntax of the function is:
//
// SIGN(number)
//
func (fn *formulaFuncs) SIGN(argsList *list.List) (result string, err error) {
if argsList.Len() != 1 {
err = errors.New("SIGN requires 1 numeric argument")
return
}
var val float64
if val, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
if val < 0 {
result = "-1"
return
}
if val > 0 {
result = "1"
return
}
result = "0"
return
}
// SIN function calculates the sine of a given angle. The syntax of the
// function is:
//
// SIN(number)
//
func (fn *formulaFuncs) SIN(argsList *list.List) (result string, err error) {
if argsList.Len() != 1 {
err = errors.New("SIN requires 1 numeric argument")
return
}
var number float64
if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
result = fmt.Sprintf("%g", math.Sin(number))
return
}
// SINH function calculates the hyperbolic sine (sinh) of a supplied number.
// The syntax of the function is:
//
// SINH(number)
//
func (fn *formulaFuncs) SINH(argsList *list.List) (result string, err error) {
if argsList.Len() != 1 {
err = errors.New("SINH requires 1 numeric argument")
return
}
var number float64
if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
result = fmt.Sprintf("%g", math.Sinh(number))
return
}
// SQRT function calculates the positive square root of a supplied number. The
// syntax of the function is:
//
// SQRT(number)
//
func (fn *formulaFuncs) SQRT(argsList *list.List) (result string, err error) {
if argsList.Len() != 1 {
err = errors.New("SQRT requires 1 numeric argument")
return
}
var res float64
var value = argsList.Front().Value.(formulaArg).String
if value == "" {
result = "0"
return
}
if res, err = strconv.ParseFloat(value, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
if res < 0 {
err = errors.New(formulaErrorNUM)
return
}
result = fmt.Sprintf("%g", math.Sqrt(res))
return
}
// SQRTPI function returns the square root of a supplied number multiplied by
// the mathematical constant, π. The syntax of the function is:
//
// SQRTPI(number)
//
func (fn *formulaFuncs) SQRTPI(argsList *list.List) (result string, err error) {
if argsList.Len() != 1 {
err = errors.New("SQRTPI requires 1 numeric argument")
return
}
var number float64
if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
result = fmt.Sprintf("%g", math.Sqrt(number*math.Pi))
return
}
// SUM function adds together a supplied set of numbers and returns the sum of
// these values. The syntax of the function is:
//
// SUM(number1,[number2],...)
//
func (fn *formulaFuncs) SUM(argsList *list.List) (result string, err error) {
var val, sum float64
for arg := argsList.Front(); arg != nil; arg = arg.Next() {
token := arg.Value.(formulaArg)
switch token.Type {
case ArgUnknown:
continue
case ArgString:
if token.String == "" {
continue
}
if val, err = strconv.ParseFloat(token.String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
sum += val
case ArgMatrix:
for _, row := range token.Matrix {
for _, value := range row {
if value.String == "" {
continue
}
if val, err = strconv.ParseFloat(value.String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
sum += val
}
}
}
}
result = fmt.Sprintf("%g", sum)
return
}
// SUMIF function finds the values in a supplied array, that satisfy a given
// criteria, and returns the sum of the corresponding values in a second
// supplied array. The syntax of the function is:
//
// SUMIF(range,criteria,[sum_range])
//
func (fn *formulaFuncs) SUMIF(argsList *list.List) (result string, err error) {
if argsList.Len() < 2 {
err = errors.New("SUMIF requires at least 2 argument")
return
}
var criteria = formulaCriteriaParser(argsList.Front().Next().Value.(formulaArg).String)
var rangeMtx = argsList.Front().Value.(formulaArg).Matrix
var sumRange [][]formulaArg
if argsList.Len() == 3 {
sumRange = argsList.Back().Value.(formulaArg).Matrix
}
var sum, val float64
for rowIdx, row := range rangeMtx {
for colIdx, col := range row {
var ok bool
fromVal := col.String
if col.String == "" {
continue
}
if ok, err = formulaCriteriaEval(fromVal, criteria); err != nil {
return
}
if ok {
if argsList.Len() == 3 {
if len(sumRange) <= rowIdx || len(sumRange[rowIdx]) <= colIdx {
continue
}
fromVal = sumRange[rowIdx][colIdx].String
}
if val, err = strconv.ParseFloat(fromVal, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
sum += val
}
}
}
result = fmt.Sprintf("%g", sum)
return
}
// SUMSQ function returns the sum of squares of a supplied set of values. The
// syntax of the function is:
//
// SUMSQ(number1,[number2],...)
//
func (fn *formulaFuncs) SUMSQ(argsList *list.List) (result string, err error) {
var val, sq float64
for arg := argsList.Front(); arg != nil; arg = arg.Next() {
token := arg.Value.(formulaArg)
switch token.Type {
case ArgString:
if token.String == "" {
continue
}
if val, err = strconv.ParseFloat(token.String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
sq += val * val
case ArgMatrix:
for _, row := range token.Matrix {
for _, value := range row {
if value.String == "" {
continue
}
if val, err = strconv.ParseFloat(value.String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
sq += val * val
}
}
}
}
result = fmt.Sprintf("%g", sq)
return
}
// TAN function calculates the tangent of a given angle. The syntax of the
// function is:
//
// TAN(number)
//
func (fn *formulaFuncs) TAN(argsList *list.List) (result string, err error) {
if argsList.Len() != 1 {
err = errors.New("TAN requires 1 numeric argument")
return
}
var number float64
if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
result = fmt.Sprintf("%g", math.Tan(number))
return
}
// TANH function calculates the hyperbolic tangent (tanh) of a supplied
// number. The syntax of the function is:
//
// TANH(number)
//
func (fn *formulaFuncs) TANH(argsList *list.List) (result string, err error) {
if argsList.Len() != 1 {
err = errors.New("TANH requires 1 numeric argument")
return
}
var number float64
if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
result = fmt.Sprintf("%g", math.Tanh(number))
return
}
// TRUNC function truncates a supplied number to a specified number of decimal
// places. The syntax of the function is:
//
// TRUNC(number,[number_digits])
//
func (fn *formulaFuncs) TRUNC(argsList *list.List) (result string, err error) {
if argsList.Len() == 0 {
err = errors.New("TRUNC requires at least 1 argument")
return
}
var number, digits, adjust, rtrim float64
if number, err = strconv.ParseFloat(argsList.Front().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
if argsList.Len() > 1 {
if digits, err = strconv.ParseFloat(argsList.Back().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
digits = math.Floor(digits)
}
adjust = math.Pow(10, digits)
x := int((math.Abs(number) - math.Abs(float64(int(number)))) * adjust)
if x != 0 {
if rtrim, err = strconv.ParseFloat(strings.TrimRight(strconv.Itoa(x), "0"), 64); err != nil {
return
}
}
if (digits > 0) && (rtrim < adjust/10) {
result = fmt.Sprintf("%g", number)
return
}
result = fmt.Sprintf("%g", float64(int(number*adjust))/adjust)
return
}
// Statistical functions
// COUNTA function returns the number of non-blanks within a supplied set of
// cells or values. The syntax of the function is:
//
// COUNTA(value1,[value2],...)
//
func (fn *formulaFuncs) COUNTA(argsList *list.List) (result string, err error) {
var count int
for token := argsList.Front(); token != nil; token = token.Next() {
arg := token.Value.(formulaArg)
switch arg.Type {
case ArgString:
if arg.String != "" {
count++
}
case ArgMatrix:
for _, row := range arg.Matrix {
for _, value := range row {
if value.String != "" {
count++
}
}
}
}
}
result = fmt.Sprintf("%d", count)
return
}
// MEDIAN function returns the statistical median (the middle value) of a list
// of supplied numbers. The syntax of the function is:
//
// MEDIAN(number1,[number2],...)
//
func (fn *formulaFuncs) MEDIAN(argsList *list.List) (result string, err error) {
if argsList.Len() == 0 {
err = errors.New("MEDIAN requires at least 1 argument")
return
}
values := []float64{}
var median, digits float64
for token := argsList.Front(); token != nil; token = token.Next() {
arg := token.Value.(formulaArg)
switch arg.Type {
case ArgString:
if digits, err = strconv.ParseFloat(argsList.Back().Value.(formulaArg).String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
values = append(values, digits)
case ArgMatrix:
for _, row := range arg.Matrix {
for _, value := range row {
if value.String == "" {
continue
}
if digits, err = strconv.ParseFloat(value.String, 64); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
values = append(values, digits)
}
}
}
}
sort.Float64s(values)
if len(values)%2 == 0 {
median = (values[len(values)/2-1] + values[len(values)/2]) / 2
} else {
median = values[len(values)/2]
}
result = fmt.Sprintf("%g", median)
return
}
// Information functions
// ISBLANK function tests if a specified cell is blank (empty) and if so,
// returns TRUE; Otherwise the function returns FALSE. The syntax of the
// function is:
//
// ISBLANK(value)
//
func (fn *formulaFuncs) ISBLANK(argsList *list.List) (result string, err error) {
if argsList.Len() != 1 {
err = errors.New("ISBLANK requires 1 argument")
return
}
token := argsList.Front().Value.(formulaArg)
result = "FALSE"
switch token.Type {
case ArgUnknown:
result = "TRUE"
case ArgString:
if token.String == "" {
result = "TRUE"
}
}
return
}
// ISERR function tests if an initial supplied expression (or value) returns
// any Excel Error, except the #N/A error. If so, the function returns the
// logical value TRUE; If the supplied value is not an error or is the #N/A
// error, the ISERR function returns FALSE. The syntax of the function is:
//
// ISERR(value)
//
func (fn *formulaFuncs) ISERR(argsList *list.List) (result string, err error) {
if argsList.Len() != 1 {
err = errors.New("ISERR requires 1 argument")
return
}
token := argsList.Front().Value.(formulaArg)
result = "FALSE"
if token.Type == ArgString {
for _, errType := range []string{formulaErrorDIV, formulaErrorNAME, formulaErrorNUM, formulaErrorVALUE, formulaErrorREF, formulaErrorNULL, formulaErrorSPILL, formulaErrorCALC, formulaErrorGETTINGDATA} {
if errType == token.String {
result = "TRUE"
}
}
}
return
}
// ISERROR function tests if an initial supplied expression (or value) returns
// an Excel Error, and if so, returns the logical value TRUE; Otherwise the
// function returns FALSE. The syntax of the function is:
//
// ISERROR(value)
//
func (fn *formulaFuncs) ISERROR(argsList *list.List) (result string, err error) {
if argsList.Len() != 1 {
err = errors.New("ISERROR requires 1 argument")
return
}
token := argsList.Front().Value.(formulaArg)
result = "FALSE"
if token.Type == ArgString {
for _, errType := range []string{formulaErrorDIV, formulaErrorNAME, formulaErrorNA, formulaErrorNUM, formulaErrorVALUE, formulaErrorREF, formulaErrorNULL, formulaErrorSPILL, formulaErrorCALC, formulaErrorGETTINGDATA} {
if errType == token.String {
result = "TRUE"
}
}
}
return
}
// ISEVEN function tests if a supplied number (or numeric expression)
// evaluates to an even number, and if so, returns TRUE; Otherwise, the
// function returns FALSE. The syntax of the function is:
//
// ISEVEN(value)
//
func (fn *formulaFuncs) ISEVEN(argsList *list.List) (result string, err error) {
if argsList.Len() != 1 {
err = errors.New("ISEVEN requires 1 argument")
return
}
token := argsList.Front().Value.(formulaArg)
result = "FALSE"
var numeric int
if token.Type == ArgString {
if numeric, err = strconv.Atoi(token.String); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
if numeric == numeric/2*2 {
result = "TRUE"
return
}
}
return
}
// ISNA function tests if an initial supplied expression (or value) returns
// the Excel #N/A Error, and if so, returns TRUE; Otherwise the function
// returns FALSE. The syntax of the function is:
//
// ISNA(value)
//
func (fn *formulaFuncs) ISNA(argsList *list.List) (result string, err error) {
if argsList.Len() != 1 {
err = errors.New("ISNA requires 1 argument")
return
}
token := argsList.Front().Value.(formulaArg)
result = "FALSE"
if token.Type == ArgString && token.String == formulaErrorNA {
result = "TRUE"
}
return
}
// ISNONTEXT function function tests if a supplied value is text. If not, the
// function returns TRUE; If the supplied value is text, the function returns
// FALSE. The syntax of the function is:
//
// ISNONTEXT(value)
//
func (fn *formulaFuncs) ISNONTEXT(argsList *list.List) (result string, err error) {
if argsList.Len() != 1 {
err = errors.New("ISNONTEXT requires 1 argument")
return
}
token := argsList.Front().Value.(formulaArg)
result = "TRUE"
if token.Type == ArgString && token.String != "" {
result = "FALSE"
}
return
}
// ISNUMBER function function tests if a supplied value is a number. If so,
// the function returns TRUE; Otherwise it returns FALSE. The syntax of the
// function is:
//
// ISNUMBER(value)
//
func (fn *formulaFuncs) ISNUMBER(argsList *list.List) (result string, err error) {
if argsList.Len() != 1 {
err = errors.New("ISNUMBER requires 1 argument")
return
}
token := argsList.Front().Value.(formulaArg)
result = "FALSE"
if token.Type == ArgString && token.String != "" {
if _, err = strconv.Atoi(token.String); err == nil {
result = "TRUE"
}
err = nil
}
return
}
// ISODD function tests if a supplied number (or numeric expression) evaluates
// to an odd number, and if so, returns TRUE; Otherwise, the function returns
// FALSE. The syntax of the function is:
//
// ISODD(value)
//
func (fn *formulaFuncs) ISODD(argsList *list.List) (result string, err error) {
if argsList.Len() != 1 {
err = errors.New("ISODD requires 1 argument")
return
}
token := argsList.Front().Value.(formulaArg)
result = "FALSE"
var numeric int
if token.Type == ArgString {
if numeric, err = strconv.Atoi(token.String); err != nil {
err = errors.New(formulaErrorVALUE)
return
}
if numeric != numeric/2*2 {
result = "TRUE"
return
}
}
return
}
// NA function returns the Excel #N/A error. This error message has the
// meaning 'value not available' and is produced when an Excel Formula is
// unable to find a value that it needs. The syntax of the function is:
//
// NA()
//
func (fn *formulaFuncs) NA(argsList *list.List) (result string, err error) {
if argsList.Len() != 0 {
err = errors.New("NA accepts no arguments")
return
}
result = formulaErrorNA
return
}
... ...
// Copyright 2016 - 2020 The excelize Authors. All rights reserved. Use of
// this source code is governed by a BSD-style license that can be found in
// the LICENSE file.
//
// Package excelize providing a set of functions that allow you to write to
// and read from XLSX / XLSM / XLTM files. Supports reading and writing
// spreadsheet documents generated by Microsoft Exce™ 2007 and later. Supports
// complex components by high compatibility, and provided streaming API for
// generating or reading data from a worksheet with huge amounts of data. This
// library needs Go version 1.10 or later.
package excelize
import (
"bytes"
"encoding/xml"
"io"
"log"
)
// calcChainReader provides a function to get the pointer to the structure
// after deserialization of xl/calcChain.xml.
func (f *File) calcChainReader() *xlsxCalcChain {
var err error
if f.CalcChain == nil {
f.CalcChain = new(xlsxCalcChain)
if err = f.xmlNewDecoder(bytes.NewReader(namespaceStrictToTransitional(f.readXML("xl/calcChain.xml")))).
Decode(f.CalcChain); err != nil && err != io.EOF {
log.Printf("xml decode error: %s", err)
}
}
return f.CalcChain
}
// calcChainWriter provides a function to save xl/calcChain.xml after
// serialize structure.
func (f *File) calcChainWriter() {
if f.CalcChain != nil && f.CalcChain.C != nil {
output, _ := xml.Marshal(f.CalcChain)
f.saveFileList("xl/calcChain.xml", output)
}
}
// deleteCalcChain provides a function to remove cell reference on the
// calculation chain.
func (f *File) deleteCalcChain(index int, axis string) {
calc := f.calcChainReader()
if calc != nil {
calc.C = xlsxCalcChainCollection(calc.C).Filter(func(c xlsxCalcChainC) bool {
return !((c.I == index && c.R == axis) || (c.I == index && axis == ""))
})
}
if len(calc.C) == 0 {
f.CalcChain = nil
delete(f.XLSX, "xl/calcChain.xml")
content := f.contentTypesReader()
for k, v := range content.Overrides {
if v.PartName == "/xl/calcChain.xml" {
content.Overrides = append(content.Overrides[:k], content.Overrides[k+1:]...)
}
}
}
}
type xlsxCalcChainCollection []xlsxCalcChainC
// Filter provides a function to filter calculation chain.
func (c xlsxCalcChainCollection) Filter(fn func(v xlsxCalcChainC) bool) []xlsxCalcChainC {
var results []xlsxCalcChainC
for _, v := range c {
if fn(v) {
results = append(results, v)
}
}
return results
}
... ...