使用Open Xml SDK,我在WorksheetPart
中添加了一個DrawingsPart
,後來我嘗試引用WorksheetPart
內的DrawingsPart
,但我收到了ArgumentOutOfRangeException
。圖紙部分未被添加到WorksheetPart。指定參數超出有效值範圍
下面是代碼中的相關片段:
// Add a new drawings part to the worksheet
var drawingsPart = worksheetPart.AddNewPart<DrawingsPart>();
// make a drawing DOM
var drawingRootElement = new WorksheetDrawing();
// add to the drawing DOM
...
// and then...
// associate the drawing DOM to the drawings part
drawingsPart.WorksheetDrawing = drawingRootElement;
// save the drawing DOM back to the drawings part
drawingsPart.WorksheetDrawing.Save();
// and finally...
// here is where it throws the ArgumentOutOfRangeException
// whether I supply the drawingsPart as the argument
// or the value worksheet.DrawingsPart
// it reports the same exception
// I looked up the source of OpenXmlPartContainer.GetIdOfPart
// and it looks like the DrawingsPart is not yet added to the
// PartDictionary of the WorksheetPart. I wonder why?
var relationshipIdOfDrawingsPart = drawingsPart
.GetIdOfPart(worksheetPart.DrawingsPart /* drawingsPart */);
// Create a new drawing element and add it to the Worksheet DOM
var drawingElement = new DocumentFormat.OpenXml.Spreadsheet.Drawing { Id = relationshipIdOfDrawingsPart };
worksheetPart.Worksheet.Append(drawingElement);
異常詳細信息:
System.ArgumentOutOfRangeException發生的HResult = 0x80131502
消息=指定參數超出有效範圍的值。
源= DocumentFormat.OpenXml堆棧跟蹤:在在 DocumentFormat.OpenXml.Packaging.OpenXmlPartContainer.GetIdOfPart(OpenXmlPart 部分)......我的代碼
我擡頭的OpenXmlPartContainer.GetIdOfPart
源(轉載如下):
// DocumentFormat.OpenXml.Packaging.OpenXmlPartContainer
/// <summary>
/// Gets the relationship ID of the part.
/// </summary>
/// <param name="part">The part.</param>
/// <returns>The relationship ID of the part.</returns>
/// <exception cref="T:System.ArgumentNullException">Thrown when "part" is null reference.</exception>
/// <exception cref="T:System.ArgumentOutOfRangeException">Thrown when the part does not exist.</exception>
public string GetIdOfPart(OpenXmlPart part)
{
this.ThrowIfObjectDisposed();
if (part == null)
{
throw new ArgumentNullException("part");
}
if (this.PartDictionary.ContainsValue(part))
{
foreach (KeyValuePair<string, OpenXmlPart> current in this.PartDictionary)
{
if (part == current.Value)
{
return current.Key;
}
}
}
throw new ArgumentOutOfRangeException("part");
}
它看起來像DrawingsPart
沒有被添加到WorksheetPart
的PartDictionary
。我想知道爲什麼?
@mjwills我相信'worksheetPart.DrawingsPart'由代碼的第一行填充,即調用'worksheetPart.AddNewPart()'?我解壓縮了我的程序生成的輸出文件,圖紙部分在'sheet1.xml.rels'文件中。 –
@mjwills'drawingsPart'的數量在上面代碼的第三行代碼中描述:'drawingsPart.WorksheetDrawing = drawingRootElement;' –
@mjwills它在同一行代碼中被聲明和分配。 –