作者 唐旭辉

添加依赖

要显示太多修改。

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

{
// 使用 IntelliSense 了解相关属性。
// 悬停以查看现有属性的描述。
// 欲了解更多信息,请访问: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "Launch",
"type": "go",
"request": "launch",
"mode": "auto",
"program": "${workspaceFolder}/main.go",
"env": {},
"args": []
}
]
}
... ...
~$*.xlsx
test/Test*.xlsx
*.out
*.test
\ No newline at end of file
... ...
language: go
install:
- go get -d -t -v ./... && go build -v ./...
go:
- 1.10.x
- 1.11.x
- 1.12.x
os:
- linux
- osx
env:
matrix:
- GOARCH=amd64
- GOARCH=386
script:
- go vet ./...
- go test ./... -v -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 1.4, available at [http://contributor-covenant.org/version/1/4][version]
[homepage]: http://contributor-covenant.org
[version]: http://contributor-covenant.org/version/1/4/
... ...
# 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:
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-2019, 360 Enterprise Security Group, Endpoint Security, Inc.
Copyright (c) 2011-2017, Geoffrey J. Teale (complying with the tealeg/xlsx license)
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://godoc.org/github.com/360EntSecGroup-Skylar/excelize"><img src="https://godoc.org/github.com/360EntSecGroup-Skylar/excelize?status.svg" alt="GoDoc"></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 files. Supports reading and writing XLSX file generated by Microsoft Excel&trade; 2007 and later.
Supports saving a file without losing original charts of XLSX. 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 [godoc.org](https://godoc.org/github.com/360EntSecGroup-Skylar/excelize) and [docs reference](https://xuri.me/excelize/).
## Basic Usage
### Installation
```bash
go get github.com/360EntSecGroup-Skylar/excelize
```
### Create XLSX file
Here is a minimal example usage that will create XLSX 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.
err := f.SaveAs("./Book1.xlsx")
if err != nil {
fmt.Println(err)
}
}
```
### Reading XLSX file
The following constitutes the bare to read a XLSX 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 XLSX 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)
}
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"}}`)
if err != nil {
fmt.Println(err)
return
}
// Save xlsx file by the given path.
err = f.SaveAs("./Book1.xlsx")
if err != nil {
fmt.Println(err)
}
}
```
### Add picture to XLSX 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.
err = f.AddPicture("Sheet1", "A2", "./image1.png", "")
if err != nil {
fmt.Println(err)
}
// Insert a picture to worksheet with scaling.
err = f.AddPicture("Sheet1", "D2", "./image2.jpg", `{"x_scale": 0.5, "y_scale": 0.5}`)
if err != nil {
fmt.Println(err)
}
// Insert a picture offset in the cell with printing support.
err = f.AddPicture("Sheet1", "H2", "./image3.gif", `{"x_offset": 15, "y_offset": 10, "print_obj": true, "lock_aspect_ratio": false, "locked": false}`)
if err != nil {
fmt.Println(err)
}
// Save the xlsx file with the origin path.
err = f.Save()
if 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.
Some struct of XML originally by [tealeg/xlsx](https://github.com/tealeg/xlsx). Licensed under the [BSD 3-Clause License](https://github.com/tealeg/xlsx/blob/master/LICENSE).
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://godoc.org/github.com/360EntSecGroup-Skylar/excelize"><img src="https://godoc.org/github.com/360EntSecGroup-Skylar/excelize?status.svg" alt="GoDoc"></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 Office OpenXML 标准。可以使用它来读取、写入由 Microsoft Excel&trade; 2007 及以上版本创建的 XLSX 文档。相比较其他的开源类库,Excelize 支持写入原本带有图片(表)、透视表和切片器等复杂样式的文档,还支持向 Excel 文档中插入图片与图表,并且在保存后不会丢失文档原有样式,可以应用于各类报表系统中。使用本类库要求使用的 Go 语言为 1.10 或更高版本,完整的 API 使用文档请访问 [godoc.org](https://godoc.org/github.com/360EntSecGroup-Skylar/excelize) 或查看 [参考文档](https://xuri.me/excelize/)
## 快速上手
### 安装
```bash
go get github.com/360EntSecGroup-Skylar/excelize
```
### 创建 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)
// 根据指定路径保存文件
err := f.SaveAs("./Book1.xlsx")
if 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)
}
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"}}`)
if err != nil {
fmt.Println(err)
return
}
// 根据指定路径保存文件
err = f.SaveAs("./Book1.xlsx")
if 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
}
// 插入图片
err = f.AddPicture("Sheet1", "A2", "./image1.png", "")
if err != nil {
fmt.Println(err)
}
// 在工作表中插入图片,并设置图片的缩放比例
err = f.AddPicture("Sheet1", "D2", "./image2.jpg", `{"x_scale": 0.5, "y_scale": 0.5}`)
if err != nil {
fmt.Println(err)
}
// 在工作表中插入图片,并设置图片的打印属性
err = f.AddPicture("Sheet1", "H2", "./image3.gif", `{"x_offset": 15, "y_offset": 10, "print_obj": true, "lock_aspect_ratio": false, "locked": false}`)
if err != nil {
fmt.Println(err)
}
// 保存文件
err = f.Save()
if 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) 的商标,项目的图片是一种改编。
本类库中部分 XML 结构体的定义参考了开源项目:[tealeg/xlsx](https://github.com/tealeg/xlsx),遵循 [BSD 3-Clause License](https://github.com/tealeg/xlsx/blob/master/LICENSE) 开源许可协议。
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 - 2019 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 files. Support reads and writes XLSX file generated by
// Microsoft Excel™ 2007 and later. Support save file without losing original
// charts of XLSX. 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, r := range xlsx.SheetData.Row {
if newRow := r.R + offset; r.R >= row && newRow > 0 {
f.ajustSingleRowDimensions(&xlsx.SheetData.Row[i], 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 rowIdx, linkData := range xlsx.Hyperlinks.Hyperlink {
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[:rowIdx],
xlsx.Hyperlinks.Hyperlink[rowIdx+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) {
coordinates := make([]int, 4)
rng := strings.Split(ref, ":")
firstCell := rng[0]
lastCell := rng[1]
var err error
coordinates[0], coordinates[1], err = CellNameToCoordinates(firstCell)
if err != nil {
return coordinates, err
}
coordinates[2], coordinates[3], err = CellNameToCoordinates(lastCell)
if err != nil {
return coordinates, err
}
return coordinates, err
}
// 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 - 2019 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 files. Support reads and writes XLSX file generated by
// Microsoft Excel™ 2007 and later. Support save file without losing original
// charts of XLSX. This library needs Go version 1.10 or later.
package excelize
import "encoding/xml"
// calcChainReader provides a function to get the pointer to the structure
// after deserialization of xl/calcChain.xml.
func (f *File) calcChainReader() *xlsxCalcChain {
if f.CalcChain == nil {
var c xlsxCalcChain
_ = xml.Unmarshal(namespaceStrictToTransitional(f.readXML("xl/calcChain.xml")), &c)
f.CalcChain = &c
}
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 {
results := make([]xlsxCalcChainC, 0)
for _, v := range c {
if fn(v) {
results = append(results, v)
}
}
return results
}
... ...
// Copyright 2016 - 2019 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 files. Support reads and writes XLSX file generated by
// Microsoft Excel™ 2007 and later. Support save file without losing original
// charts of XLSX. This library needs Go version 1.10 or later.
package excelize
import (
"encoding/xml"
"errors"
"fmt"
"reflect"
"strconv"
"strings"
"time"
)
const (
// STCellFormulaTypeArray defined the formula is an array formula.
STCellFormulaTypeArray = "array"
// STCellFormulaTypeDataTable defined the formula is a data table formula.
STCellFormulaTypeDataTable = "dataTable"
// STCellFormulaTypeNormal defined the formula is a regular cell formula.
STCellFormulaTypeNormal = "normal"
// STCellFormulaTypeShared defined the formula is part of a shared formula.
STCellFormulaTypeShared = "shared"
)
// GetCellValue provides a function to get formatted value from cell by given
// worksheet name and axis in XLSX file. If it is possible to apply a format
// to the cell value, it will do so, if not then an error will be returned,
// along with the raw value of the cell.
func (f *File) GetCellValue(sheet, axis string) (string, error) {
return f.getCellStringFunc(sheet, axis, func(x *xlsxWorksheet, c *xlsxC) (string, bool, error) {
val, err := c.getValueFrom(f, f.sharedStringsReader())
if err != nil {
return val, false, err
}
return val, true, err
})
}
// SetCellValue provides a function to set value of a cell. The following
// shows the supported data types:
//
// int
// int8
// int16
// int32
// int64
// uint
// uint8
// uint16
// uint32
// uint64
// float32
// float64
// string
// []byte
// time.Duration
// time.Time
// bool
// nil
//
// Note that default date format is m/d/yy h:mm of time.Time type value. You can
// set numbers format by SetCellStyle() method.
func (f *File) SetCellValue(sheet, axis string, value interface{}) error {
var err error
switch v := value.(type) {
case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64:
err = f.setCellIntFunc(sheet, axis, v)
case float32:
err = f.SetCellFloat(sheet, axis, float64(v), -1, 32)
case float64:
err = f.SetCellFloat(sheet, axis, v, -1, 64)
case string:
err = f.SetCellStr(sheet, axis, v)
case []byte:
err = f.SetCellStr(sheet, axis, string(v))
case time.Duration:
err = f.SetCellDefault(sheet, axis, strconv.FormatFloat(v.Seconds()/86400.0, 'f', -1, 32))
if err != nil {
return err
}
err = f.setDefaultTimeStyle(sheet, axis, 21)
case time.Time:
err = f.setCellTimeFunc(sheet, axis, v)
case bool:
err = f.SetCellBool(sheet, axis, v)
case nil:
err = f.SetCellStr(sheet, axis, "")
default:
err = f.SetCellStr(sheet, axis, fmt.Sprint(value))
}
return err
}
// setCellIntFunc is a wrapper of SetCellInt.
func (f *File) setCellIntFunc(sheet, axis string, value interface{}) error {
var err error
switch v := value.(type) {
case int:
err = f.SetCellInt(sheet, axis, v)
case int8:
err = f.SetCellInt(sheet, axis, int(v))
case int16:
err = f.SetCellInt(sheet, axis, int(v))
case int32:
err = f.SetCellInt(sheet, axis, int(v))
case int64:
err = f.SetCellInt(sheet, axis, int(v))
case uint:
err = f.SetCellInt(sheet, axis, int(v))
case uint8:
err = f.SetCellInt(sheet, axis, int(v))
case uint16:
err = f.SetCellInt(sheet, axis, int(v))
case uint32:
err = f.SetCellInt(sheet, axis, int(v))
case uint64:
err = f.SetCellInt(sheet, axis, int(v))
}
return err
}
// setCellTimeFunc provides a method to process time type of value for
// SetCellValue.
func (f *File) setCellTimeFunc(sheet, axis string, value time.Time) error {
excelTime, err := timeToExcelTime(value)
if err != nil {
return err
}
if excelTime > 0 {
err = f.SetCellDefault(sheet, axis, strconv.FormatFloat(excelTime, 'f', -1, 64))
if err != nil {
return err
}
err = f.setDefaultTimeStyle(sheet, axis, 22)
if err != nil {
return err
}
} else {
err = f.SetCellStr(sheet, axis, value.Format(time.RFC3339Nano))
if err != nil {
return err
}
}
return err
}
// SetCellInt provides a function to set int type value of a cell by given
// worksheet name, cell coordinates and cell value.
func (f *File) SetCellInt(sheet, axis string, value int) error {
xlsx, err := f.workSheetReader(sheet)
if err != nil {
return err
}
cellData, col, _, err := f.prepareCell(xlsx, sheet, axis)
if err != nil {
return err
}
cellData.S = f.prepareCellStyle(xlsx, col, cellData.S)
cellData.T = ""
cellData.V = strconv.Itoa(value)
return err
}
// SetCellBool provides a function to set bool type value of a cell by given
// worksheet name, cell name and cell value.
func (f *File) SetCellBool(sheet, axis string, value bool) error {
xlsx, err := f.workSheetReader(sheet)
if err != nil {
return err
}
cellData, col, _, err := f.prepareCell(xlsx, sheet, axis)
if err != nil {
return err
}
cellData.S = f.prepareCellStyle(xlsx, col, cellData.S)
cellData.T = "b"
if value {
cellData.V = "1"
} else {
cellData.V = "0"
}
return err
}
// SetCellFloat sets a floating point value into a cell. The prec parameter
// specifies how many places after the decimal will be shown while -1 is a
// special value that will use as many decimal places as necessary to
// represent the number. bitSize is 32 or 64 depending on if a float32 or
// float64 was originally used for the value. For Example:
//
// var x float32 = 1.325
// f.SetCellFloat("Sheet1", "A1", float64(x), 2, 32)
//
func (f *File) SetCellFloat(sheet, axis string, value float64, prec, bitSize int) error {
xlsx, err := f.workSheetReader(sheet)
if err != nil {
return err
}
cellData, col, _, err := f.prepareCell(xlsx, sheet, axis)
if err != nil {
return err
}
cellData.S = f.prepareCellStyle(xlsx, col, cellData.S)
cellData.T = ""
cellData.V = strconv.FormatFloat(value, 'f', prec, bitSize)
return err
}
// SetCellStr provides a function to set string type value of a cell. Total
// number of characters that a cell can contain 32767 characters.
func (f *File) SetCellStr(sheet, axis, value string) error {
xlsx, err := f.workSheetReader(sheet)
if err != nil {
return err
}
cellData, col, _, err := f.prepareCell(xlsx, sheet, axis)
if err != nil {
return err
}
if len(value) > 32767 {
value = value[0:32767]
}
// Leading space(s) character detection.
if len(value) > 0 && value[0] == 32 {
cellData.XMLSpace = xml.Attr{
Name: xml.Name{Space: NameSpaceXML, Local: "space"},
Value: "preserve",
}
}
cellData.S = f.prepareCellStyle(xlsx, col, cellData.S)
cellData.T = "str"
cellData.V = value
return err
}
// SetCellDefault provides a function to set string type value of a cell as
// default format without escaping the cell.
func (f *File) SetCellDefault(sheet, axis, value string) error {
xlsx, err := f.workSheetReader(sheet)
if err != nil {
return err
}
cellData, col, _, err := f.prepareCell(xlsx, sheet, axis)
if err != nil {
return err
}
cellData.S = f.prepareCellStyle(xlsx, col, cellData.S)
cellData.T = ""
cellData.V = value
return err
}
// GetCellFormula provides a function to get formula from cell by given
// worksheet name and axis in XLSX file.
func (f *File) GetCellFormula(sheet, axis string) (string, error) {
return f.getCellStringFunc(sheet, axis, func(x *xlsxWorksheet, c *xlsxC) (string, bool, error) {
if c.F == nil {
return "", false, nil
}
if c.F.T == STCellFormulaTypeShared {
return getSharedForumula(x, c.F.Si), true, nil
}
return c.F.Content, true, nil
})
}
// FormulaOpts can be passed to SetCellFormula to use other formula types.
type FormulaOpts struct {
Type *string // Formula type
Ref *string // Shared formula ref
}
// SetCellFormula provides a function to set cell formula by given string and
// worksheet name.
func (f *File) SetCellFormula(sheet, axis, formula string, opts ...FormulaOpts) error {
xlsx, err := f.workSheetReader(sheet)
if err != nil {
return err
}
cellData, _, _, err := f.prepareCell(xlsx, sheet, axis)
if err != nil {
return err
}
if formula == "" {
cellData.F = nil
f.deleteCalcChain(f.GetSheetIndex(sheet), axis)
return err
}
if cellData.F != nil {
cellData.F.Content = formula
} else {
cellData.F = &xlsxF{Content: formula}
}
for _, o := range opts {
if o.Type != nil {
cellData.F.T = *o.Type
}
if o.Ref != nil {
cellData.F.Ref = *o.Ref
}
}
return err
}
// GetCellHyperLink provides a function to get cell hyperlink by given
// worksheet name and axis. Boolean type value link will be ture if the cell
// has a hyperlink and the target is the address of the hyperlink. Otherwise,
// the value of link will be false and the value of the target will be a blank
// string. For example get hyperlink of Sheet1!H6:
//
// link, target, err := f.GetCellHyperLink("Sheet1", "H6")
//
func (f *File) GetCellHyperLink(sheet, axis string) (bool, string, error) {
// Check for correct cell name
if _, _, err := SplitCellName(axis); err != nil {
return false, "", err
}
xlsx, err := f.workSheetReader(sheet)
if err != nil {
return false, "", err
}
axis, err = f.mergeCellsParser(xlsx, axis)
if err != nil {
return false, "", err
}
if xlsx.Hyperlinks != nil {
for _, link := range xlsx.Hyperlinks.Hyperlink {
if link.Ref == axis {
if link.RID != "" {
return true, f.getSheetRelationshipsTargetByID(sheet, link.RID), err
}
return true, link.Location, err
}
}
}
return false, "", err
}
// SetCellHyperLink provides a function to set cell hyperlink by given
// worksheet name and link URL address. LinkType defines two types of
// hyperlink "External" for web site or "Location" for moving to one of cell
// in this workbook. Maximum limit hyperlinks in a worksheet is 65530. The
// below is example for external link.
//
// err := f.SetCellHyperLink("Sheet1", "A3", "https://github.com/360EntSecGroup-Skylar/excelize", "External")
// // Set underline and font color style for the cell.
// style, err := f.NewStyle(`{"font":{"color":"#1265BE","underline":"single"}}`)
// err = f.SetCellStyle("Sheet1", "A3", "A3", style)
//
// A this is another example for "Location":
//
// err := f.SetCellHyperLink("Sheet1", "A3", "Sheet1!A40", "Location")
//
func (f *File) SetCellHyperLink(sheet, axis, link, linkType string) error {
// Check for correct cell name
if _, _, err := SplitCellName(axis); err != nil {
return err
}
xlsx, err := f.workSheetReader(sheet)
if err != nil {
return err
}
axis, err = f.mergeCellsParser(xlsx, axis)
if err != nil {
return err
}
var linkData xlsxHyperlink
if xlsx.Hyperlinks == nil {
xlsx.Hyperlinks = new(xlsxHyperlinks)
}
if len(xlsx.Hyperlinks.Hyperlink) > 65529 {
return errors.New("over maximum limit hyperlinks in a worksheet")
}
switch linkType {
case "External":
linkData = xlsxHyperlink{
Ref: axis,
}
sheetPath, _ := f.sheetMap[trimSheetName(sheet)]
sheetRels := "xl/worksheets/_rels/" + strings.TrimPrefix(sheetPath, "xl/worksheets/") + ".rels"
rID := f.addRels(sheetRels, SourceRelationshipHyperLink, link, linkType)
linkData.RID = "rId" + strconv.Itoa(rID)
case "Location":
linkData = xlsxHyperlink{
Ref: axis,
Location: link,
}
default:
return fmt.Errorf("invalid link type %q", linkType)
}
xlsx.Hyperlinks.Hyperlink = append(xlsx.Hyperlinks.Hyperlink, linkData)
return nil
}
// MergeCell provides a function to merge cells by given coordinate area and
// sheet name. For example create a merged cell of D3:E9 on Sheet1:
//
// err := f.MergeCell("Sheet1", "D3", "E9")
//
// If you create a merged cell that overlaps with another existing merged cell,
// those merged cells that already exist will be removed.
func (f *File) MergeCell(sheet, hcell, vcell string) error {
coordinates, err := f.areaRefToCoordinates(hcell + ":" + vcell)
if err != nil {
return err
}
x1, y1, x2, y2 := coordinates[0], coordinates[1], coordinates[2], coordinates[3]
if x1 == x2 && y1 == y2 {
return err
}
// Correct the coordinate area, such correct C1:B3 to B1:C3.
if x2 < x1 {
x1, x2 = x2, x1
}
if y2 < y1 {
y1, y2 = y2, y1
}
hcell, _ = CoordinatesToCellName(x1, y1)
vcell, _ = CoordinatesToCellName(x2, y2)
xlsx, err := f.workSheetReader(sheet)
if err != nil {
return err
}
if xlsx.MergeCells != nil {
ref := hcell + ":" + vcell
// Delete the merged cells of the overlapping area.
for _, cellData := range xlsx.MergeCells.Cells {
cc := strings.Split(cellData.Ref, ":")
if len(cc) != 2 {
return fmt.Errorf("invalid area %q", cellData.Ref)
}
c1, _ := checkCellInArea(hcell, cellData.Ref)
c2, _ := checkCellInArea(vcell, cellData.Ref)
c3, _ := checkCellInArea(cc[0], ref)
c4, _ := checkCellInArea(cc[1], ref)
if !(!c1 && !c2 && !c3 && !c4) {
return nil
}
}
xlsx.MergeCells.Cells = append(xlsx.MergeCells.Cells, &xlsxMergeCell{Ref: ref})
} else {
xlsx.MergeCells = &xlsxMergeCells{Cells: []*xlsxMergeCell{{Ref: hcell + ":" + vcell}}}
}
return err
}
// SetSheetRow writes an array to row by given worksheet name, starting
// coordinate and a pointer to array type 'slice'. For example, writes an
// array to row 6 start with the cell B6 on Sheet1:
//
// err := f.SetSheetRow("Sheet1", "B6", &[]interface{}{"1", nil, 2})
//
func (f *File) SetSheetRow(sheet, axis string, slice interface{}) error {
col, row, err := CellNameToCoordinates(axis)
if err != nil {
return err
}
// Make sure 'slice' is a Ptr to Slice
v := reflect.ValueOf(slice)
if v.Kind() != reflect.Ptr || v.Elem().Kind() != reflect.Slice {
return errors.New("pointer to slice expected")
}
v = v.Elem()
for i := 0; i < v.Len(); i++ {
cell, err := CoordinatesToCellName(col+i, row)
// Error should never happens here. But keep checking to early detect regresions
// if it will be introduced in future.
if err != nil {
return err
}
if err := f.SetCellValue(sheet, cell, v.Index(i).Interface()); err != nil {
return err
}
}
return err
}
// getCellInfo does common preparation for all SetCell* methods.
func (f *File) prepareCell(xlsx *xlsxWorksheet, sheet, cell string) (*xlsxC, int, int, error) {
var err error
cell, err = f.mergeCellsParser(xlsx, cell)
if err != nil {
return nil, 0, 0, err
}
col, row, err := CellNameToCoordinates(cell)
if err != nil {
return nil, 0, 0, err
}
prepareSheetXML(xlsx, col, row)
return &xlsx.SheetData.Row[row-1].C[col-1], col, row, err
}
// getCellStringFunc does common value extraction workflow for all GetCell*
// methods. Passed function implements specific part of required logic.
func (f *File) getCellStringFunc(sheet, axis string, fn func(x *xlsxWorksheet, c *xlsxC) (string, bool, error)) (string, error) {
xlsx, err := f.workSheetReader(sheet)
if err != nil {
return "", err
}
axis, err = f.mergeCellsParser(xlsx, axis)
if err != nil {
return "", err
}
_, row, err := CellNameToCoordinates(axis)
if err != nil {
return "", err
}
lastRowNum := 0
if l := len(xlsx.SheetData.Row); l > 0 {
lastRowNum = xlsx.SheetData.Row[l-1].R
}
// keep in mind: row starts from 1
if row > lastRowNum {
return "", nil
}
for rowIdx := range xlsx.SheetData.Row {
rowData := &xlsx.SheetData.Row[rowIdx]
if rowData.R != row {
continue
}
for colIdx := range rowData.C {
colData := &rowData.C[colIdx]
if axis != colData.R {
continue
}
val, ok, err := fn(xlsx, colData)
if err != nil {
return "", err
}
if ok {
return val, nil
}
}
}
return "", nil
}
// formattedValue provides a function to returns a value after formatted. If
// it is possible to apply a format to the cell value, it will do so, if not
// then an error will be returned, along with the raw value of the cell.
func (f *File) formattedValue(s int, v string) string {
if s == 0 {
return v
}
styleSheet := f.stylesReader()
ok := builtInNumFmtFunc[styleSheet.CellXfs.Xf[s].NumFmtID]
if ok != nil {
return ok(styleSheet.CellXfs.Xf[s].NumFmtID, v)
}
return v
}
// prepareCellStyle provides a function to prepare style index of cell in
// worksheet by given column index and style index.
func (f *File) prepareCellStyle(xlsx *xlsxWorksheet, col, style int) int {
if xlsx.Cols != nil && style == 0 {
for _, c := range xlsx.Cols.Col {
if c.Min <= col && col <= c.Max {
style = c.Style
}
}
}
return style
}
// mergeCellsParser provides a function to check merged cells in worksheet by
// given axis.
func (f *File) mergeCellsParser(xlsx *xlsxWorksheet, axis string) (string, error) {
axis = strings.ToUpper(axis)
if xlsx.MergeCells != nil {
for i := 0; i < len(xlsx.MergeCells.Cells); i++ {
ok, err := checkCellInArea(axis, xlsx.MergeCells.Cells[i].Ref)
if err != nil {
return axis, err
}
if ok {
axis = strings.Split(xlsx.MergeCells.Cells[i].Ref, ":")[0]
}
}
}
return axis, nil
}
// checkCellInArea provides a function to determine if a given coordinate is
// within an area.
func checkCellInArea(cell, area string) (bool, error) {
col, row, err := CellNameToCoordinates(cell)
if err != nil {
return false, err
}
rng := strings.Split(area, ":")
if len(rng) != 2 {
return false, err
}
firstCol, firstRow, _ := CellNameToCoordinates(rng[0])
lastCol, lastRow, _ := CellNameToCoordinates(rng[1])
return col >= firstCol && col <= lastCol && row >= firstRow && row <= lastRow, err
}
// getSharedForumula find a cell contains the same formula as another cell,
// the "shared" value can be used for the t attribute and the si attribute can
// be used to refer to the cell containing the formula. Two formulas are
// considered to be the same when their respective representations in
// R1C1-reference notation, are the same.
//
// Note that this function not validate ref tag to check the cell if or not in
// allow area, and always return origin shared formula.
func getSharedForumula(xlsx *xlsxWorksheet, si string) string {
for _, r := range xlsx.SheetData.Row {
for _, c := range r.C {
if c.F != nil && c.F.Ref != "" && c.F.T == STCellFormulaTypeShared && c.F.Si == si {
return c.F.Content
}
}
}
return ""
}
... ...
// Copyright 2016 - 2019 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 files. Support reads and writes XLSX file generated by
// Microsoft Excel™ 2007 and later. Support save file without losing original
// charts of XLSX. This library needs Go version 1.10 or later.
package excelize
import "strings"
// GetMergeCells provides a function to get all merged cells from a worksheet
// currently.
func (f *File) GetMergeCells(sheet string) ([]MergeCell, error) {
var mergeCells []MergeCell
xlsx, err := f.workSheetReader(sheet)
if err != nil {
return mergeCells, err
}
if xlsx.MergeCells != nil {
mergeCells = make([]MergeCell, 0, len(xlsx.MergeCells.Cells))
for i := range xlsx.MergeCells.Cells {
ref := xlsx.MergeCells.Cells[i].Ref
axis := strings.Split(ref, ":")[0]
val, _ := f.GetCellValue(sheet, axis)
mergeCells = append(mergeCells, []string{ref, val})
}
}
return mergeCells, err
}
// MergeCell define a merged cell data.
// It consists of the following structure.
// example: []string{"D4:E10", "cell value"}
type MergeCell []string
// GetCellValue returns merged cell value.
func (m *MergeCell) GetCellValue() string {
return (*m)[1]
}
// GetStartAxis returns the merge start axis.
// example: "C2"
func (m *MergeCell) GetStartAxis() string {
axis := strings.Split((*m)[0], ":")
return axis[0]
}
// GetEndAxis returns the merge end axis.
// example: "D4"
func (m *MergeCell) GetEndAxis() string {
axis := strings.Split((*m)[0], ":")
return axis[1]
}
... ...
// Copyright 2016 - 2019 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 files. Support reads and writes XLSX file generated by
// Microsoft Excel™ 2007 and later. Support save file without losing original
// charts of XLSX. This library needs Go version 1.10 or later.
package excelize
import (
"encoding/json"
"encoding/xml"
"errors"
"strconv"
"strings"
)
// This section defines the currently supported chart types.
const (
Area = "area"
AreaStacked = "areaStacked"
AreaPercentStacked = "areaPercentStacked"
Area3D = "area3D"
Area3DStacked = "area3DStacked"
Area3DPercentStacked = "area3DPercentStacked"
Bar = "bar"
BarStacked = "barStacked"
BarPercentStacked = "barPercentStacked"
Bar3DClustered = "bar3DClustered"
Bar3DStacked = "bar3DStacked"
Bar3DPercentStacked = "bar3DPercentStacked"
Bar3DConeClustered = "bar3DConeClustered"
Bar3DConeStacked = "bar3DConeStacked"
Bar3DConePercentStacked = "bar3DConePercentStacked"
Bar3DPyramidClustered = "bar3DPyramidClustered"
Bar3DPyramidStacked = "bar3DPyramidStacked"
Bar3DPyramidPercentStacked = "bar3DPyramidPercentStacked"
Bar3DCylinderClustered = "bar3DCylinderClustered"
Bar3DCylinderStacked = "bar3DCylinderStacked"
Bar3DCylinderPercentStacked = "bar3DCylinderPercentStacked"
Col = "col"
ColStacked = "colStacked"
ColPercentStacked = "colPercentStacked"
Col3D = "col3D"
Col3DClustered = "col3DClustered"
Col3DStacked = "col3DStacked"
Col3DPercentStacked = "col3DPercentStacked"
Col3DCone = "col3DCone"
Col3DConeClustered = "col3DConeClustered"
Col3DConeStacked = "col3DConeStacked"
Col3DConePercentStacked = "col3DConePercentStacked"
Col3DPyramid = "col3DPyramid"
Col3DPyramidClustered = "col3DPyramidClustered"
Col3DPyramidStacked = "col3DPyramidStacked"
Col3DPyramidPercentStacked = "col3DPyramidPercentStacked"
Col3DCylinder = "col3DCylinder"
Col3DCylinderClustered = "col3DCylinderClustered"
Col3DCylinderStacked = "col3DCylinderStacked"
Col3DCylinderPercentStacked = "col3DCylinderPercentStacked"
Doughnut = "doughnut"
Line = "line"
Pie = "pie"
Pie3D = "pie3D"
Radar = "radar"
Scatter = "scatter"
Surface3D = "surface3D"
WireframeSurface3D = "wireframeSurface3D"
Contour = "contour"
WireframeContour = "wireframeContour"
Bubble = "bubble"
Bubble3D = "bubble3D"
)
// This section defines the default value of chart properties.
var (
chartView3DRotX = map[string]int{
Area: 0,
AreaStacked: 0,
AreaPercentStacked: 0,
Area3D: 15,
Area3DStacked: 15,
Area3DPercentStacked: 15,
Bar: 0,
BarStacked: 0,
BarPercentStacked: 0,
Bar3DClustered: 15,
Bar3DStacked: 15,
Bar3DPercentStacked: 15,
Bar3DConeClustered: 15,
Bar3DConeStacked: 15,
Bar3DConePercentStacked: 15,
Bar3DPyramidClustered: 15,
Bar3DPyramidStacked: 15,
Bar3DPyramidPercentStacked: 15,
Bar3DCylinderClustered: 15,
Bar3DCylinderStacked: 15,
Bar3DCylinderPercentStacked: 15,
Col: 0,
ColStacked: 0,
ColPercentStacked: 0,
Col3D: 15,
Col3DClustered: 15,
Col3DStacked: 15,
Col3DPercentStacked: 15,
Col3DCone: 15,
Col3DConeClustered: 15,
Col3DConeStacked: 15,
Col3DConePercentStacked: 15,
Col3DPyramid: 15,
Col3DPyramidClustered: 15,
Col3DPyramidStacked: 15,
Col3DPyramidPercentStacked: 15,
Col3DCylinder: 15,
Col3DCylinderClustered: 15,
Col3DCylinderStacked: 15,
Col3DCylinderPercentStacked: 15,
Doughnut: 0,
Line: 0,
Pie: 0,
Pie3D: 30,
Radar: 0,
Scatter: 0,
Surface3D: 15,
WireframeSurface3D: 15,
Contour: 90,
WireframeContour: 90,
}
chartView3DRotY = map[string]int{
Area: 0,
AreaStacked: 0,
AreaPercentStacked: 0,
Area3D: 20,
Area3DStacked: 20,
Area3DPercentStacked: 20,
Bar: 0,
BarStacked: 0,
BarPercentStacked: 0,
Bar3DClustered: 20,
Bar3DStacked: 20,
Bar3DPercentStacked: 20,
Bar3DConeClustered: 20,
Bar3DConeStacked: 20,
Bar3DConePercentStacked: 20,
Bar3DPyramidClustered: 20,
Bar3DPyramidStacked: 20,
Bar3DPyramidPercentStacked: 20,
Bar3DCylinderClustered: 20,
Bar3DCylinderStacked: 20,
Bar3DCylinderPercentStacked: 20,
Col: 0,
ColStacked: 0,
ColPercentStacked: 0,
Col3D: 20,
Col3DClustered: 20,
Col3DStacked: 20,
Col3DPercentStacked: 20,
Col3DCone: 20,
Col3DConeClustered: 20,
Col3DConeStacked: 20,
Col3DConePercentStacked: 20,
Col3DPyramid: 20,
Col3DPyramidClustered: 20,
Col3DPyramidStacked: 20,
Col3DPyramidPercentStacked: 20,
Col3DCylinder: 20,
Col3DCylinderClustered: 20,
Col3DCylinderStacked: 20,
Col3DCylinderPercentStacked: 20,
Doughnut: 0,
Line: 0,
Pie: 0,
Pie3D: 0,
Radar: 0,
Scatter: 0,
Surface3D: 20,
WireframeSurface3D: 20,
Contour: 0,
WireframeContour: 0,
}
plotAreaChartOverlap = map[string]int{
BarStacked: 100,
BarPercentStacked: 100,
ColStacked: 100,
ColPercentStacked: 100,
}
chartView3DPerspective = map[string]int{
Contour: 0,
WireframeContour: 0,
}
chartView3DRAngAx = map[string]int{
Area: 0,
AreaStacked: 0,
AreaPercentStacked: 0,
Area3D: 1,
Area3DStacked: 1,
Area3DPercentStacked: 1,
Bar: 0,
BarStacked: 0,
BarPercentStacked: 0,
Bar3DClustered: 1,
Bar3DStacked: 1,
Bar3DPercentStacked: 1,
Bar3DConeClustered: 1,
Bar3DConeStacked: 1,
Bar3DConePercentStacked: 1,
Bar3DPyramidClustered: 1,
Bar3DPyramidStacked: 1,
Bar3DPyramidPercentStacked: 1,
Bar3DCylinderClustered: 1,
Bar3DCylinderStacked: 1,
Bar3DCylinderPercentStacked: 1,
Col: 0,
ColStacked: 0,
ColPercentStacked: 0,
Col3D: 1,
Col3DClustered: 1,
Col3DStacked: 1,
Col3DPercentStacked: 1,
Col3DCone: 1,
Col3DConeClustered: 1,
Col3DConeStacked: 1,
Col3DConePercentStacked: 1,
Col3DPyramid: 1,
Col3DPyramidClustered: 1,
Col3DPyramidStacked: 1,
Col3DPyramidPercentStacked: 1,
Col3DCylinder: 1,
Col3DCylinderClustered: 1,
Col3DCylinderStacked: 1,
Col3DCylinderPercentStacked: 1,
Doughnut: 0,
Line: 0,
Pie: 0,
Pie3D: 0,
Radar: 0,
Scatter: 0,
Surface3D: 0,
WireframeSurface3D: 0,
Contour: 0,
Bubble: 0,
Bubble3D: 0,
}
chartLegendPosition = map[string]string{
"bottom": "b",
"left": "l",
"right": "r",
"top": "t",
"top_right": "tr",
}
chartValAxNumFmtFormatCode = map[string]string{
Area: "General",
AreaStacked: "General",
AreaPercentStacked: "0%",
Area3D: "General",
Area3DStacked: "General",
Area3DPercentStacked: "0%",
Bar: "General",
BarStacked: "General",
BarPercentStacked: "0%",
Bar3DClustered: "General",
Bar3DStacked: "General",
Bar3DPercentStacked: "0%",
Bar3DConeClustered: "General",
Bar3DConeStacked: "General",
Bar3DConePercentStacked: "0%",
Bar3DPyramidClustered: "General",
Bar3DPyramidStacked: "General",
Bar3DPyramidPercentStacked: "0%",
Bar3DCylinderClustered: "General",
Bar3DCylinderStacked: "General",
Bar3DCylinderPercentStacked: "0%",
Col: "General",
ColStacked: "General",
ColPercentStacked: "0%",
Col3D: "General",
Col3DClustered: "General",
Col3DStacked: "General",
Col3DPercentStacked: "0%",
Col3DCone: "General",
Col3DConeClustered: "General",
Col3DConeStacked: "General",
Col3DConePercentStacked: "0%",
Col3DPyramid: "General",
Col3DPyramidClustered: "General",
Col3DPyramidStacked: "General",
Col3DPyramidPercentStacked: "0%",
Col3DCylinder: "General",
Col3DCylinderClustered: "General",
Col3DCylinderStacked: "General",
Col3DCylinderPercentStacked: "0%",
Doughnut: "General",
Line: "General",
Pie: "General",
Pie3D: "General",
Radar: "General",
Scatter: "General",
Surface3D: "General",
WireframeSurface3D: "General",
Contour: "General",
WireframeContour: "General",
Bubble: "General",
Bubble3D: "General",
}
chartValAxCrossBetween = map[string]string{
Area: "midCat",
AreaStacked: "midCat",
AreaPercentStacked: "midCat",
Area3D: "midCat",
Area3DStacked: "midCat",
Area3DPercentStacked: "midCat",
Bar: "between",
BarStacked: "between",
BarPercentStacked: "between",
Bar3DClustered: "between",
Bar3DStacked: "between",
Bar3DPercentStacked: "between",
Bar3DConeClustered: "between",
Bar3DConeStacked: "between",
Bar3DConePercentStacked: "between",
Bar3DPyramidClustered: "between",
Bar3DPyramidStacked: "between",
Bar3DPyramidPercentStacked: "between",
Bar3DCylinderClustered: "between",
Bar3DCylinderStacked: "between",
Bar3DCylinderPercentStacked: "between",
Col: "between",
ColStacked: "between",
ColPercentStacked: "between",
Col3D: "between",
Col3DClustered: "between",
Col3DStacked: "between",
Col3DPercentStacked: "between",
Col3DCone: "between",
Col3DConeClustered: "between",
Col3DConeStacked: "between",
Col3DConePercentStacked: "between",
Col3DPyramid: "between",
Col3DPyramidClustered: "between",
Col3DPyramidStacked: "between",
Col3DPyramidPercentStacked: "between",
Col3DCylinder: "between",
Col3DCylinderClustered: "between",
Col3DCylinderStacked: "between",
Col3DCylinderPercentStacked: "between",
Doughnut: "between",
Line: "between",
Pie: "between",
Pie3D: "between",
Radar: "between",
Scatter: "between",
Surface3D: "midCat",
WireframeSurface3D: "midCat",
Contour: "midCat",
WireframeContour: "midCat",
Bubble: "midCat",
Bubble3D: "midCat",
}
plotAreaChartGrouping = map[string]string{
Area: "standard",
AreaStacked: "stacked",
AreaPercentStacked: "percentStacked",
Area3D: "standard",
Area3DStacked: "stacked",
Area3DPercentStacked: "percentStacked",
Bar: "clustered",
BarStacked: "stacked",
BarPercentStacked: "percentStacked",
Bar3DClustered: "clustered",
Bar3DStacked: "stacked",
Bar3DPercentStacked: "percentStacked",
Bar3DConeClustered: "clustered",
Bar3DConeStacked: "stacked",
Bar3DConePercentStacked: "percentStacked",
Bar3DPyramidClustered: "clustered",
Bar3DPyramidStacked: "stacked",
Bar3DPyramidPercentStacked: "percentStacked",
Bar3DCylinderClustered: "clustered",
Bar3DCylinderStacked: "stacked",
Bar3DCylinderPercentStacked: "percentStacked",
Col: "clustered",
ColStacked: "stacked",
ColPercentStacked: "percentStacked",
Col3D: "standard",
Col3DClustered: "clustered",
Col3DStacked: "stacked",
Col3DPercentStacked: "percentStacked",
Col3DCone: "standard",
Col3DConeClustered: "clustered",
Col3DConeStacked: "stacked",
Col3DConePercentStacked: "percentStacked",
Col3DPyramid: "standard",
Col3DPyramidClustered: "clustered",
Col3DPyramidStacked: "stacked",
Col3DPyramidPercentStacked: "percentStacked",
Col3DCylinder: "standard",
Col3DCylinderClustered: "clustered",
Col3DCylinderStacked: "stacked",
Col3DCylinderPercentStacked: "percentStacked",
Line: "standard",
}
plotAreaChartBarDir = map[string]string{
Bar: "bar",
BarStacked: "bar",
BarPercentStacked: "bar",
Bar3DClustered: "bar",
Bar3DStacked: "bar",
Bar3DPercentStacked: "bar",
Bar3DConeClustered: "bar",
Bar3DConeStacked: "bar",
Bar3DConePercentStacked: "bar",
Bar3DPyramidClustered: "bar",
Bar3DPyramidStacked: "bar",
Bar3DPyramidPercentStacked: "bar",
Bar3DCylinderClustered: "bar",
Bar3DCylinderStacked: "bar",
Bar3DCylinderPercentStacked: "bar",
Col: "col",
ColStacked: "col",
ColPercentStacked: "col",
Col3D: "col",
Col3DClustered: "col",
Col3DStacked: "col",
Col3DPercentStacked: "col",
Col3DCone: "col",
Col3DConeStacked: "col",
Col3DConeClustered: "col",
Col3DConePercentStacked: "col",
Col3DPyramid: "col",
Col3DPyramidClustered: "col",
Col3DPyramidStacked: "col",
Col3DPyramidPercentStacked: "col",
Col3DCylinder: "col",
Col3DCylinderClustered: "col",
Col3DCylinderStacked: "col",
Col3DCylinderPercentStacked: "col",
Line: "standard",
}
orientation = map[bool]string{
true: "maxMin",
false: "minMax",
}
catAxPos = map[bool]string{
true: "t",
false: "b",
}
valAxPos = map[bool]string{
true: "r",
false: "l",
}
valTickLblPos = map[string]string{
Contour: "none",
WireframeContour: "none",
}
)
// parseFormatChartSet provides a function to parse the format settings of the
// chart with default value.
func parseFormatChartSet(formatSet string) (*formatChart, error) {
format := formatChart{
Dimension: formatChartDimension{
Width: 480,
Height: 290,
},
Format: formatPicture{
FPrintsWithSheet: true,
FLocksWithSheet: false,
NoChangeAspect: false,
OffsetX: 0,
OffsetY: 0,
XScale: 1.0,
YScale: 1.0,
},
Legend: formatChartLegend{
Position: "bottom",
ShowLegendKey: false,
},
Title: formatChartTitle{
Name: " ",
},
ShowBlanksAs: "gap",
}
err := json.Unmarshal([]byte(formatSet), &format)
return &format, err
}
// AddChart provides the method to add chart in a sheet by given chart format
// set (such as offset, scale, aspect ratio setting and print settings) and
// properties set. For example, create 3D clustered column chart with data
// Sheet1!$A$29:$D$32:
//
// 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)
// }
// err := f.AddChart("Sheet1", "E1", `{"type":"col3DClustered","dimension":{"width":640,"height":480},"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"}],"format":{"x_scale":1.0,"y_scale":1.0,"x_offset":15,"y_offset":10,"print_obj":true,"lock_aspect_ratio":false,"locked":false},"legend":{"position":"bottom","show_legend_key":false},"title":{"name":"Fruit 3D Clustered Column Chart"},"plotarea":{"show_bubble_size":true,"show_cat_name":false,"show_leader_lines":false,"show_percent":true,"show_series_name":true,"show_val":true},"show_blanks_as":"zero","x_axis":{"reverse_order":true},"y_axis":{"maximum":7.5,"minimum":0.5}}`)
// if err != nil {
// fmt.Println(err)
// return
// }
// // Save xlsx file by the given path.
// err = xlsx.SaveAs("./Book1.xlsx")
// if err != nil {
// fmt.Println(err)
// }
// }
//
// The following shows the type of chart supported by excelize:
//
// Type | Chart
// -----------------------------+------------------------------
// area | 2D area chart
// areaStacked | 2D stacked area chart
// areaPercentStacked | 2D 100% stacked area chart
// area3D | 3D area chart
// area3DStacked | 3D stacked area chart
// area3DPercentStacked | 3D 100% stacked area chart
// bar | 2D clustered bar chart
// barStacked | 2D stacked bar chart
// barPercentStacked | 2D 100% stacked bar chart
// bar3DClustered | 3D clustered bar chart
// bar3DStacked | 3D stacked bar chart
// bar3DPercentStacked | 3D 100% stacked bar chart
// bar3DConeClustered | 3D cone clustered bar chart
// bar3DConeStacked | 3D cone stacked bar chart
// bar3DConePercentStacked | 3D cone percent bar chart
// bar3DPyramidClustered | 3D pyramid clustered bar chart
// bar3DPyramidStacked | 3D pyramid stacked bar chart
// bar3DPyramidPercentStacked | 3D pyramid percent stacked bar chart
// bar3DCylinderClustered | 3D cylinder clustered bar chart
// bar3DCylinderStacked | 3D cylinder stacked bar chart
// bar3DCylinderPercentStacked | 3D cylinder percent stacked bar chart
// col | 2D clustered column chart
// colStacked | 2D stacked column chart
// colPercentStacked | 2D 100% stacked column chart
// col3DClustered | 3D clustered column chart
// col3D | 3D column chart
// col3DStacked | 3D stacked column chart
// col3DPercentStacked | 3D 100% stacked column chart
// col3DCone | 3D cone column chart
// col3DConeClustered | 3D cone clustered column chart
// col3DConeStacked | 3D cone stacked column chart
// col3DConePercentStacked | 3D cone percent stacked column chart
// col3DPyramid | 3D pyramid column chart
// col3DPyramidClustered | 3D pyramid clustered column chart
// col3DPyramidStacked | 3D pyramid stacked column chart
// col3DPyramidPercentStacked | 3D pyramid percent stacked column chart
// col3DCylinder | 3D cylinder column chart
// col3DCylinderClustered | 3D cylinder clustered column chart
// col3DCylinderStacked | 3D cylinder stacked column chart
// col3DCylinderPercentStacked | 3D cylinder percent stacked column chart
// doughnut | doughnut chart
// line | line chart
// pie | pie chart
// pie3D | 3D pie chart
// radar | radar chart
// scatter | scatter chart
// surface3D | 3D surface chart
// wireframeSurface3D | 3D wireframe surface chart
// contour | contour chart
// wireframeContour | wireframe contour chart
// bubble | bubble chart
// bubble3D | 3D bubble chart
//
// In Excel a chart series is a collection of information that defines which data is plotted such as values, axis labels and formatting.
//
// The series options that can be set are:
//
// name
// categories
// values
//
// name: Set the name for the series. The name is displayed in the chart legend and in the formula bar. The name property is optional and if it isn't supplied it will default to Series 1..n. The name can also be a formula such as Sheet1!$A$1
//
// categories: This sets the chart category labels. The category is more or less the same as the X axis. In most chart types the categories property is optional and the chart will just assume a sequential series from 1..n.
//
// values: This is the most important property of a series and is the only mandatory option for every chart object. This option links the chart with the worksheet data that it displays.
//
// Set properties of the chart legend. The options that can be set are:
//
// position
// show_legend_key
//
// position: Set the position of the chart legend. The default legend position is right. The available positions are:
//
// top
// bottom
// left
// right
// top_right
//
// show_legend_key: Set the legend keys shall be shown in data labels. The default value is false.
//
// Set properties of the chart title. The properties that can be set are:
//
// title
//
// name: Set the name (title) for the chart. The name is displayed above the chart. The name can also be a formula such as Sheet1!$A$1 or a list with a sheetname. The name property is optional. The default is to have no chart title.
//
// Specifies how blank cells are plotted on the chart by show_blanks_as. The default value is gap. The options that can be set are:
//
// gap
// span
// zero
//
// gap: Specifies that blank values shall be left as a gap.
//
// sapn: Specifies that blank values shall be spanned with a line.
//
// zero: Specifies that blank values shall be treated as zero.
//
// Set chart offset, scale, aspect ratio setting and print settings by format, same as function AddPicture.
//
// Set the position of the chart plot area by plotarea. The properties that can be set are:
//
// show_bubble_size
// show_cat_name
// show_leader_lines
// show_percent
// show_series_name
// show_val
//
// show_bubble_size: Specifies the bubble size shall be shown in a data label. The show_bubble_size property is optional. The default value is false.
//
// show_cat_name: Specifies that the category name shall be shown in the data label. The show_cat_name property is optional. The default value is true.
//
// show_leader_lines: Specifies leader lines shall be shown for data labels. The show_leader_lines property is optional. The default value is false.
//
// show_percent: Specifies that the percentage shall be shown in a data label. The show_percent property is optional. The default value is false.
//
// show_series_name: Specifies that the series name shall be shown in a data label. The show_series_name property is optional. The default value is false.
//
// show_val: Specifies that the value shall be shown in a data label. The show_val property is optional. The default value is false.
//
// Set the primary horizontal and vertical axis options by x_axis and y_axis. The properties that can be set are:
//
// reverse_order
// maximum
// minimum
//
// reverse_order: Specifies that the categories or values on reverse order (orientation of the chart). The reverse_order property is optional. The default value is false.
//
// maximum: Specifies that the fixed maximum, 0 is auto. The maximum property is optional. The default value is auto.
//
// minimum: Specifies that the fixed minimum, 0 is auto. The minimum property is optional. The default value is auto.
//
// Set chart size by dimension property. The dimension property is optional. The default width is 480, and height is 290.
//
func (f *File) AddChart(sheet, cell, format string) error {
formatSet, err := parseFormatChartSet(format)
if err != nil {
return err
}
// Read sheet data.
xlsx, err := f.workSheetReader(sheet)
if err != nil {
return err
}
if _, ok := chartValAxNumFmtFormatCode[formatSet.Type]; !ok {
return errors.New("unsupported chart type " + formatSet.Type)
}
// Add first picture for given sheet, create xl/drawings/ and xl/drawings/_rels/ folder.
drawingID := f.countDrawings() + 1
chartID := f.countCharts() + 1
drawingXML := "xl/drawings/drawing" + strconv.Itoa(drawingID) + ".xml"
drawingID, drawingXML = f.prepareDrawing(xlsx, drawingID, sheet, drawingXML)
drawingRels := "xl/drawings/_rels/drawing" + strconv.Itoa(drawingID) + ".xml.rels"
drawingRID := f.addRels(drawingRels, SourceRelationshipChart, "../charts/chart"+strconv.Itoa(chartID)+".xml", "")
err = f.addDrawingChart(sheet, drawingXML, cell, formatSet.Dimension.Width, formatSet.Dimension.Height, drawingRID, &formatSet.Format)
if err != nil {
return err
}
f.addChart(formatSet)
f.addContentTypePart(chartID, "chart")
f.addContentTypePart(drawingID, "drawings")
return err
}
// countCharts provides a function to get chart files count storage in the
// folder xl/charts.
func (f *File) countCharts() int {
count := 0
for k := range f.XLSX {
if strings.Contains(k, "xl/charts/chart") {
count++
}
}
return count
}
// prepareDrawing provides a function to prepare drawing ID and XML by given
// drawingID, worksheet name and default drawingXML.
func (f *File) prepareDrawing(xlsx *xlsxWorksheet, drawingID int, sheet, drawingXML string) (int, string) {
sheetRelationshipsDrawingXML := "../drawings/drawing" + strconv.Itoa(drawingID) + ".xml"
if xlsx.Drawing != nil {
// The worksheet already has a picture or chart relationships, use the relationships drawing ../drawings/drawing%d.xml.
sheetRelationshipsDrawingXML = f.getSheetRelationshipsTargetByID(sheet, xlsx.Drawing.RID)
drawingID, _ = strconv.Atoi(strings.TrimSuffix(strings.TrimPrefix(sheetRelationshipsDrawingXML, "../drawings/drawing"), ".xml"))
drawingXML = strings.Replace(sheetRelationshipsDrawingXML, "..", "xl", -1)
} else {
// Add first picture for given sheet.
sheetPath, _ := f.sheetMap[trimSheetName(sheet)]
sheetRels := "xl/worksheets/_rels/" + strings.TrimPrefix(sheetPath, "xl/worksheets/") + ".rels"
rID := f.addRels(sheetRels, SourceRelationshipDrawingML, sheetRelationshipsDrawingXML, "")
f.addSheetDrawing(sheet, rID)
}
return drawingID, drawingXML
}
// addChart provides a function to create chart as xl/charts/chart%d.xml by
// given format sets.
func (f *File) addChart(formatSet *formatChart) {
count := f.countCharts()
xlsxChartSpace := xlsxChartSpace{
XMLNSc: NameSpaceDrawingMLChart,
XMLNSa: NameSpaceDrawingML,
XMLNSr: SourceRelationship,
XMLNSc16r2: SourceRelationshipChart201506,
Date1904: &attrValBool{Val: false},
Lang: &attrValString{Val: "en-US"},
RoundedCorners: &attrValBool{Val: false},
Chart: cChart{
Title: &cTitle{
Tx: cTx{
Rich: &cRich{
P: aP{
PPr: &aPPr{
DefRPr: aRPr{
Kern: 1200,
Strike: "noStrike",
U: "none",
Sz: 1400,
SolidFill: &aSolidFill{
SchemeClr: &aSchemeClr{
Val: "tx1",
LumMod: &attrValInt{
Val: 65000,
},
LumOff: &attrValInt{
Val: 35000,
},
},
},
Ea: &aEa{
Typeface: "+mn-ea",
},
Cs: &aCs{
Typeface: "+mn-cs",
},
Latin: &aLatin{
Typeface: "+mn-lt",
},
},
},
R: &aR{
RPr: aRPr{
Lang: "en-US",
AltLang: "en-US",
},
T: formatSet.Title.Name,
},
},
},
},
TxPr: cTxPr{
P: aP{
PPr: &aPPr{
DefRPr: aRPr{
Kern: 1200,
U: "none",
Sz: 14000,
Strike: "noStrike",
},
},
EndParaRPr: &aEndParaRPr{
Lang: "en-US",
},
},
},
},
View3D: &cView3D{
RotX: &attrValInt{Val: chartView3DRotX[formatSet.Type]},
RotY: &attrValInt{Val: chartView3DRotY[formatSet.Type]},
Perspective: &attrValInt{Val: chartView3DPerspective[formatSet.Type]},
RAngAx: &attrValInt{Val: chartView3DRAngAx[formatSet.Type]},
},
Floor: &cThicknessSpPr{
Thickness: &attrValInt{Val: 0},
},
SideWall: &cThicknessSpPr{
Thickness: &attrValInt{Val: 0},
},
BackWall: &cThicknessSpPr{
Thickness: &attrValInt{Val: 0},
},
PlotArea: &cPlotArea{},
Legend: &cLegend{
LegendPos: &attrValString{Val: chartLegendPosition[formatSet.Legend.Position]},
Overlay: &attrValBool{Val: false},
},
PlotVisOnly: &attrValBool{Val: false},
DispBlanksAs: &attrValString{Val: formatSet.ShowBlanksAs},
ShowDLblsOverMax: &attrValBool{Val: false},
},
SpPr: &cSpPr{
SolidFill: &aSolidFill{
SchemeClr: &aSchemeClr{Val: "bg1"},
},
Ln: &aLn{
W: 9525,
Cap: "flat",
Cmpd: "sng",
Algn: "ctr",
SolidFill: &aSolidFill{
SchemeClr: &aSchemeClr{Val: "tx1",
LumMod: &attrValInt{
Val: 15000,
},
LumOff: &attrValInt{
Val: 85000,
},
},
},
},
},
PrintSettings: &cPrintSettings{
PageMargins: &cPageMargins{
B: 0.75,
L: 0.7,
R: 0.7,
T: 0.7,
Header: 0.3,
Footer: 0.3,
},
},
}
plotAreaFunc := map[string]func(*formatChart) *cPlotArea{
Area: f.drawBaseChart,
AreaStacked: f.drawBaseChart,
AreaPercentStacked: f.drawBaseChart,
Area3D: f.drawBaseChart,
Area3DStacked: f.drawBaseChart,
Area3DPercentStacked: f.drawBaseChart,
Bar: f.drawBaseChart,
BarStacked: f.drawBaseChart,
BarPercentStacked: f.drawBaseChart,
Bar3DClustered: f.drawBaseChart,
Bar3DStacked: f.drawBaseChart,
Bar3DPercentStacked: f.drawBaseChart,
Bar3DConeClustered: f.drawBaseChart,
Bar3DConeStacked: f.drawBaseChart,
Bar3DConePercentStacked: f.drawBaseChart,
Bar3DPyramidClustered: f.drawBaseChart,
Bar3DPyramidStacked: f.drawBaseChart,
Bar3DPyramidPercentStacked: f.drawBaseChart,
Bar3DCylinderClustered: f.drawBaseChart,
Bar3DCylinderStacked: f.drawBaseChart,
Bar3DCylinderPercentStacked: f.drawBaseChart,
Col: f.drawBaseChart,
ColStacked: f.drawBaseChart,
ColPercentStacked: f.drawBaseChart,
Col3D: f.drawBaseChart,
Col3DClustered: f.drawBaseChart,
Col3DStacked: f.drawBaseChart,
Col3DPercentStacked: f.drawBaseChart,
Col3DCone: f.drawBaseChart,
Col3DConeClustered: f.drawBaseChart,
Col3DConeStacked: f.drawBaseChart,
Col3DConePercentStacked: f.drawBaseChart,
Col3DPyramid: f.drawBaseChart,
Col3DPyramidClustered: f.drawBaseChart,
Col3DPyramidStacked: f.drawBaseChart,
Col3DPyramidPercentStacked: f.drawBaseChart,
Col3DCylinder: f.drawBaseChart,
Col3DCylinderClustered: f.drawBaseChart,
Col3DCylinderStacked: f.drawBaseChart,
Col3DCylinderPercentStacked: f.drawBaseChart,
Doughnut: f.drawDoughnutChart,
Line: f.drawLineChart,
Pie3D: f.drawPie3DChart,
Pie: f.drawPieChart,
Radar: f.drawRadarChart,
Scatter: f.drawScatterChart,
Surface3D: f.drawSurface3DChart,
WireframeSurface3D: f.drawSurface3DChart,
Contour: f.drawSurfaceChart,
WireframeContour: f.drawSurfaceChart,
Bubble: f.drawBaseChart,
Bubble3D: f.drawBaseChart,
}
xlsxChartSpace.Chart.PlotArea = plotAreaFunc[formatSet.Type](formatSet)
chart, _ := xml.Marshal(xlsxChartSpace)
media := "xl/charts/chart" + strconv.Itoa(count+1) + ".xml"
f.saveFileList(media, chart)
}
// drawBaseChart provides a function to draw the c:plotArea element for bar,
// and column series charts by given format sets.
func (f *File) drawBaseChart(formatSet *formatChart) *cPlotArea {
c := cCharts{
BarDir: &attrValString{
Val: "col",
},
Grouping: &attrValString{
Val: "clustered",
},
VaryColors: &attrValBool{
Val: true,
},
Ser: f.drawChartSeries(formatSet),
Shape: f.drawChartShape(formatSet),
DLbls: f.drawChartDLbls(formatSet),
AxID: []*attrValInt{
{Val: 754001152},
{Val: 753999904},
},
Overlap: &attrValInt{Val: 100},
}
var ok bool
if c.BarDir.Val, ok = plotAreaChartBarDir[formatSet.Type]; !ok {
c.BarDir = nil
}
if c.Grouping.Val, ok = plotAreaChartGrouping[formatSet.Type]; !ok {
c.Grouping = nil
}
if c.Overlap.Val, ok = plotAreaChartOverlap[formatSet.Type]; !ok {
c.Overlap = nil
}
catAx := f.drawPlotAreaCatAx(formatSet)
valAx := f.drawPlotAreaValAx(formatSet)
charts := map[string]*cPlotArea{
"area": {
AreaChart: &c,
CatAx: catAx,
ValAx: valAx,
},
"areaStacked": {
AreaChart: &c,
CatAx: catAx,
ValAx: valAx,
},
"areaPercentStacked": {
AreaChart: &c,
CatAx: catAx,
ValAx: valAx,
},
"area3D": {
Area3DChart: &c,
CatAx: catAx,
ValAx: valAx,
},
"area3DStacked": {
Area3DChart: &c,
CatAx: catAx,
ValAx: valAx,
},
"area3DPercentStacked": {
Area3DChart: &c,
CatAx: catAx,
ValAx: valAx,
},
"bar": {
BarChart: &c,
CatAx: catAx,
ValAx: valAx,
},
"barStacked": {
BarChart: &c,
CatAx: catAx,
ValAx: valAx,
},
"barPercentStacked": {
BarChart: &c,
CatAx: catAx,
ValAx: valAx,
},
"bar3DClustered": {
Bar3DChart: &c,
CatAx: catAx,
ValAx: valAx,
},
"bar3DStacked": {
Bar3DChart: &c,
CatAx: catAx,
ValAx: valAx,
},
"bar3DPercentStacked": {
Bar3DChart: &c,
CatAx: catAx,
ValAx: valAx,
},
"bar3DConeClustered": {
Bar3DChart: &c,
CatAx: catAx,
ValAx: valAx,
},
"bar3DConeStacked": {
Bar3DChart: &c,
CatAx: catAx,
ValAx: valAx,
},
"bar3DConePercentStacked": {
Bar3DChart: &c,
CatAx: catAx,
ValAx: valAx,
},
"bar3DPyramidClustered": {
Bar3DChart: &c,
CatAx: catAx,
ValAx: valAx,
},
"bar3DPyramidStacked": {
Bar3DChart: &c,
CatAx: catAx,
ValAx: valAx,
},
"bar3DPyramidPercentStacked": {
Bar3DChart: &c,
CatAx: catAx,
ValAx: valAx,
},
"bar3DCylinderClustered": {
Bar3DChart: &c,
CatAx: catAx,
ValAx: valAx,
},
"bar3DCylinderStacked": {
Bar3DChart: &c,
CatAx: catAx,
ValAx: valAx,
},
"bar3DCylinderPercentStacked": {
Bar3DChart: &c,
CatAx: catAx,
ValAx: valAx,
},
"col": {
BarChart: &c,
CatAx: catAx,
ValAx: valAx,
},
"colStacked": {
BarChart: &c,
CatAx: catAx,
ValAx: valAx,
},
"colPercentStacked": {
BarChart: &c,
CatAx: catAx,
ValAx: valAx,
},
"col3D": {
Bar3DChart: &c,
CatAx: catAx,
ValAx: valAx,
},
"col3DClustered": {
Bar3DChart: &c,
CatAx: catAx,
ValAx: valAx,
},
"col3DStacked": {
Bar3DChart: &c,
CatAx: catAx,
ValAx: valAx,
},
"col3DPercentStacked": {
Bar3DChart: &c,
CatAx: catAx,
ValAx: valAx,
},
"col3DCone": {
Bar3DChart: &c,
CatAx: catAx,
ValAx: valAx,
},
"col3DConeClustered": {
Bar3DChart: &c,
CatAx: catAx,
ValAx: valAx,
},
"col3DConeStacked": {
Bar3DChart: &c,
CatAx: catAx,
ValAx: valAx,
},
"col3DConePercentStacked": {
Bar3DChart: &c,
CatAx: catAx,
ValAx: valAx,
},
"col3DPyramid": {
Bar3DChart: &c,
CatAx: catAx,
ValAx: valAx,
},
"col3DPyramidClustered": {
Bar3DChart: &c,
CatAx: catAx,
ValAx: valAx,
},
"col3DPyramidStacked": {
Bar3DChart: &c,
CatAx: catAx,
ValAx: valAx,
},
"col3DPyramidPercentStacked": {
Bar3DChart: &c,
CatAx: catAx,
ValAx: valAx,
},
"col3DCylinder": {
Bar3DChart: &c,
CatAx: catAx,
ValAx: valAx,
},
"col3DCylinderClustered": {
Bar3DChart: &c,
CatAx: catAx,
ValAx: valAx,
},
"col3DCylinderStacked": {
Bar3DChart: &c,
CatAx: catAx,
ValAx: valAx,
},
"col3DCylinderPercentStacked": {
Bar3DChart: &c,
CatAx: catAx,
ValAx: valAx,
},
"bubble": {
BubbleChart: &c,
CatAx: catAx,
ValAx: valAx,
},
"bubble3D": {
BubbleChart: &c,
CatAx: catAx,
ValAx: valAx,
},
}
return charts[formatSet.Type]
}
// drawDoughnutChart provides a function to draw the c:plotArea element for
// doughnut chart by given format sets.
func (f *File) drawDoughnutChart(formatSet *formatChart) *cPlotArea {
return &cPlotArea{
DoughnutChart: &cCharts{
VaryColors: &attrValBool{
Val: true,
},
Ser: f.drawChartSeries(formatSet),
HoleSize: &attrValInt{Val: 75},
},
}
}
// drawLineChart provides a function to draw the c:plotArea element for line
// chart by given format sets.
func (f *File) drawLineChart(formatSet *formatChart) *cPlotArea {
return &cPlotArea{
LineChart: &cCharts{
Grouping: &attrValString{
Val: plotAreaChartGrouping[formatSet.Type],
},
VaryColors: &attrValBool{
Val: false,
},
Ser: f.drawChartSeries(formatSet),
DLbls: f.drawChartDLbls(formatSet),
Smooth: &attrValBool{
Val: false,
},
AxID: []*attrValInt{
{Val: 754001152},
{Val: 753999904},
},
},
CatAx: f.drawPlotAreaCatAx(formatSet),
ValAx: f.drawPlotAreaValAx(formatSet),
}
}
// drawPieChart provides a function to draw the c:plotArea element for pie
// chart by given format sets.
func (f *File) drawPieChart(formatSet *formatChart) *cPlotArea {
return &cPlotArea{
PieChart: &cCharts{
VaryColors: &attrValBool{
Val: true,
},
Ser: f.drawChartSeries(formatSet),
},
}
}
// drawPie3DChart provides a function to draw the c:plotArea element for 3D
// pie chart by given format sets.
func (f *File) drawPie3DChart(formatSet *formatChart) *cPlotArea {
return &cPlotArea{
Pie3DChart: &cCharts{
VaryColors: &attrValBool{
Val: true,
},
Ser: f.drawChartSeries(formatSet),
},
}
}
// drawRadarChart provides a function to draw the c:plotArea element for radar
// chart by given format sets.
func (f *File) drawRadarChart(formatSet *formatChart) *cPlotArea {
return &cPlotArea{
RadarChart: &cCharts{
RadarStyle: &attrValString{
Val: "marker",
},
VaryColors: &attrValBool{
Val: false,
},
Ser: f.drawChartSeries(formatSet),
DLbls: f.drawChartDLbls(formatSet),
AxID: []*attrValInt{
{Val: 754001152},
{Val: 753999904},
},
},
CatAx: f.drawPlotAreaCatAx(formatSet),
ValAx: f.drawPlotAreaValAx(formatSet),
}
}
// drawScatterChart provides a function to draw the c:plotArea element for
// scatter chart by given format sets.
func (f *File) drawScatterChart(formatSet *formatChart) *cPlotArea {
return &cPlotArea{
ScatterChart: &cCharts{
ScatterStyle: &attrValString{
Val: "smoothMarker", // line,lineMarker,marker,none,smooth,smoothMarker
},
VaryColors: &attrValBool{
Val: false,
},
Ser: f.drawChartSeries(formatSet),
DLbls: f.drawChartDLbls(formatSet),
AxID: []*attrValInt{
{Val: 754001152},
{Val: 753999904},
},
},
CatAx: f.drawPlotAreaCatAx(formatSet),
ValAx: f.drawPlotAreaValAx(formatSet),
}
}
// drawSurface3DChart provides a function to draw the c:surface3DChart element by
// given format sets.
func (f *File) drawSurface3DChart(formatSet *formatChart) *cPlotArea {
plotArea := &cPlotArea{
Surface3DChart: &cCharts{
Ser: f.drawChartSeries(formatSet),
AxID: []*attrValInt{
{Val: 754001152},
{Val: 753999904},
{Val: 832256642},
},
},
CatAx: f.drawPlotAreaCatAx(formatSet),
ValAx: f.drawPlotAreaValAx(formatSet),
SerAx: f.drawPlotAreaSerAx(formatSet),
}
if formatSet.Type == WireframeSurface3D {
plotArea.Surface3DChart.Wireframe = &attrValBool{Val: true}
}
return plotArea
}
// drawSurfaceChart provides a function to draw the c:surfaceChart element by
// given format sets.
func (f *File) drawSurfaceChart(formatSet *formatChart) *cPlotArea {
plotArea := &cPlotArea{
SurfaceChart: &cCharts{
Ser: f.drawChartSeries(formatSet),
AxID: []*attrValInt{
{Val: 754001152},
{Val: 753999904},
{Val: 832256642},
},
},
CatAx: f.drawPlotAreaCatAx(formatSet),
ValAx: f.drawPlotAreaValAx(formatSet),
SerAx: f.drawPlotAreaSerAx(formatSet),
}
if formatSet.Type == WireframeContour {
plotArea.SurfaceChart.Wireframe = &attrValBool{Val: true}
}
return plotArea
}
// drawChartShape provides a function to draw the c:shape element by given
// format sets.
func (f *File) drawChartShape(formatSet *formatChart) *attrValString {
shapes := map[string]string{
Bar3DConeClustered: "cone",
Bar3DConeStacked: "cone",
Bar3DConePercentStacked: "cone",
Bar3DPyramidClustered: "pyramid",
Bar3DPyramidStacked: "pyramid",
Bar3DPyramidPercentStacked: "pyramid",
Bar3DCylinderClustered: "cylinder",
Bar3DCylinderStacked: "cylinder",
Bar3DCylinderPercentStacked: "cylinder",
Col3DCone: "cone",
Col3DConeClustered: "cone",
Col3DConeStacked: "cone",
Col3DConePercentStacked: "cone",
Col3DPyramid: "pyramid",
Col3DPyramidClustered: "pyramid",
Col3DPyramidStacked: "pyramid",
Col3DPyramidPercentStacked: "pyramid",
Col3DCylinder: "cylinder",
Col3DCylinderClustered: "cylinder",
Col3DCylinderStacked: "cylinder",
Col3DCylinderPercentStacked: "cylinder",
}
if shape, ok := shapes[formatSet.Type]; ok {
return &attrValString{Val: shape}
}
return nil
}
// drawChartSeries provides a function to draw the c:ser element by given
// format sets.
func (f *File) drawChartSeries(formatSet *formatChart) *[]cSer {
ser := []cSer{}
for k := range formatSet.Series {
ser = append(ser, cSer{
IDx: &attrValInt{Val: k},
Order: &attrValInt{Val: k},
Tx: &cTx{
StrRef: &cStrRef{
F: formatSet.Series[k].Name,
},
},
SpPr: f.drawChartSeriesSpPr(k, formatSet),
Marker: f.drawChartSeriesMarker(k, formatSet),
DPt: f.drawChartSeriesDPt(k, formatSet),
DLbls: f.drawChartSeriesDLbls(formatSet),
Cat: f.drawChartSeriesCat(formatSet.Series[k], formatSet),
Val: f.drawChartSeriesVal(formatSet.Series[k], formatSet),
XVal: f.drawChartSeriesXVal(formatSet.Series[k], formatSet),
YVal: f.drawChartSeriesYVal(formatSet.Series[k], formatSet),
BubbleSize: f.drawCharSeriesBubbleSize(formatSet.Series[k], formatSet),
Bubble3D: f.drawCharSeriesBubble3D(formatSet),
})
}
return &ser
}
// drawChartSeriesSpPr provides a function to draw the c:spPr element by given
// format sets.
func (f *File) drawChartSeriesSpPr(i int, formatSet *formatChart) *cSpPr {
spPrScatter := &cSpPr{
Ln: &aLn{
W: 25400,
NoFill: " ",
},
}
spPrLine := &cSpPr{
Ln: &aLn{
W: 25400,
Cap: "rnd", // rnd, sq, flat
},
}
if i < 6 {
spPrLine.Ln.SolidFill = &aSolidFill{
SchemeClr: &aSchemeClr{Val: "accent" + strconv.Itoa(i+1)},
}
}
chartSeriesSpPr := map[string]*cSpPr{Line: spPrLine, Scatter: spPrScatter}
return chartSeriesSpPr[formatSet.Type]
}
// drawChartSeriesDPt provides a function to draw the c:dPt element by given
// data index and format sets.
func (f *File) drawChartSeriesDPt(i int, formatSet *formatChart) []*cDPt {
dpt := []*cDPt{{
IDx: &attrValInt{Val: i},
Bubble3D: &attrValBool{Val: false},
SpPr: &cSpPr{
SolidFill: &aSolidFill{
SchemeClr: &aSchemeClr{Val: "accent" + strconv.Itoa(i+1)},
},
Ln: &aLn{
W: 25400,
Cap: "rnd",
SolidFill: &aSolidFill{
SchemeClr: &aSchemeClr{Val: "lt" + strconv.Itoa(i+1)},
},
},
Sp3D: &aSp3D{
ContourW: 25400,
ContourClr: &aContourClr{
SchemeClr: &aSchemeClr{Val: "lt" + strconv.Itoa(i+1)},
},
},
},
}}
chartSeriesDPt := map[string][]*cDPt{Pie: dpt, Pie3D: dpt}
return chartSeriesDPt[formatSet.Type]
}
// drawChartSeriesCat provides a function to draw the c:cat element by given
// chart series and format sets.
func (f *File) drawChartSeriesCat(v formatChartSeries, formatSet *formatChart) *cCat {
cat := &cCat{
StrRef: &cStrRef{
F: v.Categories,
},
}
chartSeriesCat := map[string]*cCat{Scatter: nil, Bubble: nil, Bubble3D: nil}
if _, ok := chartSeriesCat[formatSet.Type]; ok {
return nil
}
return cat
}
// drawChartSeriesVal provides a function to draw the c:val element by given
// chart series and format sets.
func (f *File) drawChartSeriesVal(v formatChartSeries, formatSet *formatChart) *cVal {
val := &cVal{
NumRef: &cNumRef{
F: v.Values,
},
}
chartSeriesVal := map[string]*cVal{Scatter: nil, Bubble: nil, Bubble3D: nil}
if _, ok := chartSeriesVal[formatSet.Type]; ok {
return nil
}
return val
}
// drawChartSeriesMarker provides a function to draw the c:marker element by
// given data index and format sets.
func (f *File) drawChartSeriesMarker(i int, formatSet *formatChart) *cMarker {
marker := &cMarker{
Symbol: &attrValString{Val: "circle"},
Size: &attrValInt{Val: 5},
}
if i < 6 {
marker.SpPr = &cSpPr{
SolidFill: &aSolidFill{
SchemeClr: &aSchemeClr{
Val: "accent" + strconv.Itoa(i+1),
},
},
Ln: &aLn{
W: 9252,
SolidFill: &aSolidFill{
SchemeClr: &aSchemeClr{
Val: "accent" + strconv.Itoa(i+1),
},
},
},
}
}
chartSeriesMarker := map[string]*cMarker{Scatter: marker}
return chartSeriesMarker[formatSet.Type]
}
// drawChartSeriesXVal provides a function to draw the c:xVal element by given
// chart series and format sets.
func (f *File) drawChartSeriesXVal(v formatChartSeries, formatSet *formatChart) *cCat {
cat := &cCat{
StrRef: &cStrRef{
F: v.Categories,
},
}
chartSeriesXVal := map[string]*cCat{Scatter: cat}
return chartSeriesXVal[formatSet.Type]
}
// drawChartSeriesYVal provides a function to draw the c:yVal element by given
// chart series and format sets.
func (f *File) drawChartSeriesYVal(v formatChartSeries, formatSet *formatChart) *cVal {
val := &cVal{
NumRef: &cNumRef{
F: v.Values,
},
}
chartSeriesYVal := map[string]*cVal{Scatter: val, Bubble: val, Bubble3D: val}
return chartSeriesYVal[formatSet.Type]
}
// drawCharSeriesBubbleSize provides a function to draw the c:bubbleSize
// element by given chart series and format sets.
func (f *File) drawCharSeriesBubbleSize(v formatChartSeries, formatSet *formatChart) *cVal {
if _, ok := map[string]bool{Bubble: true, Bubble3D: true}[formatSet.Type]; !ok {
return nil
}
return &cVal{
NumRef: &cNumRef{
F: v.Values,
},
}
}
// drawCharSeriesBubble3D provides a function to draw the c:bubble3D element
// by given format sets.
func (f *File) drawCharSeriesBubble3D(formatSet *formatChart) *attrValBool {
if _, ok := map[string]bool{Bubble3D: true}[formatSet.Type]; !ok {
return nil
}
return &attrValBool{Val: true}
}
// drawChartDLbls provides a function to draw the c:dLbls element by given
// format sets.
func (f *File) drawChartDLbls(formatSet *formatChart) *cDLbls {
return &cDLbls{
ShowLegendKey: &attrValBool{Val: formatSet.Legend.ShowLegendKey},
ShowVal: &attrValBool{Val: formatSet.Plotarea.ShowVal},
ShowCatName: &attrValBool{Val: formatSet.Plotarea.ShowCatName},
ShowSerName: &attrValBool{Val: formatSet.Plotarea.ShowSerName},
ShowBubbleSize: &attrValBool{Val: formatSet.Plotarea.ShowBubbleSize},
ShowPercent: &attrValBool{Val: formatSet.Plotarea.ShowPercent},
ShowLeaderLines: &attrValBool{Val: formatSet.Plotarea.ShowLeaderLines},
}
}
// drawChartSeriesDLbls provides a function to draw the c:dLbls element by
// given format sets.
func (f *File) drawChartSeriesDLbls(formatSet *formatChart) *cDLbls {
dLbls := f.drawChartDLbls(formatSet)
chartSeriesDLbls := map[string]*cDLbls{Scatter: nil, Surface3D: nil, WireframeSurface3D: nil, Contour: nil, WireframeContour: nil, Bubble: nil, Bubble3D: nil}
if _, ok := chartSeriesDLbls[formatSet.Type]; ok {
return nil
}
return dLbls
}
// drawPlotAreaCatAx provides a function to draw the c:catAx element.
func (f *File) drawPlotAreaCatAx(formatSet *formatChart) []*cAxs {
min := &attrValFloat{Val: formatSet.XAxis.Minimum}
max := &attrValFloat{Val: formatSet.XAxis.Maximum}
if formatSet.XAxis.Minimum == 0 {
min = nil
}
if formatSet.XAxis.Maximum == 0 {
max = nil
}
axs := []*cAxs{
{
AxID: &attrValInt{Val: 754001152},
Scaling: &cScaling{
Orientation: &attrValString{Val: orientation[formatSet.XAxis.ReverseOrder]},
Max: max,
Min: min,
},
Delete: &attrValBool{Val: false},
AxPos: &attrValString{Val: catAxPos[formatSet.XAxis.ReverseOrder]},
NumFmt: &cNumFmt{
FormatCode: "General",
SourceLinked: true,
},
MajorTickMark: &attrValString{Val: "none"},
MinorTickMark: &attrValString{Val: "none"},
TickLblPos: &attrValString{Val: "nextTo"},
SpPr: f.drawPlotAreaSpPr(),
TxPr: f.drawPlotAreaTxPr(),
CrossAx: &attrValInt{Val: 753999904},
Crosses: &attrValString{Val: "autoZero"},
Auto: &attrValBool{Val: true},
LblAlgn: &attrValString{Val: "ctr"},
LblOffset: &attrValInt{Val: 100},
NoMultiLvlLbl: &attrValBool{Val: false},
},
}
if formatSet.XAxis.MajorGridlines {
axs[0].MajorGridlines = &cChartLines{SpPr: f.drawPlotAreaSpPr()}
}
return axs
}
// drawPlotAreaValAx provides a function to draw the c:valAx element.
func (f *File) drawPlotAreaValAx(formatSet *formatChart) []*cAxs {
min := &attrValFloat{Val: formatSet.YAxis.Minimum}
max := &attrValFloat{Val: formatSet.YAxis.Maximum}
if formatSet.YAxis.Minimum == 0 {
min = nil
}
if formatSet.YAxis.Maximum == 0 {
max = nil
}
axs := []*cAxs{
{
AxID: &attrValInt{Val: 753999904},
Scaling: &cScaling{
Orientation: &attrValString{Val: orientation[formatSet.YAxis.ReverseOrder]},
Max: max,
Min: min,
},
Delete: &attrValBool{Val: false},
AxPos: &attrValString{Val: valAxPos[formatSet.YAxis.ReverseOrder]},
NumFmt: &cNumFmt{
FormatCode: chartValAxNumFmtFormatCode[formatSet.Type],
SourceLinked: true,
},
MajorTickMark: &attrValString{Val: "none"},
MinorTickMark: &attrValString{Val: "none"},
TickLblPos: &attrValString{Val: "nextTo"},
SpPr: f.drawPlotAreaSpPr(),
TxPr: f.drawPlotAreaTxPr(),
CrossAx: &attrValInt{Val: 754001152},
Crosses: &attrValString{Val: "autoZero"},
CrossBetween: &attrValString{Val: chartValAxCrossBetween[formatSet.Type]},
},
}
if formatSet.YAxis.MajorGridlines {
axs[0].MajorGridlines = &cChartLines{SpPr: f.drawPlotAreaSpPr()}
}
if pos, ok := valTickLblPos[formatSet.Type]; ok {
axs[0].TickLblPos.Val = pos
}
return axs
}
// drawPlotAreaSerAx provides a function to draw the c:serAx element.
func (f *File) drawPlotAreaSerAx(formatSet *formatChart) []*cAxs {
min := &attrValFloat{Val: formatSet.YAxis.Minimum}
max := &attrValFloat{Val: formatSet.YAxis.Maximum}
if formatSet.YAxis.Minimum == 0 {
min = nil
}
if formatSet.YAxis.Maximum == 0 {
max = nil
}
return []*cAxs{
{
AxID: &attrValInt{Val: 832256642},
Scaling: &cScaling{
Orientation: &attrValString{Val: orientation[formatSet.YAxis.ReverseOrder]},
Max: max,
Min: min,
},
Delete: &attrValBool{Val: false},
AxPos: &attrValString{Val: catAxPos[formatSet.XAxis.ReverseOrder]},
TickLblPos: &attrValString{Val: "nextTo"},
SpPr: f.drawPlotAreaSpPr(),
TxPr: f.drawPlotAreaTxPr(),
CrossAx: &attrValInt{Val: 753999904},
},
}
}
// drawPlotAreaSpPr provides a function to draw the c:spPr element.
func (f *File) drawPlotAreaSpPr() *cSpPr {
return &cSpPr{
Ln: &aLn{
W: 9525,
Cap: "flat",
Cmpd: "sng",
Algn: "ctr",
SolidFill: &aSolidFill{
SchemeClr: &aSchemeClr{
Val: "tx1",
LumMod: &attrValInt{Val: 15000},
LumOff: &attrValInt{Val: 85000},
},
},
},
}
}
// drawPlotAreaTxPr provides a function to draw the c:txPr element.
func (f *File) drawPlotAreaTxPr() *cTxPr {
return &cTxPr{
BodyPr: aBodyPr{
Rot: -60000000,
SpcFirstLastPara: true,
VertOverflow: "ellipsis",
Vert: "horz",
Wrap: "square",
Anchor: "ctr",
AnchorCtr: true,
},
P: aP{
PPr: &aPPr{
DefRPr: aRPr{
Sz: 900,
B: false,
I: false,
U: "none",
Strike: "noStrike",
Kern: 1200,
Baseline: 0,
SolidFill: &aSolidFill{
SchemeClr: &aSchemeClr{
Val: "tx1",
LumMod: &attrValInt{Val: 15000},
LumOff: &attrValInt{Val: 85000},
},
},
Latin: &aLatin{Typeface: "+mn-lt"},
Ea: &aEa{Typeface: "+mn-ea"},
Cs: &aCs{Typeface: "+mn-cs"},
},
},
EndParaRPr: &aEndParaRPr{Lang: "en-US"},
},
}
}
// drawingParser provides a function to parse drawingXML. In order to solve
// the problem that the label structure is changed after serialization and
// deserialization, two different structures: decodeWsDr and encodeWsDr are
// defined.
func (f *File) drawingParser(path string) (*xlsxWsDr, int) {
if f.Drawings[path] == nil {
content := xlsxWsDr{}
content.A = NameSpaceDrawingML
content.Xdr = NameSpaceDrawingMLSpreadSheet
_, ok := f.XLSX[path]
if ok { // Append Model
decodeWsDr := decodeWsDr{}
_ = xml.Unmarshal(namespaceStrictToTransitional(f.readXML(path)), &decodeWsDr)
content.R = decodeWsDr.R
for _, v := range decodeWsDr.OneCellAnchor {
content.OneCellAnchor = append(content.OneCellAnchor, &xdrCellAnchor{
EditAs: v.EditAs,
GraphicFrame: v.Content,
})
}
for _, v := range decodeWsDr.TwoCellAnchor {
content.TwoCellAnchor = append(content.TwoCellAnchor, &xdrCellAnchor{
EditAs: v.EditAs,
GraphicFrame: v.Content,
})
}
}
f.Drawings[path] = &content
}
wsDr := f.Drawings[path]
return wsDr, len(wsDr.OneCellAnchor) + len(wsDr.TwoCellAnchor) + 2
}
// addDrawingChart provides a function to add chart graphic frame by given
// sheet, drawingXML, cell, width, height, relationship index and format sets.
func (f *File) addDrawingChart(sheet, drawingXML, cell string, width, height, rID int, formatSet *formatPicture) error {
col, row, err := CellNameToCoordinates(cell)
if err != nil {
return err
}
colIdx := col - 1
rowIdx := row - 1
width = int(float64(width) * formatSet.XScale)
height = int(float64(height) * formatSet.YScale)
colStart, rowStart, _, _, colEnd, rowEnd, x2, y2 :=
f.positionObjectPixels(sheet, colIdx, rowIdx, formatSet.OffsetX, formatSet.OffsetY, width, height)
content, cNvPrID := f.drawingParser(drawingXML)
twoCellAnchor := xdrCellAnchor{}
twoCellAnchor.EditAs = formatSet.Positioning
from := xlsxFrom{}
from.Col = colStart
from.ColOff = formatSet.OffsetX * EMU
from.Row = rowStart
from.RowOff = formatSet.OffsetY * EMU
to := xlsxTo{}
to.Col = colEnd
to.ColOff = x2 * EMU
to.Row = rowEnd
to.RowOff = y2 * EMU
twoCellAnchor.From = &from
twoCellAnchor.To = &to
graphicFrame := xlsxGraphicFrame{
NvGraphicFramePr: xlsxNvGraphicFramePr{
CNvPr: &xlsxCNvPr{
ID: cNvPrID,
Name: "Chart " + strconv.Itoa(cNvPrID),
},
},
Graphic: &xlsxGraphic{
GraphicData: &xlsxGraphicData{
URI: NameSpaceDrawingMLChart,
Chart: &xlsxChart{
C: NameSpaceDrawingMLChart,
R: SourceRelationship,
RID: "rId" + strconv.Itoa(rID),
},
},
},
}
graphic, _ := xml.Marshal(graphicFrame)
twoCellAnchor.GraphicFrame = string(graphic)
twoCellAnchor.ClientData = &xdrClientData{
FLocksWithSheet: formatSet.FLocksWithSheet,
FPrintsWithSheet: formatSet.FPrintsWithSheet,
}
content.TwoCellAnchor = append(content.TwoCellAnchor, &twoCellAnchor)
f.Drawings[drawingXML] = content
return err
}
... ...
tenets:
- import: codelingo/effective-go
- import: codelingo/code-review-comments
... ...
// Copyright 2016 - 2019 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 files. Support reads and writes XLSX file generated by
// Microsoft Excel™ 2007 and later. Support save file without losing original
// charts of XLSX. This library needs Go version 1.10 or later.
package excelize
import (
"errors"
"math"
"strings"
)
// Define the default cell size and EMU unit of measurement.
const (
defaultColWidthPixels float64 = 64
defaultRowHeightPixels float64 = 20
EMU int = 9525
)
// GetColVisible provides a function to get visible of a single column by given
// worksheet name and column name. For example, get visible state of column D
// in Sheet1:
//
// visiable, err := f.GetColVisible("Sheet1", "D")
//
func (f *File) GetColVisible(sheet, col string) (bool, error) {
visible := true
colNum, err := ColumnNameToNumber(col)
if err != nil {
return visible, err
}
xlsx, err := f.workSheetReader(sheet)
if err != nil {
return false, err
}
if xlsx.Cols == nil {
return visible, err
}
for c := range xlsx.Cols.Col {
colData := &xlsx.Cols.Col[c]
if colData.Min <= colNum && colNum <= colData.Max {
visible = !colData.Hidden
}
}
return visible, err
}
// SetColVisible provides a function to set visible of a single column by given
// worksheet name and column name. For example, hide column D in Sheet1:
//
// err := f.SetColVisible("Sheet1", "D", false)
//
func (f *File) SetColVisible(sheet, col string, visible bool) error {
colNum, err := ColumnNameToNumber(col)
if err != nil {
return err
}
colData := xlsxCol{
Min: colNum,
Max: colNum,
Hidden: !visible,
CustomWidth: true,
}
xlsx, err := f.workSheetReader(sheet)
if err != nil {
return err
}
if xlsx.Cols == nil {
cols := xlsxCols{}
cols.Col = append(cols.Col, colData)
xlsx.Cols = &cols
return err
}
for v := range xlsx.Cols.Col {
if xlsx.Cols.Col[v].Min <= colNum && colNum <= xlsx.Cols.Col[v].Max {
colData = xlsx.Cols.Col[v]
}
}
colData.Min = colNum
colData.Max = colNum
colData.Hidden = !visible
colData.CustomWidth = true
xlsx.Cols.Col = append(xlsx.Cols.Col, colData)
return err
}
// GetColOutlineLevel provides a function to get outline level of a single
// column by given worksheet name and column name. For example, get outline
// level of column D in Sheet1:
//
// level, err := f.GetColOutlineLevel("Sheet1", "D")
//
func (f *File) GetColOutlineLevel(sheet, col string) (uint8, error) {
level := uint8(0)
colNum, err := ColumnNameToNumber(col)
if err != nil {
return level, err
}
xlsx, err := f.workSheetReader(sheet)
if err != nil {
return 0, err
}
if xlsx.Cols == nil {
return level, err
}
for c := range xlsx.Cols.Col {
colData := &xlsx.Cols.Col[c]
if colData.Min <= colNum && colNum <= colData.Max {
level = colData.OutlineLevel
}
}
return level, err
}
// SetColOutlineLevel provides a function to set outline level of a single
// column by given worksheet name and column name. The value of parameter
// 'level' is 1-7. For example, set outline level of column D in Sheet1 to 2:
//
// err := f.SetColOutlineLevel("Sheet1", "D", 2)
//
func (f *File) SetColOutlineLevel(sheet, col string, level uint8) error {
if level > 7 || level < 1 {
return errors.New("invalid outline level")
}
colNum, err := ColumnNameToNumber(col)
if err != nil {
return err
}
colData := xlsxCol{
Min: colNum,
Max: colNum,
OutlineLevel: level,
CustomWidth: true,
}
xlsx, err := f.workSheetReader(sheet)
if err != nil {
return err
}
if xlsx.Cols == nil {
cols := xlsxCols{}
cols.Col = append(cols.Col, colData)
xlsx.Cols = &cols
return err
}
for v := range xlsx.Cols.Col {
if xlsx.Cols.Col[v].Min <= colNum && colNum <= xlsx.Cols.Col[v].Max {
colData = xlsx.Cols.Col[v]
}
}
colData.Min = colNum
colData.Max = colNum
colData.OutlineLevel = level
colData.CustomWidth = true
xlsx.Cols.Col = append(xlsx.Cols.Col, colData)
return err
}
// SetColStyle provides a function to set style of columns by given worksheet
// name, columns range and style ID.
//
// For example set style of column H on Sheet1:
//
// err = f.SetColStyle("Sheet1", "H", style)
//
// Set style of columns C:F on Sheet1:
//
// err = f.SetColStyle("Sheet1", "C:F", style)
//
func (f *File) SetColStyle(sheet, columns string, styleID int) error {
xlsx, err := f.workSheetReader(sheet)
if err != nil {
return err
}
var c1, c2 string
var min, max int
cols := strings.Split(columns, ":")
c1 = cols[0]
min, err = ColumnNameToNumber(c1)
if err != nil {
return err
}
if len(cols) == 2 {
c2 = cols[1]
max, err = ColumnNameToNumber(c2)
if err != nil {
return err
}
} else {
max = min
}
if max < min {
min, max = max, min
}
if xlsx.Cols == nil {
xlsx.Cols = &xlsxCols{}
}
var find bool
for idx, col := range xlsx.Cols.Col {
if col.Min == min && col.Max == max {
xlsx.Cols.Col[idx].Style = styleID
find = true
}
}
if !find {
xlsx.Cols.Col = append(xlsx.Cols.Col, xlsxCol{
Min: min,
Max: max,
Width: 9,
Style: styleID,
})
}
return nil
}
// SetColWidth provides a function to set the width of a single column or
// multiple columns. For example:
//
// f := excelize.NewFile()
// err := f.SetColWidth("Sheet1", "A", "H", 20)
//
func (f *File) SetColWidth(sheet, startcol, endcol string, width float64) error {
min, err := ColumnNameToNumber(startcol)
if err != nil {
return err
}
max, err := ColumnNameToNumber(endcol)
if err != nil {
return err
}
if min > max {
min, max = max, min
}
xlsx, err := f.workSheetReader(sheet)
if err != nil {
return err
}
col := xlsxCol{
Min: min,
Max: max,
Width: width,
CustomWidth: true,
}
if xlsx.Cols != nil {
xlsx.Cols.Col = append(xlsx.Cols.Col, col)
} else {
cols := xlsxCols{}
cols.Col = append(cols.Col, col)
xlsx.Cols = &cols
}
return err
}
// positionObjectPixels calculate the vertices that define the position of a
// graphical object within the worksheet in pixels.
//
// +------------+------------+
// | A | B |
// +-----+------------+------------+
// | |(x1,y1) | |
// | 1 |(A1)._______|______ |
// | | | | |
// | | | | |
// +-----+----| OBJECT |-----+
// | | | | |
// | 2 | |______________. |
// | | | (B2)|
// | | | (x2,y2)|
// +-----+------------+------------+
//
// Example of an object that covers some of the area from cell A1 to B2.
//
// Based on the width and height of the object we need to calculate 8 vars:
//
// colStart, rowStart, colEnd, rowEnd, x1, y1, x2, y2.
//
// We also calculate the absolute x and y position of the top left vertex of
// the object. This is required for images.
//
// The width and height of the cells that the object occupies can be
// variable and have to be taken into account.
//
// The values of col_start and row_start are passed in from the calling
// function. The values of col_end and row_end are calculated by
// subtracting the width and height of the object from the width and
// height of the underlying cells.
//
// colStart # Col containing upper left corner of object.
// x1 # Distance to left side of object.
//
// rowStart # Row containing top left corner of object.
// y1 # Distance to top of object.
//
// colEnd # Col containing lower right corner of object.
// x2 # Distance to right side of object.
//
// rowEnd # Row containing bottom right corner of object.
// y2 # Distance to bottom of object.
//
// width # Width of object frame.
// height # Height of object frame.
//
// xAbs # Absolute distance to left side of object.
// yAbs # Absolute distance to top side of object.
//
func (f *File) positionObjectPixels(sheet string, col, row, x1, y1, width, height int) (int, int, int, int, int, int, int, int) {
xAbs := 0
yAbs := 0
// Calculate the absolute x offset of the top-left vertex.
for colID := 1; colID <= col; colID++ {
xAbs += f.getColWidth(sheet, colID)
}
xAbs += x1
// Calculate the absolute y offset of the top-left vertex.
// Store the column change to allow optimisations.
for rowID := 1; rowID <= row; rowID++ {
yAbs += f.getRowHeight(sheet, rowID)
}
yAbs += y1
// Adjust start column for offsets that are greater than the col width.
for x1 >= f.getColWidth(sheet, col) {
x1 -= f.getColWidth(sheet, col)
col++
}
// Adjust start row for offsets that are greater than the row height.
for y1 >= f.getRowHeight(sheet, row) {
y1 -= f.getRowHeight(sheet, row)
row++
}
// Initialise end cell to the same as the start cell.
colEnd := col
rowEnd := row
width += x1
height += y1
// Subtract the underlying cell widths to find end cell of the object.
for width >= f.getColWidth(sheet, colEnd+1) {
colEnd++
width -= f.getColWidth(sheet, colEnd)
}
// Subtract the underlying cell heights to find end cell of the object.
for height >= f.getRowHeight(sheet, rowEnd) {
height -= f.getRowHeight(sheet, rowEnd)
rowEnd++
}
// The end vertices are whatever is left from the width and height.
x2 := width
y2 := height
return col, row, xAbs, yAbs, colEnd, rowEnd, x2, y2
}
// getColWidth provides a function to get column width in pixels by given
// sheet name and column index.
func (f *File) getColWidth(sheet string, col int) int {
xlsx, _ := f.workSheetReader(sheet)
if xlsx.Cols != nil {
var width float64
for _, v := range xlsx.Cols.Col {
if v.Min <= col && col <= v.Max {
width = v.Width
}
}
if width != 0 {
return int(convertColWidthToPixels(width))
}
}
// Optimisation for when the column widths haven't changed.
return int(defaultColWidthPixels)
}
// GetColWidth provides a function to get column width by given worksheet name
// and column index.
func (f *File) GetColWidth(sheet, col string) (float64, error) {
colNum, err := ColumnNameToNumber(col)
if err != nil {
return defaultColWidthPixels, err
}
xlsx, err := f.workSheetReader(sheet)
if err != nil {
return defaultColWidthPixels, err
}
if xlsx.Cols != nil {
var width float64
for _, v := range xlsx.Cols.Col {
if v.Min <= colNum && colNum <= v.Max {
width = v.Width
}
}
if width != 0 {
return width, err
}
}
// Optimisation for when the column widths haven't changed.
return defaultColWidthPixels, err
}
// InsertCol provides a function to insert a new column before given column
// index. For example, create a new column before column C in Sheet1:
//
// err := f.InsertCol("Sheet1", "C")
//
func (f *File) InsertCol(sheet, col string) error {
num, err := ColumnNameToNumber(col)
if err != nil {
return err
}
return f.adjustHelper(sheet, columns, num, 1)
}
// RemoveCol provides a function to remove single column by given worksheet
// name and column index. For example, remove column C in Sheet1:
//
// err := f.RemoveCol("Sheet1", "C")
//
// Use this method with caution, which will affect changes in references such
// as formulas, charts, and so on. If there is any referenced value of the
// worksheet, it will cause a file error when you open it. The excelize only
// partially updates these references currently.
func (f *File) RemoveCol(sheet, col string) error {
num, err := ColumnNameToNumber(col)
if err != nil {
return err
}
xlsx, err := f.workSheetReader(sheet)
if err != nil {
return err
}
for rowIdx := range xlsx.SheetData.Row {
rowData := &xlsx.SheetData.Row[rowIdx]
for colIdx := range rowData.C {
colName, _, _ := SplitCellName(rowData.C[colIdx].R)
if colName == col {
rowData.C = append(rowData.C[:colIdx], rowData.C[colIdx+1:]...)[:len(rowData.C)-1]
break
}
}
}
return f.adjustHelper(sheet, columns, num, -1)
}
// convertColWidthToPixels provieds function to convert the width of a cell
// from user's units to pixels. Excel rounds the column width to the nearest
// pixel. If the width hasn't been set by the user we use the default value.
// If the column is hidden it has a value of zero.
func convertColWidthToPixels(width float64) float64 {
var padding float64 = 5
var pixels float64
var maxDigitWidth float64 = 7
if width == 0 {
return pixels
}
if width < 1 {
pixels = (width * 12) + 0.5
return math.Ceil(pixels)
}
pixels = (width*maxDigitWidth + 0.5) + padding
return math.Ceil(pixels)
}
... ...
// Copyright 2016 - 2019 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 files. Support reads and writes XLSX file generated by
// Microsoft Excel™ 2007 and later. Support save file without losing original
// charts of XLSX. This library needs Go version 1.10 or later.
package excelize
import (
"encoding/json"
"encoding/xml"
"fmt"
"strconv"
"strings"
)
// parseFormatCommentsSet provides a function to parse the format settings of
// the comment with default value.
func parseFormatCommentsSet(formatSet string) (*formatComment, error) {
format := formatComment{
Author: "Author:",
Text: " ",
}
err := json.Unmarshal([]byte(formatSet), &format)
return &format, err
}
// GetComments retrieves all comments and returns a map of worksheet name to
// the worksheet comments.
func (f *File) GetComments() (comments map[string][]Comment) {
comments = map[string][]Comment{}
for n := range f.sheetMap {
if d := f.commentsReader("xl" + strings.TrimPrefix(f.getSheetComments(f.GetSheetIndex(n)), "..")); d != nil {
sheetComments := []Comment{}
for _, comment := range d.CommentList.Comment {
sheetComment := Comment{}
if comment.AuthorID < len(d.Authors) {
sheetComment.Author = d.Authors[comment.AuthorID].Author
}
sheetComment.Ref = comment.Ref
sheetComment.AuthorID = comment.AuthorID
if comment.Text.T != nil {
sheetComment.Text += *comment.Text.T
}
for _, text := range comment.Text.R {
sheetComment.Text += text.T
}
sheetComments = append(sheetComments, sheetComment)
}
comments[n] = sheetComments
}
}
return
}
// getSheetComments provides the method to get the target comment reference by
// given worksheet index.
func (f *File) getSheetComments(sheetID int) string {
var rels = "xl/worksheets/_rels/sheet" + strconv.Itoa(sheetID) + ".xml.rels"
if sheetRels := f.relsReader(rels); sheetRels != nil {
for _, v := range sheetRels.Relationships {
if v.Type == SourceRelationshipComments {
return v.Target
}
}
}
return ""
}
// AddComment provides the method to add comment in a sheet by given worksheet
// index, cell and format set (such as author and text). Note that the max
// author length is 255 and the max text length is 32512. For example, add a
// comment in Sheet1!$A$30:
//
// err := f.AddComment("Sheet1", "A30", `{"author":"Excelize: ","text":"This is a comment."}`)
//
func (f *File) AddComment(sheet, cell, format string) error {
formatSet, err := parseFormatCommentsSet(format)
if err != nil {
return err
}
// Read sheet data.
xlsx, err := f.workSheetReader(sheet)
if err != nil {
return err
}
commentID := f.countComments() + 1
drawingVML := "xl/drawings/vmlDrawing" + strconv.Itoa(commentID) + ".vml"
sheetRelationshipsComments := "../comments" + strconv.Itoa(commentID) + ".xml"
sheetRelationshipsDrawingVML := "../drawings/vmlDrawing" + strconv.Itoa(commentID) + ".vml"
if xlsx.LegacyDrawing != nil {
// The worksheet already has a comments relationships, use the relationships drawing ../drawings/vmlDrawing%d.vml.
sheetRelationshipsDrawingVML = f.getSheetRelationshipsTargetByID(sheet, xlsx.LegacyDrawing.RID)
commentID, _ = strconv.Atoi(strings.TrimSuffix(strings.TrimPrefix(sheetRelationshipsDrawingVML, "../drawings/vmlDrawing"), ".vml"))
drawingVML = strings.Replace(sheetRelationshipsDrawingVML, "..", "xl", -1)
} else {
// Add first comment for given sheet.
sheetPath, _ := f.sheetMap[trimSheetName(sheet)]
sheetRels := "xl/worksheets/_rels/" + strings.TrimPrefix(sheetPath, "xl/worksheets/") + ".rels"
rID := f.addRels(sheetRels, SourceRelationshipDrawingVML, sheetRelationshipsDrawingVML, "")
f.addRels(sheetRels, SourceRelationshipComments, sheetRelationshipsComments, "")
f.addSheetLegacyDrawing(sheet, rID)
}
commentsXML := "xl/comments" + strconv.Itoa(commentID) + ".xml"
f.addComment(commentsXML, cell, formatSet)
var colCount int
for i, l := range strings.Split(formatSet.Text, "\n") {
if ll := len(l); ll > colCount {
if i == 0 {
ll += len(formatSet.Author)
}
colCount = ll
}
}
err = f.addDrawingVML(commentID, drawingVML, cell, strings.Count(formatSet.Text, "\n")+1, colCount)
if err != nil {
return err
}
f.addContentTypePart(commentID, "comments")
return err
}
// addDrawingVML provides a function to create comment as
// xl/drawings/vmlDrawing%d.vml by given commit ID and cell.
func (f *File) addDrawingVML(commentID int, drawingVML, cell string, lineCount, colCount int) error {
col, row, err := CellNameToCoordinates(cell)
if err != nil {
return err
}
yAxis := col - 1
xAxis := row - 1
vml := f.VMLDrawing[drawingVML]
if vml == nil {
vml = &vmlDrawing{
XMLNSv: "urn:schemas-microsoft-com:vml",
XMLNSo: "urn:schemas-microsoft-com:office:office",
XMLNSx: "urn:schemas-microsoft-com:office:excel",
XMLNSmv: "http://macVmlSchemaUri",
Shapelayout: &xlsxShapelayout{
Ext: "edit",
IDmap: &xlsxIDmap{
Ext: "edit",
Data: commentID,
},
},
Shapetype: &xlsxShapetype{
ID: "_x0000_t202",
Coordsize: "21600,21600",
Spt: 202,
Path: "m0,0l0,21600,21600,21600,21600,0xe",
Stroke: &xlsxStroke{
Joinstyle: "miter",
},
VPath: &vPath{
Gradientshapeok: "t",
Connecttype: "miter",
},
},
}
}
sp := encodeShape{
Fill: &vFill{
Color2: "#fbfe82",
Angle: -180,
Type: "gradient",
Fill: &oFill{
Ext: "view",
Type: "gradientUnscaled",
},
},
Shadow: &vShadow{
On: "t",
Color: "black",
Obscured: "t",
},
Path: &vPath{
Connecttype: "none",
},
Textbox: &vTextbox{
Style: "mso-direction-alt:auto",
Div: &xlsxDiv{
Style: "text-align:left",
},
},
ClientData: &xClientData{
ObjectType: "Note",
Anchor: fmt.Sprintf(
"%d, 23, %d, 0, %d, %d, %d, 5",
1+yAxis, 1+xAxis, 2+yAxis+lineCount, colCount+yAxis, 2+xAxis+lineCount),
AutoFill: "True",
Row: xAxis,
Column: yAxis,
},
}
s, _ := xml.Marshal(sp)
shape := xlsxShape{
ID: "_x0000_s1025",
Type: "#_x0000_t202",
Style: "position:absolute;73.5pt;width:108pt;height:59.25pt;z-index:1;visibility:hidden",
Fillcolor: "#fbf6d6",
Strokecolor: "#edeaa1",
Val: string(s[13 : len(s)-14]),
}
d := f.decodeVMLDrawingReader(drawingVML)
if d != nil {
for _, v := range d.Shape {
s := xlsxShape{
ID: "_x0000_s1025",
Type: "#_x0000_t202",
Style: "position:absolute;73.5pt;width:108pt;height:59.25pt;z-index:1;visibility:hidden",
Fillcolor: "#fbf6d6",
Strokecolor: "#edeaa1",
Val: v.Val,
}
vml.Shape = append(vml.Shape, s)
}
}
vml.Shape = append(vml.Shape, shape)
f.VMLDrawing[drawingVML] = vml
return err
}
// addComment provides a function to create chart as xl/comments%d.xml by
// given cell and format sets.
func (f *File) addComment(commentsXML, cell string, formatSet *formatComment) {
a := formatSet.Author
t := formatSet.Text
if len(a) > 255 {
a = a[0:255]
}
if len(t) > 32512 {
t = t[0:32512]
}
comments := f.commentsReader(commentsXML)
if comments == nil {
comments = &xlsxComments{
Authors: []xlsxAuthor{
{
Author: formatSet.Author,
},
},
}
}
defaultFont := f.GetDefaultFont()
cmt := xlsxComment{
Ref: cell,
AuthorID: 0,
Text: xlsxText{
R: []xlsxR{
{
RPr: &xlsxRPr{
B: " ",
Sz: &attrValFloat{Val: 9},
Color: &xlsxColor{
Indexed: 81,
},
RFont: &attrValString{Val: defaultFont},
Family: &attrValInt{Val: 2},
},
T: a,
},
{
RPr: &xlsxRPr{
Sz: &attrValFloat{Val: 9},
Color: &xlsxColor{
Indexed: 81,
},
RFont: &attrValString{Val: defaultFont},
Family: &attrValInt{Val: 2},
},
T: t,
},
},
},
}
comments.CommentList.Comment = append(comments.CommentList.Comment, cmt)
f.Comments[commentsXML] = comments
}
// countComments provides a function to get comments files count storage in
// the folder xl.
func (f *File) countComments() int {
c1, c2 := 0, 0
for k := range f.XLSX {
if strings.Contains(k, "xl/comments") {
c1++
}
}
for rel := range f.Comments {
if strings.Contains(rel, "xl/comments") {
c2++
}
}
if c1 < c2 {
return c2
}
return c1
}
// decodeVMLDrawingReader provides a function to get the pointer to the
// structure after deserialization of xl/drawings/vmlDrawing%d.xml.
func (f *File) decodeVMLDrawingReader(path string) *decodeVmlDrawing {
if f.DecodeVMLDrawing[path] == nil {
c, ok := f.XLSX[path]
if ok {
d := decodeVmlDrawing{}
_ = xml.Unmarshal(namespaceStrictToTransitional(c), &d)
f.DecodeVMLDrawing[path] = &d
}
}
return f.DecodeVMLDrawing[path]
}
// vmlDrawingWriter provides a function to save xl/drawings/vmlDrawing%d.xml
// after serialize structure.
func (f *File) vmlDrawingWriter() {
for path, vml := range f.VMLDrawing {
if vml != nil {
v, _ := xml.Marshal(vml)
f.XLSX[path] = v
}
}
}
// commentsReader provides a function to get the pointer to the structure
// after deserialization of xl/comments%d.xml.
func (f *File) commentsReader(path string) *xlsxComments {
if f.Comments[path] == nil {
content, ok := f.XLSX[path]
if ok {
c := xlsxComments{}
_ = xml.Unmarshal(namespaceStrictToTransitional(content), &c)
f.Comments[path] = &c
}
}
return f.Comments[path]
}
// commentsWriter provides a function to save xl/comments%d.xml after
// serialize structure.
func (f *File) commentsWriter() {
for path, c := range f.Comments {
if c != nil {
v, _ := xml.Marshal(c)
f.saveFileList(path, v)
}
}
}
... ...