1.使用的插件包 github.com/360EntSecGroup-Skylar/excelize
2. image: unknown format 具体源码跟踪:
err = xlsx.AddPicture(sheet_name, "B4", img_path, "")//报错位置
//源码分析
func (f *File) AddPicture(sheet, cell, picture, format string) error {
var err error
// Check picture exists first.
if _, err = os.Stat(picture); os.IsNotExist(err) {
return err
}
ext, ok := supportImageTypes[path.Ext(picture)]//这里supportImageTypes是插件所有支持的图片类型
if !ok {
return errors.New("unsupported image extension")
}
file, _ := ioutil.ReadFile(picture)
_, name := filepath.Split(picture)
return f.AddPictureFromBytes(sheet, cell, format, name, ext, file)//AddPictureFromBytes进入该方法
}
func (f *File) AddPictureFromBytes(sheet, cell, format, name, extension string, file []byte) error {
var drawingHyperlinkRID int
var hyperlinkType string
ext, ok := supportImageTypes[extension]
if !ok {
return errors.New("unsupported image extension")
}
formatSet, err := parseFormatPictureSet(format)
if err != nil {
return err
}
//这里可确定问题,图片文件格式有问题,image解码认为不是图片文件
//返回查找对原始文件的处理发现,对图片进行过截取,jpeg格式没有问题,如果是png或者其他格式,会报格式不匹配错误
img, _, err := image.DecodeConfig(bytes.NewReader(file))//这里调用的image包的解码
if err != nil {
return err
}
// Read sheet data.
xlsx, err := f.workSheetReader(sheet)
if err != nil {
return err
}
// Add first picture for given sheet, create xl/drawings/ and xl/drawings/_rels/ folder.
drawingID := f.countDrawings() + 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"
mediaStr := ".." + strings.TrimPrefix(f.addMedia(file, ext), "xl")
drawingRID := f.addRels(drawingRels, SourceRelationshipImage, mediaStr, hyperlinkType)
// Add picture with hyperlink.
if formatSet.Hyperlink != "" && formatSet.HyperlinkType != "" {
if formatSet.HyperlinkType == "External" {
hyperlinkType = formatSet.HyperlinkType
}
drawingHyperlinkRID = f.addRels(drawingRels, SourceRelationshipHyperLink, formatSet.Hyperlink, hyperlinkType)
}
err = f.addDrawingPicture(sheet, drawingXML, cell, name, img.Width, img.Height, drawingRID, drawingHyperlinkRID, formatSet)
if err != nil {
return err
}
f.addContentTypePart(drawingID, "drawings")
return err
}
func DecodeConfig(r io.Reader) (Config, string, error) {
rr := asReader(r)
f := sniff(rr)//sniff 确定真实文件的格式
if f.decodeConfig == nil {
return Config{}, "", ErrFormat//可以看到错误,文件的第一句话 var ErrFormat = errors.New("image: unknown format")
}
c, err := f.decodeConfig(rr)
return c, f.name, err
}
3.最终问题是没有引入image下的包
这三个包的init函数初始化所有的变量
_"image/gif"
_ "image/jpeg"
_ "image/png"