我有许多生成报告的 ASMX Web 服务,并希望通过添加一个链接来帮助我们的用户下载包含 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
类的实例