Skip to content

Commit

Permalink
enhance cell customization - add data-base64-xlsx-cell-config
Browse files Browse the repository at this point in the history
  • Loading branch information
yuanoook committed Dec 10, 2020
1 parent e104d08 commit e48f9b7
Show file tree
Hide file tree
Showing 3 changed files with 65 additions and 0 deletions.
10 changes: 10 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,16 @@ module.exports = (html, callback, options = {}) => {
cell.hMerge = cs - 1;
}

// In case you need the flexibility to config all possible
// _value, formula, numFmt, cellType...
const b64Config = $td.attr('data-base64-xlsx-cell-config');
if (b64Config) {
try {
const configStr = Buffer.from(b64Config, 'base64').toString('utf-8');
Object.assign(cell, JSON.parse(configStr));
} catch (e) {}
}

for (let r = 0; r < rs; r++) {
if (offsets[hi + r] === undefined) {
offsets[hi + r] = 0;
Expand Down
Binary file added test/expect/data-base64-cell-config.xlsx
Binary file not shown.
55 changes: 55 additions & 0 deletions test/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -346,4 +346,59 @@ describe('Test: index.js', () => {
});
});
});

it('should htmlToXlsx data base64 cell config ok', (done) => {
/* eslint-disable no-useless-escape */
const btoa = str => Buffer.from(str, 'utf-8').toString('base64');
const object2b64 = obj => btoa(JSON.stringify(obj));
const cells = [0, 1, 10, 100, 1000, 10000, 100000, NaN].map(amount => ({
numFmt: '"$"#,##0.00;[Red]\-"$"#,##0.00',
cellType: 'TypeNumeric',
_value: amount
}));
const body = cells.map(cell => `
<tr>
<td data-base64-xlsx-cell-config="${object2b64(cell)}"></td>
</tr>
`).concat(`
<tr>
<td data-base64-xlsx-cell-config="Trigger Base 64 parse Error"></td>
</tr>
`, `
<tr>
<td data-base64-xlsx-cell-config="${btoa('Trigger JSON parse Error')}"></td>
</tr>
`);

htmlTo(`
<style type="text/css">
table th, table td {
width: 400px;
height: 50px;
vertical-align: middle;
text-align: right;
}
</style>
<table>
${body}
</table>
`, (err, file) => {
if (err) return done(err);

const tmpfile = join(tmpdir(), 'data-base64-cell-config.xlsx');
const expfile = join(__dirname, 'expect/data-base64-cell-config.xlsx');
file
.saveAs()
.pipe(fs.createWriteStream(tmpfile))
.on('finish', () => {
const expectFile = fs.createReadStream(expfile);
const actualFile = fs.createReadStream(tmpfile);
streamEqual(expectFile, actualFile, function (err, ok) {
expect(err).to.be.null;
expect(ok).to.be.true;
done();
});
});
});
});
});

0 comments on commit e48f9b7

Please sign in to comment.