Excel OData QueryTable в C# - PullRequest
       6

Excel OData QueryTable в C#

0 голосов
/ 12 марта 2020

Я использую C# для создания электронной таблицы Excel, содержащей QueryTable с подачей OData, но по какой-то причине, хотя подключение к данным работает нормально, QueryTable не отображается в электронной таблице.

Вот фрагмент из моего тестового приложения (адаптировано из этот ответ о переполнении стека ):


        public static void CreateSpreadsheetWorkbook(string fileOutputPath, string odataURI)
        {
            using (
                // Create a spreadsheet document by supplying the filepath.
                // By default, AutoSave = true, Editable = true, and Type = xlsx.
                SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.
                    Create(fileOutputPath, SpreadsheetDocumentType.Workbook)
            )
            {
                // Add a WorkbookPart to the document.
                WorkbookPart workbookpart = spreadsheetDocument.AddWorkbookPart();
                workbookpart.Workbook = new Workbook();

                // Add a WorksheetPart to the WorkbookPart.
                WorksheetPart worksheetPart = workbookpart.AddNewPart<WorksheetPart>();
                worksheetPart.Worksheet = new Worksheet(new SheetData());

                // Add Sheets to the Workbook.
                Sheets sheets = spreadsheetDocument.WorkbookPart.Workbook.
                    AppendChild<Sheets>(new Sheets());

                // Add the data connection
                ConnectionsPart connPart = workbookpart.AddNewPart<ConnectionsPart>();
                connPart.Connections = new Connections();

                Connection c = new Connection()
                {
                    Id = 1234, //should be automatic??
                    Name = "GetProductList",
                    Type = 4, //Web Query
                    RefreshedVersion = 4,
                    MinRefreshableVersion = 1,
                    Background = true,
                    SaveData = true,
                    RefreshOnLoad = true,
                    WebQueryProperties = new WebQueryProperties()
                    {
                        XmlSource = true,
                        SourceData = true,
                        ParsePreTag = true,
                        Consecutive = true,
                        RefreshedInExcel2000 = true,
                        Url = odataURI
                    }
                };
                connPart.Connections.Append(c);

                // Append a new worksheet and associate it with the workbook.
                Sheet sheet = new Sheet()
                {
                    Id = spreadsheetDocument.WorkbookPart.GetIdOfPart(worksheetPart),
                    SheetId = 1,
                    Name = "Products"
                };
                sheets.Append(sheet);

                DefinedNames definedNames = new DefinedNames();    //Create the collection
                DefinedName definedName = new DefinedName()
                { Name = "ProductTable", Text = "Products!$A$1:$A$1" };   // Create a new range (name matching the QueryTable name) 
                definedNames.Append(definedName);                  // Add it to the collection
                workbookpart.Workbook.Append(definedNames);        // Add collection to the workbook

                QueryTablePart qt = worksheetPart.AddNewPart<QueryTablePart>();
                qt.QueryTable = new QueryTable()
                {
                    Name = "ProductTable",
                    ConnectionId = 1234,
                    AutoFormatId = 16,//From where?
                    ApplyNumberFormats = true,
                    ApplyBorderFormats = true,
                    ApplyFontFormats = true,
                    ApplyPatternFormats = true,
                    ApplyAlignmentFormats = true,
                    ApplyWidthHeightFormats = true,
                    RefreshOnLoad = true
                };

                // Save and close the document.
                workbookpart.Workbook.Save();
                spreadsheetDocument.Close();
            }
        }

Электронная таблица создана нормально, данные отображаются в ячейке A1, но это не так не может появиться в таблице, просто гигантская JSON строка типа

{"@odata.context":"https://<redacted>.azurewebsites.net/odata/$metadata#Products","value":[{"Id":1,"ProductName":"Malt Whisky"} . . .

Кто-нибудь может посоветовать, где я ошибаюсь? Я искал в Интернете, и примеры, показывающие функциональность QueryTable, трудно найти.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...