Skip to content

Commit bd5b033

Browse files
committed
Support set work sheet background image.
1 parent 9559f45 commit bd5b033

File tree

7 files changed

+96
-15
lines changed

7 files changed

+96
-15
lines changed

col.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@ func (f *File) SetColWidth(sheet, startcol, endcol string, width float64) {
6868
// | | | (x2,y2)|
6969
// +-----+------------+------------+
7070
//
71-
// Example of an object that covers some of the area from cell A1 to B2.
71+
// Example of an object that covers some of the area from cell A1 to B2.
7272
//
7373
// Based on the width and height of the object we need to calculate 8 vars:
7474
//

excelize_test.go

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -208,3 +208,30 @@ func TestSetCellFormula(t *testing.T) {
208208
t.Log(err)
209209
}
210210
}
211+
212+
func TestSetSheetBackground(t *testing.T) {
213+
xlsx, err := OpenFile("./test/Workbook1.xlsx")
214+
if err != nil {
215+
t.Log(err)
216+
}
217+
err = xlsx.SetSheetBackground("sheet2", "./test/images/background.png")
218+
if err != nil {
219+
t.Log(err)
220+
}
221+
err = xlsx.SetSheetBackground("sheet2", "./test/Workbook1.xlsx")
222+
if err != nil {
223+
t.Log(err)
224+
}
225+
err = xlsx.SetSheetBackground("sheet2", "./test/images/background.jpg")
226+
if err != nil {
227+
t.Log(err)
228+
}
229+
err = xlsx.SetSheetBackground("sheet2", "./test/images/background.jpg")
230+
if err != nil {
231+
t.Log(err)
232+
}
233+
err = xlsx.Save()
234+
if err != nil {
235+
t.Log(err)
236+
}
237+
}

file.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ func CreateFile() *File {
2727
}
2828
}
2929

