How to edit docx with nokogiri and rubyzip

后端 未结 3 1026
走了就别回头了
走了就别回头了 2021-02-01 10:27

I\'m using a combination of rubyzip and nokogiri to edit a .docx file. I\'m using rubyzip to unzip the .docx file and then using nokogiri to parse and change the body of the wo

3条回答
  •  抹茶落季
    2021-02-01 11:25

    I stumbled accross the post and know nothing about ruby or nokogiri but ...

    It looks like you are reziping the new content incorrectly. I don't know about rubyzip, but you need a way to tell it to update the entry word/document.xml and then resave/rezip the file.

    It looks like you are just overwriting the entry with new data wich of course is going to be a different size and totally screw up the rest of the zip file.

    I give an example for excel in this post Parse text file and create an excel report

    which may be of use even though i am using a different zip library and VB (Im still doing exactly what you are trying to do, my code is about half way down)

    here is the part that applies

    Using z As ZipFile = ZipFile.Read(xlStream.BaseStream) 
    'Grab Sheet 1 out of the file parts and read it into a string. 
    Dim myEntry As ZipEntry = z("xl/worksheets/sheet1.xml") 
    Dim msSheet1 As New MemoryStream 
    myEntry.Extract(msSheet1) 
    msSheet1.Position = 0 
    Dim sr As New StreamReader(msSheet1) 
    Dim strXMLData As String = sr.ReadToEnd 
    
    'Grab the data in the empty sheet and swap out the data that I want  
    Dim str2 As XElement = CreateSheetData(tbl) 
    Dim strReplace As String = strXMLData.Replace("", str2.ToString) 
    z.UpdateEntry("xl/worksheets/sheet1.xml", strReplace) 
    'This just rezips the file with the new data it doesnt save to disk 
    z.Save(fiRet.FullName) 
    End Using 
    

提交回复
热议问题