{"id":1021,"date":"2022-01-21T16:32:36","date_gmt":"2022-01-21T15:32:36","guid":{"rendered":"http:\/\/daxvisionerp.com\/?p=1021"},"modified":"2025-10-22T14:40:20","modified_gmt":"2025-10-22T14:40:20","slug":"create-an-excel-file-to-docuref-directly-in-d365-fo","status":"publish","type":"post","link":"https:\/\/daxvisionerp.com\/home\/create-an-excel-file-to-docuref-directly-in-d365-fo\/","title":{"rendered":"Create an Excel file to DocuRef directly in D365 SCM"},"content":{"rendered":"\n<p>This post shows how to create an Excel file from x++ code and save it to the &#8216;DocuRef&#8217; table without saving the file locally.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>using System.IO;\nusing OfficeOpenXml;\nusing OfficeOpenXml.Style;\nusing OfficeOpenXml.Table;\n\nclass ExcelExportToDocuRef_DV\n{\n    OfficeOpenXml.ExcelRange\tcell,cells;\n    public static void main(Args _args)\n    {\n        ExcelExportToDocuRef_DV excelExport = new ExcelExportToDocuRef_DV();\n\n        excelExport.run();\n    }\n\n    public void run()\n    {\n        CustTable    custTable;\n        MemoryStream memoryStream = new MemoryStream();\n        \n        SalesTable   salesTable = SalesTable::find(\"012509\");\t\n\n        using (var package = new ExcelPackage(memoryStream))\n        {\n            int\tcurrentRow = 1;\n            var\tworksheets = package.get_Workbook().get_Worksheets();\n            var\tCustTableWorksheet = worksheets.Add(\"Export\");\n            cells = CustTableWorksheet.get_Cells();\n\n            this.insertCel(currentRow,1,\"@SYS7149\");  \/\/ AccountNum\n            this.insertCel(currentRow,2,\"@SYS7572\");  \/\/ CurrencyCode\n            this.insertCel(currentRow,3,\"@SYS23784\"); \/\/ SalesGroup\n            this.insertCel(currentRow,4,\"@SYS27703\"); \/\/ DlvTerm\n   \n            while select firstonly10 AccountNum, Currency, SalesGroup, DlvTerm\n                from custTable\n            {\n                currentRow ++;\n\n                this.insertCel(currentRow,1,custTable.AccountNum);\t\t \/\/ AccountNum\n                this.insertCel(currentRow,2,custTable.Currency);\t\t  \/\/ CurrencyCode\n                this.insertCel(currentRow,3,custTable.SalesGroup);\t\t\/\/ SalesGroup\n                this.insertCel(currentRow,4,custTable.DlvTerm);\t\t\t   \/\/ SalesGroup\n            }\n\n            package.SaveAs(memoryStream);\n            str fileName = \"CustomersSaveToDocuRef_\" + date2Str(DateTimeUtil::getToday(DateTimeUtil::getUserPreferredTimeZone()), 321, DateDay::Digits2, DateSeparator::Hyphen, DateMonth::Digits2, DateSeparator::Hyphen, DateYear::Digits4) + \"_\" + time2Str(DateTimeUtil::getTimeNow(DateTimeUtil::getUserPreferredTimeZone()), TimeSeparator::Colon, TimeSeparator::Colon) + \".xlsx\";\n\t\t\t\n            this.createAttachment(salesTable.TableId,salesTable.RecId,memoryStream,fileName);\n        }\n    }\n\n    public void insertCel(int _row, int _col, anytype _value)\n    {\n        cell  = null;\n        cell  = cells.get_Item(_row, _col);\n        cell.set_Value(_value.ToString());\n    }\n\n    public void createAttachment(TableId _refTableId, RefRecId _refRecId, System.IO.MemoryStream _result, FileName _fileName)\n    {\n\n        DocuRef\t  docuRefTable;\n        DocuValue docuValueTable;\n        Microsoft.Dynamics.AX.Framework.FileManagement.DocumentLocation\t\t\tlocation;\n        Microsoft.Dynamics.AX.Framework.FileManagement.IDocumentStorageProvider storageProvider;\n\n        System.IO.Stream fileStream;\n\n        FileIOPermission permission  = new FileIOPermission(\"\", 'r');\n        permission.assert();\n        InteropPermission interopPerm = new InteropPermission(InteropKind::ClrInterop);\n        interopPerm.assert();\n        DocuType fileType = DocuType::find(DocuType::typeFile());\n\n        storageProvider = Docu::GetStorageProvider(fileType, true, curUserId());\n\n        if (_refRecId &gt; 0)\n        {\n            guid      fileId = newGuid();\n            container readcon = Binary::constructFromMemoryStream(_result).getContainer();\n\n            ttsBegin;\n            \n            docuValueTable.clear();\n            docuValueTable.FileId           = fileId;\n            docuValueTable.FileType         = \"xlsx\";\n            docuValueTable.FileName         = _fileName;\n            docuValueTable.Name             = _fileName;\n            docuValueTable.OriginalFileName = _fileName;\n            docuValueTable.File\t            = readcon;\n\n            fileStream = Binary::constructFromContainer(docuValueTable.File).getMemoryStream();\n            location   = storageProvider.SaveFile(docuValueTable.FileId, storageProvider.GenerateUniqueName(docuValueTable.OriginalFileName), System.Web.MimeMapping::GetMimeMapping(docuValueTable.OriginalFileName), fileStream);\n\n            if (location.NavigationUri)\n            {\n                docuValueTable.Path = location.get_NavigationUri().ToString();\n            }\n\n            if (location.AccessUri)\n            {\n                docuValueTable.AccessInformation = location.get_AccessUri().ToString();\n            }\n\n            docuValueTable.StorageProviderId = storageProvider.ProviderId;\n            docuValueTable.insert();\n\n            if (docuValueTable.RecId)\n            {\n                docuRefTable.clear();\n                docuRefTable.RefRecId     = _refRecid;\n                docuRefTable.RefTableId   = _refTableId;\n                docuRefTable.RefCompanyId = curext();\n                docuRefTable.Name         = \"Attachment\";\n                docuRefTable.Notes        = _fileName;\n                docuRefTable.TypeId       = 'File';\n                docuRefTable.ValueRecId   = docuValueTable.RecId;\n    \n                docuRefTable.insert();\n\n                info(\"The attachment is successfully uploaded!\");\n\n            }\n            ttsCommit;\n        }\n    }\n\n}<\/code><\/pre>\n\n\n\n<p>The attachment appeared after running the code:<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"430\" src=\"https:\/\/daxvisionerp.com\/home\/wp-content\/uploads\/2022\/01\/MicrosoftTeams-image-2-1024x430-1.png\" alt=\"\" class=\"wp-image-1352\" srcset=\"https:\/\/daxvisionerp.com\/home\/wp-content\/uploads\/2022\/01\/MicrosoftTeams-image-2-1024x430-1.png 1024w, https:\/\/daxvisionerp.com\/home\/wp-content\/uploads\/2022\/01\/MicrosoftTeams-image-2-1024x430-1-980x412.png 980w, https:\/\/daxvisionerp.com\/home\/wp-content\/uploads\/2022\/01\/MicrosoftTeams-image-2-1024x430-1-480x202.png 480w\" sizes=\"(min-width: 0px) and (max-width: 480px) 480px, (min-width: 481px) and (max-width: 980px) 980px, (min-width: 981px) 1024px, 100vw\" \/><\/figure>\n\n\n\n<p>Attachment<\/p>\n\n\n\n<figure class=\"wp-block-image size-full is-resized\"><img loading=\"lazy\" decoding=\"async\" width=\"655\" height=\"477\" src=\"https:\/\/daxvisionerp.com\/home\/wp-content\/uploads\/2022\/01\/image-2.png\" alt=\"\" class=\"wp-image-1353\" style=\"width:1108px;height:auto\" srcset=\"https:\/\/daxvisionerp.com\/home\/wp-content\/uploads\/2022\/01\/image-2.png 655w, https:\/\/daxvisionerp.com\/home\/wp-content\/uploads\/2022\/01\/image-2-480x350.png 480w\" sizes=\"(min-width: 0px) and (max-width: 480px) 480px, (min-width: 481px) 655px, 100vw\" \/><\/figure>\n\n\n\n<p>Excel file content<\/p>\n\n\n\n<p>This blogpost and code example was created by Tamas Zelinka. It is also available on GitHub: <a href=\"https:\/\/github.com\/PeterProkopecz\/AX\/tree\/master\/D365FO_TAZ_create-an-excel-file-to-docuref-directly-in-d365-fo\" target=\"_blank\" rel=\"noreferrer noopener\">https:\/\/github.com\/PeterProkopecz\/AX\/tree\/master\/D365FO_TAZ_create-an-excel-file-to-docuref-directly-in-d365-fo<\/a><\/p>\n\n\n\n<p><\/p>\n\n\n<div class=\"taxonomy-post_tag wp-block-post-terms\"><a href=\"https:\/\/daxvisionerp.com\/home\/tag\/excel-export\/\" rel=\"tag\">Excel export<\/a><span class=\"wp-block-post-terms__separator\">, <\/span><a href=\"https:\/\/daxvisionerp.com\/home\/tag\/save-to-docuref\/\" rel=\"tag\">Save to DocuRef<\/a><\/div>","protected":false},"excerpt":{"rendered":"<p>This post shows how to create an Excel file from x++ code and save it to the &#8216;DocuRef&#8217; table without saving the file locally. The attachment appeared after running the code: Attachment Excel file content This blogpost and code example was created by Tamas Zelinka. It is also available on GitHub: https:\/\/github.com\/PeterProkopecz\/AX\/tree\/master\/D365FO_TAZ_create-an-excel-file-to-docuref-directly-in-d365-fo<\/p>\n","protected":false},"author":6,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_et_pb_use_builder":"","_et_pb_old_content":"","_et_gb_content_width":"1080","footnotes":""},"categories":[19],"tags":[153,155],"class_list":["post-1021","post","type-post","status-publish","format-standard","hentry","category-dynamics-365fo","tag-excel-export","tag-save-to-docuref"],"_links":{"self":[{"href":"https:\/\/daxvisionerp.com\/home\/wp-json\/wp\/v2\/posts\/1021","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/daxvisionerp.com\/home\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/daxvisionerp.com\/home\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/daxvisionerp.com\/home\/wp-json\/wp\/v2\/users\/6"}],"replies":[{"embeddable":true,"href":"https:\/\/daxvisionerp.com\/home\/wp-json\/wp\/v2\/comments?post=1021"}],"version-history":[{"count":1,"href":"https:\/\/daxvisionerp.com\/home\/wp-json\/wp\/v2\/posts\/1021\/revisions"}],"predecessor-version":[{"id":1354,"href":"https:\/\/daxvisionerp.com\/home\/wp-json\/wp\/v2\/posts\/1021\/revisions\/1354"}],"wp:attachment":[{"href":"https:\/\/daxvisionerp.com\/home\/wp-json\/wp\/v2\/media?parent=1021"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/daxvisionerp.com\/home\/wp-json\/wp\/v2\/categories?post=1021"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/daxvisionerp.com\/home\/wp-json\/wp\/v2\/tags?post=1021"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}