Skip to content

Commit

Permalink
feat: utilized exceljs to skip empty rows in file while counting
Browse files Browse the repository at this point in the history
  • Loading branch information
chavda-bhavik committed Oct 8, 2024
1 parent 64d617d commit 04d00ce
Show file tree
Hide file tree
Showing 3 changed files with 242 additions and 26 deletions.
1 change: 1 addition & 0 deletions apps/api/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@
"dayjs": "^1.11.11",
"dotenv": "^16.0.2",
"envalid": "^7.3.1",
"exceljs": "^4.4.0",
"hat": "^0.0.3",
"jsonwebtoken": "^9.0.0",
"jszip": "^3.10.1",
Expand Down
29 changes: 6 additions & 23 deletions apps/api/src/app/shared/services/file/file.service.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import * as XLSX from 'xlsx';
import * as exceljs from 'exceljs';
import { cwd } from 'node:process';
import * as xlsxPopulate from 'xlsx-populate';
import { CONSTANTS } from '@shared/constants';
Expand Down Expand Up @@ -154,31 +155,13 @@ export class ExcelFileService {
getExcelRowsColumnsCount(file: Express.Multer.File, sheetName?: string): Promise<{ rows: number; columns: number }> {
return new Promise(async (resolve, reject) => {
try {
const wb = XLSX.read(file.buffer);
const ws = sheetName && wb.SheetNames.includes(sheetName) ? wb.Sheets[sheetName] : wb.Sheets[wb.SheetNames[0]];
const range = ws['!ref'];
const regex = /([A-Z]+)(\d+):([A-Z]+)(\d+)/;
const match = range.match(regex);

if (!match) reject(new InvalidFileException());

const [, startCol, startRow, endCol, endRow] = match;

function columnToNumber(col: string) {
let num = 0;
for (let i = 0; i < col.length; i++) {
num = num * 26 + (col.charCodeAt(i) - 64);
}

return num;
}

const columns = columnToNumber(endCol) - columnToNumber(startCol) + 1;
const rows = parseInt(endRow) - parseInt(startRow) + 1;
const workbook = new exceljs.Workbook();
await workbook.xlsx.load(file.buffer);
const worksheet = workbook.getWorksheet(sheetName || workbook.worksheets[0].name);

resolve({
columns,
rows,
columns: worksheet.actualColumnCount,
rows: worksheet.actualRowCount,
});
} catch (error) {
reject(error);
Expand Down
Loading

0 comments on commit 04d00ce

Please sign in to comment.