30-
// Save provides function override the xlsx file with origin path.
30+
// Save provides function to override the xlsx file with origin path.
3131
func (f *File) Save() error {
3232
buf := new(bytes.Buffer)
3333
w := zip.NewWriter(buf)

lib.go

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -38,15 +38,16 @@ func ReadZipReader(r *zip.Reader) (map[string]string, int, error) {
3838
return fileList, worksheets, nil
3939
}
4040

41-
// Read XML content as string.
41+
// readXML provides function to read XML content as string.
4242
func (f *File) readXML(name string) string {
4343
if content, ok := f.XLSX[name]; ok {
4444
return content
4545
}
4646
return ""
4747
}
4848

49-
// Update given file content in file list of XLSX.
49+
// saveFileList provides function to update given file content in file list of
50+
// XLSX.
5051
func (f *File) saveFileList(name string, content string) {
5152
f.XLSX[name] = XMLHeader + content
5253
}
@@ -63,7 +64,8 @@ func readFile(file *zip.File) string {
6364
return string(buff.Bytes())
6465
}
6566

66-
// Convert integer to Excel sheet column title.
67+
// toAlphaString provides function to convert integer to Excel sheet column
68+
// title.
6769
func toAlphaString(value int) string {
6870
if value < 0 {
6971
return ""
@@ -77,7 +79,7 @@ func toAlphaString(value int) string {
7779
return ans
7880
}
7981

80-
// Convert Excel sheet column title to int.
82+
// titleToNumber provides function to convert Excel sheet column title to int.
8183
func titleToNumber(s string) int {
8284
weight := 0.0
8385
sum := 0

picture.go

Lines changed: 31 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -135,7 +135,23 @@ func (f *File) addSheetDrawing(sheet string, rID int) {
135135
if err != nil {
136136
fmt.Println(err)
137137
}
138-
f.saveFileList(name, string(output))
138+
f.saveFileList(name, replaceWorkSheetsRelationshipsNameSpace(string(output)))
139+
}
140+
141+
// addSheetPicture provides function to add picture element to
142+
// xl/worksheets/sheet%d.xml by given sheet name and relationship index.
143+
func (f *File) addSheetPicture(sheet string, rID int) {
144+
var xlsx xlsxWorksheet
145+
name := "xl/worksheets/" + strings.ToLower(sheet) + ".xml"
146+
xml.Unmarshal([]byte(f.readXML(name)), &xlsx)
147+
xlsx.Picture = &xlsxPicture{
148+
RID: "rId" + strconv.Itoa(rID),
149+
}
150+
output, err := xml.Marshal(xlsx)
151+
if err != nil {
152+
fmt.Println(err)
153+
}
154+
f.saveFileList(name, replaceWorkSheetsRelationshipsNameSpace(string(output)))
139155
}
140156

141157
// countDrawings provides function to get drawing files count storage in the
@@ -270,13 +286,10 @@ func (f *File) addMedia(file string, ext string) {
270286
f.XLSX[media] = string(dat)
271287
}
272288

273-
// addDrawingContentTypePart provides function to add image part relationships
274-
// in http://purl.oclc.org/ooxml/officeDocument/relationships/image and
275-
// appropriate content type.
276-
func (f *File) addDrawingContentTypePart(index int) {
289+
func (f *File) setContentTypePartImageExtensions() {
277290
var imageTypes = map[string]bool{"jpeg": false, "png": false, "gif": false}
278291
var content xlsxTypes
279-
xml.Unmarshal([]byte(f.readXML(`[Content_Types].xml`)), &content)
292+
xml.Unmarshal([]byte(f.readXML("[Content_Types].xml")), &content)
280293
for _, v := range content.Defaults {
281294
_, ok := imageTypes[v.Extension]
282295
if ok {
@@ -291,6 +304,17 @@ func (f *File) addDrawingContentTypePart(index int) {
291304
})
292305
}
293306
}
307+
output, _ := xml.Marshal(content)
308+
f.saveFileList("[Content_Types].xml", string(output))
309+
}
310+
311+
// addDrawingContentTypePart provides function to add image part relationships
312+
// in http://purl.oclc.org/ooxml/officeDocument/relationships/image and
313+
// appropriate content type.
314+
func (f *File) addDrawingContentTypePart(index int) {
315+
f.setContentTypePartImageExtensions()
316+
var content xlsxTypes
317+
xml.Unmarshal([]byte(f.readXML("[Content_Types].xml")), &content)
294318
for _, v := range content.Overrides {
295319
if v.PartName == "/xl/drawings/drawing"+strconv.Itoa(index)+".xml" {
296320
output, _ := xml.Marshal(content)
@@ -303,7 +327,7 @@ func (f *File) addDrawingContentTypePart(index int) {
303327
ContentType: "application/vnd.openxmlformats-officedocument.drawing+xml",
304328
})
305329
output, _ := xml.Marshal(content)
306-
f.saveFileList(`[Content_Types].xml`, string(output))
330+
f.saveFileList("[Content_Types].xml", string(output))
307331
}
308332

309333
// getSheetRelationshipsTargetByID provides function to get Target attribute

sheet.go

Lines changed: 30 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,10 @@ package excelize
33
import (
44
"bytes"
55
"encoding/xml"
6+
"errors"
67
"fmt"
8+
"os"
9+
"path"
710
"strconv"
811
"strings"
912
)
@@ -193,8 +196,8 @@ func (f *File) GetActiveSheetIndex() int {
193196
xml.Unmarshal([]byte(f.readXML(buffer.String())), &xlsx)
194197
for _, sheetView := range xlsx.SheetViews.SheetView {
195198
if sheetView.TabSelected {
196-
id, _ := strconv.Atoi(strings.TrimPrefix(v.ID, "rId"))
197-
return id
199+
ID, _ := strconv.Atoi(strings.TrimPrefix(v.ID, "rId"))
200+
return ID
198201
}
199202
}
200203
buffer.Reset()
@@ -258,3 +261,28 @@ func (f *File) GetSheetMap() map[int]string {
258261
}
259262
return sheetMap
260263
}
264+
265+
// SetSheetBackground provides function to set background picture by given sheet
266+
// index.
267+
func (f *File) SetSheetBackground(sheet, picture string) error {
268+
var supportTypes = map[string]string{".gif": ".gif", ".jpg": ".jpeg", ".jpeg": ".jpeg", ".png": ".png"}
269+
var err error
270+
// Check picture exists first.
271+
if _, err = os.Stat(picture); os.IsNotExist(err) {
272+
return err
273+
}
274+
ext, ok := supportTypes[path.Ext(picture)]
275+
if !ok {
276+
return errors.New("Unsupported image extension")
277+
}
278+
// Read sheet data.
279+
var xlsx xlsxWorksheet
280+
name := "xl/worksheets/" + strings.ToLower(sheet) + ".xml"
281+
xml.Unmarshal([]byte(f.readXML(name)), &xlsx)
282+
pictureID := f.countMedia() + 1
283+
rID := f.addSheetRelationships(sheet, SourceRelationshipImage, "../media/image"+strconv.Itoa(pictureID)+ext, "")
284+
f.addSheetPicture(sheet, rID)
285+
f.addMedia(picture, ext)
286+
f.setContentTypePartImageExtensions()
287+
return err
288+
}

test/images/background.jpg

2.32 KB
Loading

0 commit comments

Comments
 (0)