Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

New function add_picture #3

Merged
merged 1 commit into from
Dec 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,46 @@ if err:
print(err)
```

### Add picture to spreadsheet file

```python
import excelize

f, err = excelize.open_file("Book1.xlsx")
if err:
print(err)
exit()
# Insert a picture.
err = f.add_picture("Sheet1", "A2", "image.png", None)
if err:
print(err)
# Insert a picture to worksheet with scaling.
err = f.add_picture("Sheet1", "D2", "image.jpg", excelize.GraphicOptions(
scale_x=0.5,
scale_y=0.5,
))
if err:
print(err)
# Insert a picture offset in the cell with printing support.
err = f.add_picture("Sheet1", "H2", "image.gif", excelize.GraphicOptions(
print_object=True,
lock_aspect_ratio=False,
offset_x=15,
offset_y=10,
locked=False,
))
if err:
print(err)
# Save the spreadsheet with the origin path.
err = f.save()
if err:
print(err)
# Close the spreadsheet.
err = f.close()
if err:
print(err)
```

## Contributing

Contributions are welcome! Open a pull request to fix a bug, or open an issue to discuss a new feature or change.
Expand Down
40 changes: 40 additions & 0 deletions README_zh.md
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,46 @@ if err:
print(err)
```

### 向 Excel 文档中插入图片

```python
import excelize

f, err = excelize.open_file("Book1.xlsx")
if err:
print(err)
exit()
# 插入图片
err = f.add_picture("Sheet1", "A2", "image.png", None)
if err:
print(err)
# 在工作表中插入图片,并设置图片的缩放比例
err = f.add_picture("Sheet1", "D2", "image.jpg", excelize.GraphicOptions(
scale_x=0.5,
scale_y=0.5,
))
if err:
print(err)
# 在工作表中插入图片,并设置图片的打印属性
err = f.add_picture("Sheet1", "H2", "image.gif", excelize.GraphicOptions(
print_object=True,
lock_aspect_ratio=False,
offset_x=15,
offset_y=10,
locked=False,
))
if err:
print(err)
# 保存工作簿
err = f.save()
if err:
print(err)
# 关闭工作簿
err = f.close()
if err:
print(err)
```

## 社区合作

欢迎您为此项目贡献代码,提出建议或问题、修复 Bug 以及参与讨论对新功能的想法。
Expand Down
34 changes: 34 additions & 0 deletions excelize.py
Original file line number Diff line number Diff line change
Expand Up @@ -495,6 +495,40 @@ def add_chart(
).decode(ENCODE)
return None if err == "" else Exception(err)

def add_picture(
self, sheet: str, cell: str, name: str, opts: GraphicOptions | None
) -> Exception | None:
"""
Add picture in a sheet by given picture format set (such as offset,
scale, aspect ratio setting and print settings) and file path, supported
image types: BMP, EMF, EMZ, GIF, JPEG, JPG, PNG, SVG, TIF, TIFF, WMF,
and WMZ.

Args:
sheet (str): The worksheet name
cell (str): The cell reference
name (str): The image file path
*opts (GraphicOptions): The image options

Returns:
Exception | None: Returns None if no error occurred,
otherwise returns an Exception with the message.
"""
lib.AddPicture.restype = c_char_p
options = (
byref(py_value_to_c(opts, types_go._GraphicOptions()))
if opts
else POINTER(types_go._GraphicOptions)()
)
err = lib.AddPicture(
self.file_index,
sheet.encode(ENCODE),
cell.encode(ENCODE),
name.encode(ENCODE),
options,
).decode(ENCODE)
return None if err == "" else Exception(err)

