使用C#在Open XML电子表格中创建QueryTable

时间:2013-06-21 13:43:19

标签: c# excel-2010 openxml-sdk

我有一些生成报告的ASMX网络服务,并希望通过添加链接来帮助我们的用户下载包含Web服务的预配置和格式化查询表的.XLSX文件。

他们将能够像现在一样构建自己的图表和派生报告,但也能够刷新数据而无需重建所有内容。

var machStore = IsolatedStorageFile.GetMachineStoreForAssembly();
string fileName = Path.ChangeExtension(Path.GetRandomFileName(), ".xlsx");

using (
    IsolatedStorageFileStream ifStream = new IsolatedStorageFileStream(
        fileName,
        FileMode.CreateNew,
        FileAccess.ReadWrite,
        FileShare.Read,
        machStore
    )
)
{
    using (
        SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Create(
            ifStream,
            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());

        ConnectionsPart connPart = workbookpart.AddNewPart<ConnectionsPart>();
        connPart.Connections = new Connections();

        Connection c = new Connection(){
            Id = 1, //should be automatic??
            Name = "List",
            Type = 4, //Web Query
            RefreshedVersion = 4,
            MinRefreshableVersion= 1,
            Background = false,
            SaveData = true,
            RefreshOnLoad = true,
            WebQueryProperties = new WebQueryProperties()
            {
                XmlSource = true,
                SourceData = true,
                ParsePreTag = true,
                Consecutive = true,
                RefreshedInExcel2000 = true,
                Url = "http://server/data/Demand.asmx/List"
            }
        };
        connPart.Connections.Append(c);

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

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

        workbookpart.Workbook.Save();

        // Close the document.
        spreadsheetDocument.Close();
    }
    ifStream.Position = 0;
    response.Clear();
    response.AddHeader("content-disposition", "attachment; filename=" + fileName);
    response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
    ifStream.CopyTo(response.OutputStream);

}

下载时,该文件在Excel 2010中打开,但查询表不显示为工作表。 DocumentFormat.OpenXml的文档没有明确说明我应该如何处理QueryTable类的实例

1 个答案:

答案 0 :(得分:2)

您需要添加

DefinedNames definedNames = new DefinedNames();    //Create the collection
DefinedName definedName = new DefinedName()
    { Name = "List", Text="mysheet!$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

并删除该行

sheets.Append(qt.QueryTable);