2016-12-15 178 views

回答

2

的解決方案是,如果我們試圖將文件已損壞的壓縮文件夾壓縮包含在XLSX文件的直接列表,出於某種原因。

的代碼看起來是這樣的,如果你使用JSZIP

var fs = require('fs'); 
var JSZip = require("jszip"); 
var zip = new JSZip(); 
var file = []; 
file.push("_rels/.rels"); 
file.push("docProps/core.xml"); 
file.push("docProps/app.xml"); 
file.push("docProps/custom.xml"); 
file.push("[Content_Types].xml"); 
file.push("xl/_rels/workbook.xml.rels"); 
file.push("xl/styles.xml"); 
file.push("xl/pivotTables/_rels/pivotTable3.xml.rels"); 
file.push("xl/pivotTables/_rels/pivotTable1.xml.rels"); 
file.push("xl/pivotTables/_rels/pivotTable2.xml.rels"); 
file.push("xl/pivotTables/pivotTable3.xml"); 
file.push("xl/pivotTables/pivotTable1.xml"); 
file.push("xl/pivotTables/pivotTable2.xml"); 
file.push("xl/workbook.xml"); 
file.push("xl/worksheets/_rels/sheet2.xml.rels"); 
file.push("xl/worksheets/_rels/sheet1.xml.rels"); 
file.push("xl/worksheets/_rels/sheet3.xml.rels"); 
file.push("xl/worksheets/sheet4.xml"); 
file.push("xl/worksheets/sheet1.xml"); 
file.push("xl/worksheets/sheet3.xml"); 
file.push("xl/worksheets/sheet2.xml"); 
file.push("xl/sharedStrings.xml"); 
file.push("xl/pivotCache/_rels/pivotCacheDefinition1.xml.rels"); 
file.push("xl/pivotCache/pivotCacheDefinition1.xml"); 
file.push("xl/pivotCache/pivotCacheRecords1.xml"); 

for (var i = 0; i < file.length; i++) { 
    zip.file(file[i], fs.readFileSync("/home/user/xlsx_FILES/"+file[i])); 
} 

zip.generateAsync({type:"blob"}).then(function(content) { 
    // see FileSaver.js 
    saveAs(content, "yourfile.xlsx"); 
}); 
1

看看archiver,一個nodejs的壓縮庫。圖書館的docs看起來很全面。該庫還允許您追加檔案並利用流式API來追加和創建新檔案。

以下是他們的文檔中的示例代碼片段,它顯示瞭如何使用該庫。

// require modules 
var fs = require('fs'); 
var archiver = require('archiver'); 

// create a file to stream archive data to. 
var output = fs.createWriteStream(__dirname + '/example.zip'); 
var archive = archiver('zip', { 
    store: true // Sets the compression method to STORE. 
}); 

// listen for all archive data to be written 
output.on('close', function() { 
    console.log(archive.pointer() + ' total bytes'); 
    console.log('archiver has been finalized and the output file descriptor has closed.'); 
}); 

// good practice to catch this error explicitly 
archive.on('error', function(err) { 
    throw err; 
}); 

// pipe archive data to the file 
archive.pipe(output); 
+0

它非常適合於大規模的壓縮,但是當試圖壓縮回XLSX文件被破壞。 –

+0

我想知道爲什麼?你可以將你的代碼添加到OP嗎? –

+0

我找到了解決方案,我只是將它作爲答案發布 –