# Import and export MS Project files

> Let users open MS Project XML files in the Gantt with a preview step, keep your own task fields across a round trip, and export the schedule back to XML.

Project managers keep plans in MS Project, ProjectLibre or a PPM tool and want to open them in your app, edit them, and send them back. This recipe adds an **Import** button with a preview of what the file contains, merges your own task fields back in after import, and exports the result as MS Project XML.

## Steps

1. Read the file as text and parse it with `readMSProjectXML()` to show a preview without touching the Gantt.
2. On confirmation, load it with `fromMSProjectXML()`, or with `fromJSON()` after merging your own fields.
3. Export with `toMSProjectXML()` and offer it as a download.

## Preview the file

`readMSProjectXML(xml, warn?)` returns plain project data in the shape of `toJSON()` output, so you can inspect it before it replaces anything:

```ts title="project-import.ts"
import { readMSProjectXML, type MspImportResult } from '@birchui/gantt';

export interface ImportPreview {
  data: MspImportResult;
  warnings: string[];
  summary: string;
}

export async function previewProjectFile(file: File): Promise<ImportPreview> {
  const warnings: string[] = [];
  const data = readMSProjectXML(await file.text(), (message) => warnings.push(message));
  const milestones = data.tasks.filter((task) => task.type === 'milestone').length;
  const summary =
    `${data.name ?? file.name}: ${data.tasks.length} tasks, ${milestones} milestones, ` +
    `${data.dependencies?.length ?? 0} links, ${data.calendars?.length ?? 0} calendars`;
  return { data, warnings, summary };
}
```

Text without a `<Project>` element throws a `SyntaxError`. Catch it to show a friendly message:

```ts title="import-button.ts"
fileInput.addEventListener('change', async () => {
  const file = fileInput.files?.[0];
  if (!file) return;
  try {
    const preview = await previewProjectFile(file);
    const ok = await confirmDialog(preview.summary, preview.warnings);
    if (ok) applyImport(preview.data);
  } catch (error) {
    showToast(error instanceof SyntaxError ? `${file.name} is not an MS Project XML file.` : String(error));
  } finally {
    fileInput.value = '';
  }
});
```

## Keep your own fields

MS Project XML does not carry your own task fields, task colors or `resourceIds`. The export writes your task ids to the **Text1** custom field and the import reads them back, so you can merge the fields you keep in your database by id:

```ts title="apply-import.ts"
import type { GanttTask, MspImportResult } from '@birchui/gantt';

interface SiteTask extends GanttTask {
  costCode?: string;
  siteManager?: string;
}

function applyImport(data: MspImportResult) {
  const current = new Map((gantt.toJSON().tasks as SiteTask[]).map((task) => [task.id, task]));
  const tasks = data.tasks.map((task) => {
    const existing = current.get(task.id);
    return existing
      ? { ...task, costCode: existing.costCode, siteManager: existing.siteManager, color: existing.color }
      : task;
  });
  gantt.fromJSON({ ...data, tasks });
}
```

If you do not need to merge anything, `gantt.fromMSProjectXML(xml)` parses and loads in one call.

## Export

```ts title="export-button.ts"
function downloadProjectXml(fileName: string) {
  const xml = gantt.toMSProjectXML();
  const url = URL.createObjectURL(new Blob([xml], { type: 'application/xml' }));
  const link = document.createElement('a');
  link.href = url;
  link.download = fileName;
  link.click();
  URL.revokeObjectURL(url);
}

exportButton.addEventListener('click', () => downloadProjectXml('warehouse-fit-out.xml'));
```

## Convert on a server

The reader and writer need no DOM. A route that accepts an upload and stores it as JSON:

```ts title="server/import-project.ts"
import { createGanttProject } from '@birchui/gantt';

app.post('/api/projects/:id/import', async (request, response) => {
  const warnings: string[] = [];
  const project = createGanttProject({ timeZone: 'Europe/London', warn: (message) => warnings.push(message) });
  try {
    project.fromMSProjectXML(await request.text());
  } catch {
    return response.status(400).json({ error: 'The file is not MS Project XML.' });
  }
  await db.projects.update(request.params.id, { data: project.toJSON() });
  response.json({ finish: project.getProjectRange().end, warnings });
});
```

## Pitfalls

- **Imports clear the undo history.** `fromMSProjectXML()` and `fromJSON()` replace the project. Ask for confirmation first, as above.
- **Ids from other tools.** A file that never went through your app has no Text1 values, so task ids are the file's UIDs and links get ids such as `'survey->permit'`. Match by name or WBS if you need to merge such files.
- **Percentage lags** are imported as no lag, with a warning. Show the warnings from the preview.
- **Time zones.** Dates in MS Project XML have no zone. They are read and written as wall-clock time in the Gantt's `timeZone`, so set the same zone on the server and in the browser.
- **Resources are not exchanged.** Keep assignments in your own data. See [What is not exchanged](https://docs.birchui.com/gantt/ms-project.md#what-is-not-exchanged).

## Related

- [MS Project XML](https://docs.birchui.com/gantt/ms-project.md) for the full field mapping.
- [Headless engine](https://docs.birchui.com/gantt/headless.md).
- [Critical path report](https://docs.birchui.com/recipes/gantt-critical-path-report.md).
