Skip to content

πŸ”₯ πŸ”₯ πŸ”₯ A Free & Self-hostable Airtable Alternative

feat: Add Excel download functionality to data export

claude[bot]515a22ffb67b
diff --git a/packages/nc-gui/components/smartsheet/toolbar/ExportSubActions.vue b/packages/nc-gui/components/smartsheet/toolbar/ExportSubActions.vue
index c73e7f892b..84b42fd336 100644
--- a/packages/nc-gui/components/smartsheet/toolbar/ExportSubActions.vue
+++ b/packages/nc-gui/components/smartsheet/toolbar/ExportSubActions.vue
@@ -186,4 +186,4 @@ const exportFile = async (exportType: ExportTypes) => {
JSON
</div>
</NcMenuItem>
-</template>
+ <NcMenuItem v-e="['a:download:excel']" @click.stop="exportFile(ExportTypes.EXCEL)">\n <div class="flex flex-row items-center nc-base-menu-item !py-0 children:flex-none">\n <GeneralLoader v-if="isExporting" size="regular" />\n <component :is="iconMap.ncFileTypeExcel" v-else class="w-4" />\n <!-- Download as Excel -->\n Excel\n </div>\n </NcMenuItem>\n</template>
diff --git a/packages/nocodb/src/modules/jobs/jobs/data-export/data-export.processor.ts b/packages/nocodb/src/modules/jobs/jobs/data-export/data-export.processor.ts
index d0348fb8da..0234834481 100644
--- a/packages/nocodb/src/modules/jobs/jobs/data-export/data-export.processor.ts
+++ b/packages/nocodb/src/modules/jobs/jobs/data-export/data-export.processor.ts
@@ -5,6 +5,7 @@ import { Injectable, Logger } from '@nestjs/common';
import dayjs from 'dayjs';
import utc from 'dayjs/plugin/utc';
import timezone from 'dayjs/plugin/timezone';
+import * as XLSX from 'xlsx';
import type { Job } from 'bull';
dayjs.extend(utc);
@@ -12,9 +13,10 @@ dayjs.extend(timezone);
import { type DataExportJobData } from '~/interface/Jobs';
import { elapsedTime, initTime } from '~/modules/jobs/helpers';
import { ExportService } from '~/modules/jobs/jobs/export-import/export.service';
-import { Base, Model, PresignedUrl, View } from '~/models';
+import { Base, Model, PresignedUrl, View, Source } from '~/models';
import { NcError } from '~/helpers/catchError';
import NcPluginMgrv2 from '~/helpers/NcPluginMgrv2';
+import NcConnectionMgrv2 from '~/utils/common/NcConnectionMgrv2';
function getViewTitle(view: View) {
return view?.title;
@@ -37,7 +39,7 @@ export class DataExportProcessor {
ncSiteUrl,
} = job.data;
- if (exportAs !== 'csv' && exportAs !== 'json')
+ if (exportAs !== 'csv' && exportAs !== 'json' && exportAs !== 'xlsx')
NcError.notImplemented(`Export as ${exportAs}`);
const hrTime = initTime();
@@ -63,72 +65,63 @@ export class DataExportProcessor {
view,
)}) ${date}`;
- const fileExtension = exportAs === 'json' ? 'json' : 'csv';
+ const fileExtension =
+ exportAs === 'json' ? 'json' : exportAs === 'xlsx' ? 'xlsx' : 'csv';
const destPath = `nc/uploads/data-export/${dateFolder}/${modelId}/${filename}.${fileExtension}`;
let url = null;
try {
- const dataStream = new Readable({
- read() {},
- });
+ if (exportAs === 'xlsx') {
+ url = await this.exportAsExcel(context, {
+ model,
+ view,
+ options,
+ storageAdapter,
+ destPath,
+ });
+ } else {
+ const dataStream = new Readable({
+ read() {},
+ });
- dataStream.setEncoding('utf8');
-
- const encodedStream =
- options?.encoding &&
- options.encoding !== 'utf-8' &&
- iconv.encodingExists(options.encoding)
- ? dataStream
- .pipe(iconv.decodeStream('utf-8'))
- .pipe(iconv.encodeStream(options?.encoding || 'utf-8'))
- : dataStream;
-
- if (
- exportAs === 'csv' &&
- (!options?.encoding || options.encoding === 'utf-8') &&
- options.includeByteOrderMark
- ) {
- // Push UTF-8 BOM at the start
- dataStream.push('\uFEFF');
- }
+ dataStream.setEncoding('utf8');
- let error = null;
+ const encodedStream =
+ options?.encoding &&
+ options.encoding !== 'utf-8' &&
+ iconv.encodingExists(options.encoding)
+ ? dataStream
+ .pipe(iconv.decodeStream('utf-8'))
+ .pipe(iconv.encodeStream(options?.encoding || 'utf-8'))
+ : dataStream;
- const uploadFilePromise = (storageAdapter as any)
- .fileCreateByStream(destPath, encodedStream)
- .catch((e) => {
- this.logger.error(e);
- error = e;
- });
+ if (
+ ['csv', 'xlsx'].includes(exportAs) &&
+ (!options?.encoding || options.encoding === 'utf-8') &&
+ options.includeByteOrderMark
+ ) {
+ // Push UTF-8 BOM at the start
+ dataStream.push('\uFEFF');
+ }
- if (exportAs === 'json') {
- this.exportService
- .streamModelDataAsJson(context, {
- dataStream,
- baseId: model.base_id,
- modelId: model.id,
- viewId: view.id,
- ncSiteUrl: ncSiteUrl,
- includeCrossBaseColumns: true,
- filterArrJson: options.filterArrJson,
- sortArrJson: options.sortArrJson,
- })
+ let error = null;
+
+ const uploadFilePromise = (storageAdapter as any)
+ .fileCreateByStream(destPath, encodedStream)
.catch((e) => {
- this.logger.debug(e);
- dataStream.push(null);
+ this.logger.error(e);
error = e;
});
- } else {
+
+ if (exportAs === 'json') {
this.exportService
- .streamModelDataAsCsv(context, {
+ .streamModelDataAsJson(context, {
dataStream,
- linkStream: null,
baseId: model.base_id,
modelId: model.id,
viewId: view.id,
ncSiteUrl: ncSiteUrl,
- delimiter: options?.delimiter,
includeCrossBaseColumns: true,
filterArrJson: options.filterArrJson,
sortArrJson: options.sortArrJson,
@@ -138,15 +131,39 @@ export class DataExportProcessor {
dataStream.push(null);
error = e;
});
+ } else {
+ this.exportService
+ .streamModelDataAsCsv(context, {
+ dataStream,
+ linkStream: null,
+ baseId: model.base_id,
+ modelId: model.id,
+ viewId: view.id,
+ ncSiteUrl: ncSiteUrl,
+ delimiter: options?.delimiter,
+ includeCrossBaseColumns: true,
+ filterArrJson: options.filterArrJson,
+ sortArrJson: options.sortArrJson,
+ })
+ .catch((e) => {
+ this.logger.debug(e);
+ dataStream.push(null);
+ error = e;
+ });
}
- url = await uploadFilePromise;
+ url = await uploadFilePromise;
+ }
// if url is not defined, it is local attachment
const mimetype = exportAs === 'json' ? 'application/json' : 'text/csv';
const filenameWithExt = `${filename}.${fileExtension}`;
if (!url) {
+ const mimeType =
+ exportAs === 'xlsx'
+ ? 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
+ : 'text/csv';
url = await PresignedUrl.getSignedUrl({
pathOrUrl: path.join(destPath.replace('nc/uploads/', '')),
filename: filenameWithExt,
@@ -156,6 +173,10 @@ export class DataExportProcessor {
encoding: options?.encoding || 'utf-8',
});
} else {
+ const mimeType =
+ exportAs === 'xlsx'
+ ? 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
+ : 'text/csv';
url = await PresignedUrl.getSignedUrl({
pathOrUrl: url,
filename: filenameWithExt,
@@ -193,4 +214,109 @@ export class DataExportProcessor {
url,
};
}
+
+ private async exportAsExcel(
+ context,
+ param: {
+ model: any;
+ view: any;
+ options: any;
+ storageAdapter: any;
+ destPath: string;
+ },
+ ): Promise<string> {
+ const { model, view, options, storageAdapter, destPath } = param;
+
+ const allData = await this.getAllDataForExcel(context, {
+ model,
+ view,
+ options,
+ });
+
+ const workbook = XLSX.utils.book_new();
+ const worksheet = XLSX.utils.json_to_sheet(allData.rows, {
+ header: allData.headers,
+ });
+
+ XLSX.utils.book_append_sheet(workbook, worksheet, 'Data');
+
+ const excelBuffer = XLSX.write(workbook, {
+ type: 'buffer',
+ bookType: 'xlsx',
+ });
+
+ const dataStream = new Readable({
+ read() {},
+ });
+ dataStream.push(excelBuffer);
+ dataStream.push(null);
+
+ return await (storageAdapter as any).fileCreateByStream(
+ destPath,
+ dataStream,
+ );
+ }
+
+ private async getAllDataForExcel(
+ context,
+ param: {
+ model: any;
+ view: any;
+ options: any;
+ },
+ ) {
+ const { model, view, options } = param;
+
+ const allRows = [];
+ let headers = [];
+ let offset = 0;
+ const limit = 1000;
+ let hasMore = true;
+
+ const source = await Source.get(context, model.source_id);
+ const baseModel = await Model.getBaseModelSQL(context, {
+ id: model.id,
+ viewId: view.id,
+ dbDriver: await NcConnectionMgrv2.get(source),
+ });
+
+ while (hasMore) {
+ const result = await this.exportService.datasService.dataList(context, {
+ model,
+ view,
+ query: {
+ limit,
+ offset,
+ filterArrJson: options.filterArrJson,
+ sortArrJson: options.sortArrJson,
+ },
+ baseModel,
+ ignoreViewFilterAndSort: false,
+ limitOverride: limit,
+ skipSortBasedOnOrderCol: true,
+ });
+
+ if (result.list.length === 0) {
+ hasMore = false;
+ break;
+ }
+
+ if (offset === 0 && result.list.length > 0) {
+ headers = Object.keys(result.list[0]);
+ }
+
+ allRows.push(...result.list);
+
+ if (result.pageInfo.isLastPage) {
+ hasMore = false;
+ } else {
+ offset += limit;
+ }
+ }
+
+ return {
+ headers,
+ rows: allRows,
+ };
+ }
}