protobi / js-xlsx

XLSX / XLSM / XLSB (Excel 2007+ Spreadsheet) / ODS parser and writer
http://oss.sheetjs.com/js-xlsx
Other
814 stars 416 forks source link

Compression requested.. #156

Open Zhenyi-Wang opened 3 years ago

Zhenyi-Wang commented 3 years ago

Hi, just want to be able to compress the exported xlsx file.. as the origional SheetJs version could do. Is it diffiluct to merge the function?

vodnokoki commented 3 years ago

I have the same issue, is it possible to merge with SheetJs?

Zhenyi-Wang commented 3 years ago

I have the same issue, is it possible to merge with SheetJs?

Inspired from https://github.com/protobi/js-xlsx/pull/128 and the answer posted by @Plotisateur in https://github.com/protobi/js-xlsx/issues/87#issuecomment-339522056_

Manually replace the function write_zip_type in xlsx.js with below code, only tested with xlsx

function write_zip_type(wb, opts) {
        var o = opts || {};
        style_builder = new StyleBuilder(opts);
        var z = write_zip(wb, o);
        var oopts = {};
        if (o.compression) oopts.compression = 'DEFLATE';
        switch (o.type) {
            case "base64":
                return z.generate({ type: "base64", compression: "DEFLATE" });
            case "binary":
                return z.generate({ type: "string", compression: "DEFLATE" });
            case "buffer":
                return z.generate({ type: "nodebuffer", compression: "DEFLATE" });
            case "file":
                return _fs.writeFileSync(o.file, z.generate({ type: "nodebuffer", compression: "DEFLATE" }));
            case "base64":
                oopts.type = "base64";
                break;
            case "binary":
                oopts.type = "string";
                break;
            case "buffer":
            case "file":
                oopts.type = "nodebuffer";
                break;
            default:
                throw new Error("Unrecognized type " + o.type);
        }

        var out = z.generate(oopts);
        if (o.type === "file") return _fs.writeFileSync(o.file, out);
        return out;
    }

and when you call XLSX.write(workbook, wopts), remember to add

compression: true

in the options, for example

var wopts = {
                bookType: 'xlsx',
                bookSST: false,
                type: 'binary',
                compression: true
            };

Worked for me :) Hope it can help in some way..