Import & Export
Facade API | Has Paid Plan | Univer Server | Univer on Node.js | Preset |
---|---|---|---|---|
✅ | ✅ | ✅ | - | UniverDocsAdvancedPreset |
Univer implements the import and export of Word DOCX format files through plugins and backend services. The plugin integrates the ability to interact with the server and provides an import and export menu entry.
This feature includes the following plugin packages:
Why does Univer implement import and export through backend services?
Importing and exporting implemented only through the frontend cannot meet enterprise requirements in terms of performance or effect. Therefore, we provide backend services to implement import and export features. You can use some open-source DOCX parsing libraries to parse files into data structures that conform to the IDocumentData
interface, and then import the data into Univer through the Facade API.
Presets Installation
import { createUniver, defaultTheme, LocaleType, merge } from '@univerjs/presets';
import { UniverDocsCorePreset } from '@univerjs/presets/preset-docs-core';
import UniverPresetDocsCoreEnUS from '@univerjs/presets/preset-docs-core/locales/en-US';
import { UniverDocsAdvancedPreset } from '@univerjs/presets/preset-docs-advanced';
import UniverPresetDocsAdvancedEnUS from '@univerjs/presets/preset-docs-advanced/locales/en-US';
import { UniverDocsDrawingPreset } from '@univerjs/presets/preset-docs-drawing'
import UniverPresetDocsDrawingEnUS from '@univerjs/presets/preset-docs-drawing/locales/en-US'
import '@univerjs/presets/lib/styles/preset-docs-core.css'
import '@univerjs/presets/lib/styles/preset-docs-drawing.css'
import '@univerjs/presets/lib/styles/preset-docs-advanced.css'
const { univerAPI } = createUniver({
locale: LocaleType.EN_US,
locales: {
[LocaleType.EN_US]: merge(
{},
UniverPresetDocsCoreEnUS,
UniverPresetDocsDrawingEnUS,
UniverPresetDocsAdvancedEnUS,
),
},
theme: defaultTheme,
presets: [
UniverDocsCorePreset(),
UniverDocsDrawingPreset(),
UniverDocsAdvancedPreset({
universerEndpoint: 'http://localhost:3010',
}),
],
});
Configuration
UniverDocsAdvancedPreset({
// Univer Server endpoint address
universerEndpoint?: string;
license?: string;
})
Piecemeal Installation
npm install @univerjs-pro/exchange-client @univerjs-pro/docs-exchange-client
import { LocaleType, merge, Univer } from '@univerjs/core';
import { defaultTheme } from "@univerjs/design";
import { UniverExchangeClientPlugin } from '@univerjs-pro/exchange-client';
import { UniverDocsExchangeClientPlugin } from '@univerjs-pro/docs-exchange-client';
import ExchangeClientEnUS from '@univerjs-pro/exchange-client/locale/en-US';
import '@univerjs-pro/exchange-client/facade';
import '@univerjs-pro/exchange-client/lib/index.css';
const univer = new Univer({
theme: defaultTheme,
locale: LocaleType.EN_US,
locales: {
[LocaleType.EN_US]: merge(
ExchangeClientEnUS
),
},
});
const UNIVER_SERVER_ENDPOINT = `http://localhost:8000`;
univer.registerPlugin(UniverExchangeClientPlugin, {
// Configurations below are for Univer Server, please modify them according to actual circumstances
uploadFileServerUrl: `${UNIVER_SERVER_ENDPOINT}/universer-api/stream/file/upload`,
importServerUrl: `${UNIVER_SERVER_ENDPOINT}/universer-api/exchange/{type}/import`,
exportServerUrl: `${UNIVER_SERVER_ENDPOINT}/universer-api/exchange/{type}/export`,
getTaskServerUrl: `${UNIVER_SERVER_ENDPOINT}/universer-api/exchange/task/{taskID}`,
signUrlServerUrl: `${UNIVER_SERVER_ENDPOINT}/universer-api/file/{fileID}/sign-url`,
downloadEndpointUrl: `${UNIVER_SERVER_ENDPOINT}/`,
});
univer.registerPlugin(UniverDocsExchangeClientPlugin);
Configuration
univer.registerPlugin(UniverExchangeClientPlugin, {
// Univer Server Configuration
downloadEndpointUrl?: string;
uploadFileServerUrl?: string;
importServerUrl?: string;
exportServerUrl?: string;
getTaskServerUrl?: string;
signUrlServerUrl?: string;
// Maximum timeout time, in milliseconds
maxTimeoutTime?: number;
});
Custom Usage
The default behavior of importing is: after importing successfully through the import entry in the menu bar, a prompt box will pop up in the lower left corner of the page, displaying the information of the successful import. Click the corresponding link to access the imported document.
If you are not satisfied with the default import and export behavior of the plugin, you can refer to the following code to customize the import and export behavior.
Get the document URL
or File
object , and then call the importDOCXToUnitIdAsync
or importDOCXToSnapshotAsync
method of the Facade API to import. The reference code is as follows:
const url = 'https://example.com/filename.docx'; // Your Excel file URL
// Function to fetch and convert the URL to a File object.
// Here, the fetch API is used to directly obtain the file,
// which may need to be modified according to the actual situation,
// such as file address authentication and cross-domain issues.
async function fetchExcelFile(url) {
try {
const response = await fetch(url);
const blob = await response.blob();
return new File([blob], 'filename.docx', { type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' });
} catch (error) {
console.error('Failed to fetch the file:', error);
}
}
// Fetch the file and import it as a snapshot
// If the URL file address is not authenticated,
// you can directly pass it to the importDOCXToSnapshotAsync or importDOCXToUnitIdAsync method
fetchExcelFile(url).then(async file => {
if (file) {
// Modify the following code according to the actual situation
univerAPI.importDOCXToSnapshotAsync(file).then(snapshot => {
console.log('Snapshot created:', snapshot);
// Create a new document with the snapshot
univerAPI.createUniverDoc(snapshot);
});
univerAPI.importDOCXToUnitIdAsync(file).then(unitId => {
console.log('Unit ID created:', unitId);
// Utilize automatic data loading in conjunction with collaborative editing. https://docs.univer.ai/en-US/guides/docs/features/collaboration#loading-collaborative-documents
const url = new URL(window.location.href);
url.searchParams.set('unit', unitId);
url.searchParams.set('type', '1'); // The meaning of "1" is String(UniverInstanceType.UNIVER_DOC)
console.log('Unit URL:', url.toString());
window.location.href = url.toString();
// Or call API: univerAPI.loadServerUnit(unitId, 1) to load the document. For specific parameters, refer to https://reference.univer.ai/en-US/classes/FUniver#loadserverunit
// This API requires UniverDocsCollaborationPreset (version after 0.6.9) or manually importing @univerjs-pro/collaboration-client/facade (version 0.6.7+) to use
});
}
});
Facade API
Import DOCX
To import via API, use the Facade API to call the features provided by the import/export plugin. Make sure to include the necessary dependencies before use.
Import DOCX and Get unitId
In a collaborative environment, each document has a unique unitId
. Use the API importDOCXToUnitIdAsync
to pass in the file
parameter and return unitId
, which can be used to access the document. The file
parameter can be a File object or a URL to a remote file.
// Accepts a File object
const unitId = await univerAPI.importDOCXToUnitIdAsync(file);
// Or accepts a URL to a remote file
// const unitId = await univerAPI.importDOCXToUnitIdAsync('https://example.com/filename.docx');
// Utilize automatic data loading in conjunction with collaborative editing. https://docs.univer.ai/en-US/guides/docs/features/collaboration#loading-collaborative-documents
const url = new URL(window.location.href);
url.searchParams.set('unit', unitId);
url.searchParams.set('type', "1"); // The meaning of "1" is String(UniverInstanceType.UNIVER_DOC)
console.log('Unit URL:', url.toString());
window.location.href = url.toString();
// Or call API: univerAPI.loadServerUnit(unitId, 1) to load the document. For specific parameters, refer to https://reference.univer.ai/en-US/classes/FUniver#loadserverunit
// This API requires UniverDocsCollaborationPreset (version after 0.6.9) or manually importing @univerjs-pro/collaboration-client/facade (version 0.6.7+) to use
Import DOCX and Get Document Data
When using the import DOCX capability separately in a non-collaborative environment, you can use the API importDOCXToSnapshotAsync
to return the document data in the IDocumentData format.
// Accepts a File object
const snapshot = await univerAPI.importDOCXToSnapshotAsync(file);
// Or accepts a URL to a remote file
// const snapshot = await univerAPI.importDOCXToSnapshotAsync('https://example.com/filename.xlsx');
console.log('Snapshot created:', snapshot);
// Create a new document with the snapshot
univerAPI.createUniverDoc(snapshot);
Export DOCX
To export via API, use the Facade API to call the features provided by the import/export plugin. Make sure to include the necessary dependencies before use.
Export DOCX via unitId
Use the API exportDOCXByUnitIdAsync
to pass in the unitId
parameter and return an File
object. You can use downloadFile
to download the file or process it further.
import { downloadFile } from '@univerjs-pro/exchange-client';
const fDocument = univerAPI.getActiveDocument();
const unitId = fDocument.getId();
const file = await univerAPI.exportDOCXByUnitIdAsync(unitId);
// Download the file
downloadFile(file, 'univer', 'docx');
Export DOCX via Document Data
Use the API exportDOCXBySnapshotAsync
to pass in the table data in the IDocumentData
format and return a File
object.
import { downloadFile } from '@univerjs-pro/exchange-client';
const fDocument = univerAPI.getActiveDocument();
const snapshot = fDocument.getSnapshot();
const file = await univerAPI.exportDOCXBySnapshotAsync(snapshot);
// Download the file
downloadFile(file, 'univer', 'xlsx');
Server-Side Data Conversion
Univer’s server provides import and export APIs, but the server-side converted data is not consistent with the Univer format. If you use our frontend import/export plugin @univerjs-pro/exchange-client
, the data is automatically converted by default without any additional processing. However, if you use the server’s import/export API directly, you need to use the following methods to convert the data.
Converting Snapshot to Document Data
After importing, the obtained Snapshot JSON data needs to be converted into the IDocumentData
format for use in Univer.
import { transformSnapshotJsonToDocumentData } from '@univerjs-pro/exchange-client';
const documentData = transformSnapshotJsonToDocumentData(json);
Converting Document Data to Snapshot
Before exporting, the IDocumentData
format data needs to be converted into Snapshot JSON data so that it can be passed to the server for export.
import { transformDocumentDataToSnapshotJson } from '@univerjs-pro/exchange-client';
const snapshotJson = transformDocumentDataToSnapshotJson(documentData);