def close(self) -> Exception | None:
"""
Closes and cleanup the open temporary file for the spreadsheet.
Expand Down
5 changes: 4 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@ module github.com/xuri/excelize-py

go 1.18

require github.com/xuri/excelize/v2 v2.9.1-0.20241122135638-c93618856aaf
require (
github.com/xuri/excelize/v2 v2.9.1-0.20241122135638-c93618856aaf
golang.org/x/image v0.22.0
)

require (
github.com/richardlehane/mscfb v1.0.4 // indirect
Expand Down
3 changes: 2 additions & 1 deletion go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@ github.com/xuri/nfp v0.0.0-20240318013403-ab9948c2c4a7 h1:hPVCafDV85blFTabnqKgNh
github.com/xuri/nfp v0.0.0-20240318013403-ab9948c2c4a7/go.mod h1:WwHg+CVyzlv/TX9xqBFXEZAuxOPxn2k1GNHwG41IIUQ=
golang.org/x/crypto v0.29.0 h1:L5SG1JTTXupVV3n6sUqMTeWbjAyfPwoda2DLX8J8FrQ=
golang.org/x/crypto v0.29.0/go.mod h1:+F4F4N5hv6v38hfeYwTdx20oUvLLc+QfrE9Ax9HtgRg=
golang.org/x/image v0.18.0 h1:jGzIakQa/ZXI1I0Fxvaa9W7yP25TqT6cHIHn+6CqvSQ=
golang.org/x/image v0.22.0 h1:UtK5yLUzilVrkjMAZAZ34DXGpASN8i8pj8g+O+yd10g=
golang.org/x/image v0.22.0/go.mod h1:9hPFhljd4zZ1GNSIZJ49sqbp45GKK9t6w+iXvGqZUz4=
golang.org/x/net v0.31.0 h1:68CPQngjLL0r2AlUKiSxtQFKvzRVbnzLwMUn5SzcLHo=
golang.org/x/net v0.31.0/go.mod h1:P4fl1q7dY2hnZFxEk4pPSkDHF+QqjitcnDjUQyMM+pM=
golang.org/x/text v0.20.0 h1:gK/Kv2otX8gz+wn7Rmb3vT96ZwuoxnQlY+HlJVj7Qug=
Expand Down
33 changes: 33 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,12 @@ import (
"unicode"
"unsafe"

_ "image/gif"
_ "image/jpeg"
_ "image/png"

_ "golang.org/x/image/tiff"

"github.com/xuri/excelize/v2"
)

Expand Down Expand Up @@ -441,6 +447,33 @@ func AddChart(idx int, sheet, cell *C.char, chart *C.struct_Chart, length int) *
return C.CString(errNil)
}

// Add picture in a sheet by given picture format set (such as offset, scale,
// aspect ratio setting and print settings) and file path, supported image
// types: BMP, EMF, EMZ, GIF, JPEG, JPG, PNG, SVG, TIF, TIFF, WMF, and WMZ.
//
//export AddPicture
func AddPicture(idx int, sheet, cell, name *C.char, opts *C.struct_GraphicOptions) *C.char {
f, ok := files.Load(idx)
if !ok {
return C.CString(errFilePtr)
}
if opts != nil {
goVal, err := cValueToGo(reflect.ValueOf(*opts), reflect.TypeOf(excelize.GraphicOptions{}))
if err != nil {
return C.CString(err.Error())
}
options := goVal.Elem().Interface().(excelize.GraphicOptions)
if err := f.(*excelize.File).AddPicture(C.GoString(sheet), C.GoString(cell), C.GoString(name), &options); err != nil {
return C.CString(err.Error())
}
return C.CString(errNil)
}
if err := f.(*excelize.File).AddPicture(C.GoString(sheet), C.GoString(cell), C.GoString(name), nil); err != nil {
return C.CString(err.Error())
}
return C.CString(errNil)
}

// CoordinatesToCellName converts [X, Y] coordinates to alpha-numeric cell name
// or returns an error.
//
Expand Down
18 changes: 18 additions & 0 deletions test_excelize.py
Original file line number Diff line number Diff line change
Expand Up @@ -295,6 +295,24 @@ def test_add_chart(self):
)
self.assertIsNone(f.save_as("TestAddChart.xlsx"))

def test_add_picture(self):
f = excelize.new_file()
self.assertIsNone(f.add_picture("Sheet1", "A1", "chart.png", None))
self.assertIsNone(
f.add_picture(
"Sheet1",
"A2",
"chart.png",
excelize.GraphicOptions(
print_object=True,
scale_x=0.1,
scale_y=0.1,
locked=False,
),
)
)
self.assertIsNone(f.save_as("TestAddPicture.xlsx"))

def test_type_convert(self):
class _T2(Structure):
_fields_ = [
Expand Down