【发布时间】:2019-07-29 06:52:27
【问题描述】:
我想用 openXML 库创建一个 excel 文件。文档应与数据库连接,并在单张/多张表中包含不同查询接收到的不同数据。示例结果:
SELECT * FROM dbo.MyTable1 -- data from first table
SELECT * FROM dbo.MyTable2 -- data from second table
到目前为止,我有一些工作部分的代码:
Sheets sheets = spreadsheetDocument.WorkbookPart.Workbook.AppendChild<Sheets>(new Sheets());
ConnectionsPart connPart = workbookpart.AddNewPart<ConnectionsPart>();
connPart.Connections = new Connections();
var connection = new Connection()
{
Id = 1,
Name = "Connection",
Type = 5, //ODBC
SaveData = true,
RefreshOnLoad = true,
RefreshedVersion = 5,
MinRefreshableVersion = 1,
Background = true,
DatabaseProperties = new DatabaseProperties
{
Connection =
"my-connection-string",
Command = "SELECT * FROM dbo.MyTable1",
},
};
connPart.Connections.Append(connection);
QueryTablePart qt = worksheetPart.AddNewPart<QueryTablePart>();
qt.QueryTable = new QueryTable()
{
Name = "Connection",
ConnectionId = connection.Id,
AutoFormatId = 16,
ApplyNumberFormats = true,
ApplyBorderFormats = true,
ApplyFontFormats = true,
ApplyPatternFormats = true,
ApplyAlignmentFormats = false,
ApplyWidthHeightFormats = false,
AdjustColumnWidth = true,
Headers = false,
RefreshOnLoad = true
};
// 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);
DefinedNames definedNames = new DefinedNames();
// Create a new range (name matching the QueryTable name)
DefinedName definedName = new DefinedName() { Name = "Connection", Text = "mysheet!$B$2:$B$2", };
definedNames.Append(definedName);
workbookpart.Workbook.Append(definedNames);
workbookpart.Workbook.Save();
对于单个命令的单个连接可以正常工作。问题是我不知道如何更改代码以处理多个命令(查询)。当我尝试添加第二个连接和第二个 QueryTablePart 时,创建了文档,但内容被破坏,错误提示 QueryTablePart 应该有单个根元素。有人能帮我吗?谢谢
【问题讨论】:
标签: c# sql-server excel database openxml