Skip to content

Issue/Corrupt workbook using stream writer with background image #1090

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions lib/stream/xlsx/workbook-writer.js
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,8 @@ class WorkbookWriter {

addImage(image) {
const id = this.media.length;
this.media.push(Object.assign({}, image, {type: 'image'}));
const medium = Object.assign({}, image, {type: 'image', name: `image${id}.${image.extension}`});
this.media.push(medium);
return id;
}

Expand Down Expand Up @@ -226,8 +227,7 @@ class WorkbookWriter {

addMedia() {
return Promise.all(
this.media.map((medium, idx) => {
medium.name = `image${idx+1}.${medium.extension}`;
this.media.map((medium) => {
if (medium.type === 'image') {
const filename = `xl/media/${medium.name}`;
if (medium.filename) {
Expand Down
27 changes: 27 additions & 0 deletions spec/integration/workbook-xlsx-writer/workbook-xlsx-writer.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -470,5 +470,32 @@ describe('WorkbookWriter', () => {
const imageData = await fsReadFileAsync(IMAGE_FILENAME);
expect(Buffer.compare(imageData, image.buffer)).to.equal(0);
});

it('with background image where worksheet is commited in advance', async () => {
const options = {
filename: TEST_XLSX_FILE_NAME,
};
const wb = new ExcelJS.stream.xlsx.WorkbookWriter(options);
const ws = wb.addWorksheet('Hello');

const imageId = wb.addImage({
filename: IMAGE_FILENAME,
extension: 'jpeg',
});
ws.getCell('A1').value = 'Hello, World!';
ws.addBackgroundImage(imageId);

await ws.commit();
await wb.commit();

const wb2 = new ExcelJS.Workbook();
await wb2.xlsx.readFile(TEST_XLSX_FILE_NAME);
const ws2 = wb2.getWorksheet('Hello');

const backgroundId2 = ws2.getBackgroundImageId();
const image = wb2.getImage(backgroundId2);
const imageData = await fsReadFileAsync(IMAGE_FILENAME);
expect(Buffer.compare(imageData, image.buffer)).to.equal(0);
});
});
});