Преобразовать файл mpp Microsoft Project MPP
В этой статье описывается, как преобразовать файлы MPP Project Microsoft Project в различные форматы вывода, включая HTML, простой текст и шаблон Project Microsoft (MPT) с использованием Aspose.tasks для .NET. API предоставляет комплексный набор функций для настройки вывода, включая обработку ресурсов, настройки заголовка, параметры стиля и фильтрацию контента. Каждый формат покрыт практическими примерами и дополнительными этапами настройки.
Microsoft Project (MSP) позволяет разработчикам сохранять данные проекта (MPP/XML) в шаблонах HTML, текста и MPT. Aspose.tasks также позволяет сохранять данные проекта в тех же форматах, аналогичных MSP. Это достигается с использованием стандартного метода сохранения, выявленного классом Project.
Сохранить данные проекта как html
Класс HTMLSaveOptions позволяет разработчикам контролировать макет и содержание экспортируемых HTML -файлов. Он поддерживает многостраничный экспорт, конфигурацию размера страницы, выбор временного масштаба, а также внедрение или экстернализующие CSS, шрифты и изображения. Aspose.tasks может экспортировать данные проекта в формат HTML. Это позволяет сохранять все данные в HTML или экспорт только требуемые страницы в HTML, используя SavePtions, как показано в следующих образцах кода.
1Project project = new Project("New Project.mpp");
2HtmlSaveOptions option = new HtmlSaveOptions();
3project.Save("SaveProjectDataAsHTML_out.html", option);
4
5// OR
6
7// Adding only one page (page number 2)
8option = new HtmlSaveOptions();
9option.Pages.Add(2);
10project.Save("SaveProjectDataAsHTML2_out.html", option);
Controlling Header and Title Output in HTML
By default, the exported HTML document includes the project name in the HTML <title>
and in the document’s page header. You can disable either of these elements by modifying the corresponding properties of the HtmlSaveOptions
class.
1Project project = new Project("New Project.mpp");
2HtmlSaveOptions htmlSaveOptions = new HtmlSaveOptions();
3
4// Determines whether to include project name in HTML title (true by default)
5htmlSaveOptions.IncludeProjectNameInTitle = false;
6
7// Determines whether to include project name in HTML page header (true by default)
8htmlSaveOptions.IncludeProjectNameInPageHeader = false;
9htmlSaveOptions.Pages = new List<int>();
10htmlSaveOptions.Pages.Add(1);
11project.Save("ControlHeaderNameDuringHTMLExport_out.html", htmlSaveOptions);
Saving Fonts, Images and CSS Styles Separately
Aspose.Tasks supports saving fonts, images, and CSS styles as external files. This is particularly useful when you want to integrate HTML output into an existing website or manage styling separately from the content. This is achieved using the HtmlSaveOptions class by providing information about CSS, Font and Image destinations. The resource export behavior can be configured through HtmlSaveOptions.ExportFonts, ExportImages, and ExportCss.
1public class ResourcePrefixForNestedResources : ICssSavingCallback, IFontSavingCallback, IImageSavingCallback
2{
3 public static void Run()
4 {
5 Project project = new Project("New Project.mpp");
6 HtmlSaveOptions options = GetSaveOptions(1);
7 project.Save("document.html", options);
8 }
9
10 public void CssSaving(CssSavingArgs args)
11 {
12 FileStream stream = new FileStream("css/" + args.FileName, FileMode.Create);
13 args.Stream = stream;
14 args.KeepStreamOpen = false;
15 args.Uri = "css/" + args.FileName;
16 }
17
18 public void FontSaving(FontSavingArgs args)
19 {
20 FileStream stream = new FileStream("fonts/" + args.FileName, FileMode.Create);
21 args.Stream = stream;
22 args.KeepStreamOpen = false;
23 args.Uri = "fonts/" + args.FileName;
24 }
25
26 public void ImageSaving(ImageSavingArgs args)
27 {
28 if (args.FileName.EndsWith("png"))
29 {
30 FileStream stream1 = new FileStream("resources/nestedResources/" + args.FileName, FileMode.Create);
31 args.Stream = stream1;
32 args.KeepStreamOpen = false;
33 args.Uri = "resources/" + args.FileName;
34 args.NestedUri = "nestedResources/" + args.FileName;
35 }
36 else
37 {
38 FileStream stream2 = new FileStream("resources/" + args.FileName, FileMode.Create);
39 args.Stream = stream2;
40 args.KeepStreamOpen = false;
41 args.Uri = "resources/" + args.FileName;
42 }
43 }
44
45 private static HtmlSaveOptions GetSaveOptions(int pageNumber)
46 {
47 HtmlSaveOptions options = new HtmlSaveOptions
48 {
49 Pages = new List<int>(),
50 IncludeProjectNameInPageHeader = false,
51 IncludeProjectNameInTitle = false,
52 PageSize = PageSize.A3,
53 Timescale = Timescale.ThirdsOfMonths,
54 ReduceFooterGap = true,
55 FontFaceTypes = FontFaceType.Ttf,
56 ExportCss = ResourceExportType.AsFile,
57 ExportFonts = ResourceExportType.AsFile,
58 ExportImages = ResourceExportType.AsFile
59 };
60
61 ResourcePrefixForNestedResources program = new ResourcePrefixForNestedResources();
62 options.FontSavingCallback = program;
63 options.CssSavingCallback = program;
64 options.ImageSavingCallback = program;
65
66 options.Pages.Clear();
67 options.Pages.Add(pageNumber);
68
69 if (!Directory.Exists("fonts"))
70 {
71 Directory.CreateDirectory("fonts");
72 }
73
74 if (!Directory.Exists("resources"))
75 {
76 Directory.CreateDirectory("resources");
77 }
78
79 if (!Directory.Exists("nestedResources"))
80 {
81 Directory.CreateDirectory("resources/nestedResources");
82 }
83
84 if (!Directory.Exists("css"))
85 {
86 Directory.CreateDirectory("css");
87 }
88
89 return options;
90 }
91}
Adding Custom Prefixes to CSS Class Names While Exporting to HTML
To avoid CSS class name conflicts when integrating the exported HTML into a broader application, you can define a custom prefix using the CssStylePrefix
property.
1Project project = new Project("New Project.mpp");
2
3HtmlSaveOptions options = new HtmlSaveOptions
4{
5 CssStylePrefix = "test_prefix"
6};
7
8project.Save("TestCssStylePrefix_out.html", options);
Save Project to Text
Project data can be exported to plain text using SaveFileFormat.TXT
. This format is intended for simple logging, debugging, or archival purposes.
1Project project = new Project("New Project.mpp");
2project.Save("SaveProjectAsText_out.txt", SaveFileFormat.TXT);
Save Project Data as Template (MPT)
Aspose.Tasks allows saving a project as a Microsoft Project Template (MPT) file. This is useful when you want to create reusable project structures. Use the SaveAsTemplate
method and configure optional parameters through the SaveTemplateOptions
class to remove actual and baseline values.
1Project project = new Project("New Project.mpp");
2ProjectFileInfo projectFileInfo = Project.GetProjectFileInfo("New Project.mpp");
3
4if (FileFormat.MPP14 == projectFileInfo.ProjectFileFormat)
5{
6 Console.WriteLine("Project file format is ok");
7}
8
9SaveTemplateOptions options = new SaveTemplateOptions();
10options.RemoveActualValues = true;
11options.RemoveBaselineValues = true;
12
13project.SaveAsTemplate("SaveProjectDataAsTemplate_out.mpt");
14
15ProjectFileInfo templateFileInfo = Project.GetProjectFileInfo(templateName);
16if (FileFormat.MPT14 == templateFileInfo.ProjectFileFormat)
17{
18 Console.WriteLine("Template FileFormat is ok");
19}
Conclusion
Aspose.Tasks for .NET provides flexible and developer-friendly methods for exporting project data to multiple formats, including HTML, text, and templates. With the help of configuration classes such as HtmlSaveOptions and SaveTemplateOptions, developers can fine-tune the output to meet a wide range of business requirements. For additional details, refer to the API Reference or explore other export scenarios in the documentation.