none
NPOI Insert Multi Images to the Same Excel Sheets RRS feed

  • 問題

  •         請教各位前輩

            我使用NPOI貼2個圖到同一個Sheet裡

            程式碼如下

            Dim fs As FileStream = New FileStream(ExcelFile, FileMode.Open, FileAccess.Read)
            Dim workbook = New HSSFWorkbook(fs)
            Dim sheet As HSSFSheet = workbook.GetSheet(ShtName)

            For I As Integer = 0 To 1
                Dim bytes() As Byte = System.IO.File.ReadAllBytes(ImgName(I))
                Dim pictureIdx As Integer = workbook.AddPicture(bytes, SS.UserModel.PictureType.JPEG)
                Dim patriarch As HSSFPatriarch = sheet.CreateDrawingPatriarch()
                Dim anchor As HSSFClientAnchor = New HSSFClientAnchor(0, 0, 0, 0, drawPos(I, 0), drawPos(I, 1), drawPos(I, 2), drawPos(I, 3))
                Dim pict As HSSFPicture = patriarch.CreatePicture(anchor, pictureIdx)

                Dim tfs As FileStream = New FileStream(ExcelFile, FileMode.Create, FileAccess.Write)
                workbook.Write(tfs)

                tfs.Close()
            Next

            我的問題是第二個圖一上去(workbook.Write(tfs)),第一個圖就不見了

            請問為什麼會發生這樣的情形,該如何解決?

            感謝 !

     

     

    .Net初學者

    2011年9月8日 上午 08:10

解答

所有回覆

  • http://npoi.codeplex.com/discussions/63043

    只用一個HSSFPatriarch試試

    2011年9月8日 上午 08:23
    版主
  •   Dim fs As FileStream = New FileStream(ExcelFile, FileMode.Open, FileAccess.Read)
            Dim workbook = New HSSFWorkbook(fs)
            Dim sheet As HSSFSheet = workbook.GetSheet(ShtName)

            For I As Integer = 0 To 1
                Dim bytes() As Byte = System.IO.File.ReadAllBytes(ImgName(I))
                Dim pictureIdx As Integer = workbook.AddPicture(bytes, SS.UserModel.PictureType.JPEG)
                Dim patriarch As HSSFPatriarch = sheet.CreateDrawingPatriarch()
                Dim anchor As HSSFClientAnchor = New HSSFClientAnchor(0, 0, 0, 0, drawPos(I, 0), drawPos(I, 1), drawPos(I, 2), drawPos(I, 3))
                Dim pict As HSSFPicture = patriarch.CreatePicture(anchor, pictureIdx)

                       Next

     

        以下三行放到迴圈外

                Dim tfs As FileStream = New FileStream(ExcelFile, FileMode.Create, FileAccess.Write)
                workbook.Write(tfs)

                tfs.Close()

    1.寫出Excel檔的程式碼要放到迴圈外,FileMode.Create寫在迴圈內會一直覆蓋檔案

    2.檢查粗體字地方是不是太過重覆的位置


    Shadowと愉快なコード達

    2011年9月8日 上午 08:23
  • to Shadow And Happy Code大

         我把那三行程式碼放到外面來了

         也檢查過圖貼上的位置和pictureIdx

         兩次的迴圈值都不一樣

         但結果還是一樣,只秀出第二張圖

         我試過以上的方式在不同的sheet丟圖

         結果是兩張都看的到,但同一個Sheet就是Try不出來

         真奇怪

         來去試試阿尼大的方式看看 !

         感恩 !

     

    2011年9月8日 上午 09:33
  • 試出來了

    把這一行Dim patriarch As HSSFPatriarch = sheet.CreateDrawingPatriarch()
    拿到迴圈外就OK了,就是阿尼大說的只用一個HSSFPatriarch

     

    感謝 !

    2011年9月8日 上午 09:37