2009-12-29 2 views
4

업데이트 : 이것은 Silverlight 4 베타의 확인 된 버그입니다. http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=523052Silverlight 4의 ComAutomationFactory를 사용하여 Word 문서 필드를 반복합니다.

저는이 문제를 완전히 해결 된 WPF 응용 프로그램으로 바꾸고 일반 구형 Microsoft.Office.Interop.Word를 사용하여이 문제를 해결했습니다. 하지만 ComAutomationFactory의 동적 값을 사용하여이 작업을 수행하는 방법에 대해서는 여전히 관심이 많습니다.

더 많은 C# 4.0 질문 일지 모르지만 신뢰할 수있는 SL4 앱의 ComAutomationFactory 클래스를 활용하여 Word 문서를로드하고 텍스트를 변경하고 인쇄하십시오. 일반 윈도우 응용 프로그램을 사용

, 그것은 꽤 쉽게 :

Object oMissing = System.Reflection.Missing.Value; 
    Object oTrue = true; 
    Object oFalse = false; 

    Application oWord = new Application(); 
    Document oWordDoc = new Document(); 

    oWord.Visible = false; 

    object oTemplatePath = "C:\\Users\\jwest\\Desktop\\DocumentTemplate.dotx"; 
    oWordDoc = oWord.Documents.Add(ref oTemplatePath, ref oMissing, ref oMissing, ref oMissing); 

    foreach (Field myMergeField in oWordDoc.Fields) 

그러나, SL4 당신이 동적 키워드를 사용해야합니다.

Object oMissing = System.Reflection.Missing.Value; 
    Object oTrue = true; 
    Object oFalse = false; 

    dynamic oWord = ComAutomationFactory.CreateObject("Word.Application"); 

    oWord.Visible = false; 

    object oTemplatePath = "C:\\Users\\jwest\\Desktop\\DocumentTemplate.dotx"; 
    dynamic oWordDoc = oWord.Documents.Add(ref oTemplatePath, ref oMissing, ref oMissing, ref oMissing); 
    dynamic fields = oWordDoc.Fields; 

    foreach (var myMergeField in fields) 

하는 경우에는 내가 암시를 IEnumerable ComAutomationMetaObjectProvider을 변환 할 수 없다는 런타임 오류를 얻을 : 내 필드를 반복하려고 할 때까지 잘 작동합니다. 내가하는 일과 상관없이 내 Word com 객체와 관련된 모든 속성은 ComAutomationMetaObjectProvider 유형이며 반복 할 수 없습니다.

회원으로부터 String 필드를 가져와야한다고 언급했습니다. HRESULT : 이것은 흥미로운 예외가 발생

 for (int i = 0; i < oWordDoc.Fields.Count; i++) 
     { 
      String field = oWordDoc.Fields.Item[i].Result.Text; 
     } 

0x800A16E6 봤는 절대적으로 아무것도를 제공하지 않습니다.

+0

나는 당신의 질문에 대한 답을 모르는 ... 비록 콘솔 응용 프로그램에서 잘 작동하지만 그냥 C# 4, 당신은 shouldn 지적하고 싶었 'ref oMissing' 매개 변수가 필요합니다. – CoderDennis

답변

6

확실히 C# 문제는 아닙니다. VB.NET에서도 동일한 문제가 있습니다. 여기에 버그가 있거나 문서화되지 않은 것이 있지만, 두 경우 모두 컬렉션 객체를 선언 할 수없는 것으로 보입니다.

그러나 다른 방법이 있습니다. 컬렉션의 개별 구성원에 액세스하는 것입니다. 다음은 VB.NET에서 예제로 Fields.Item을 통해 반복 할 수있는 샘플입니다. (오류 확인 또는 여기의 Word 종료 내 .dotx 두 개의 필드 - 1) 날짜 및 2) 작성자가 있습니다.

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles Button1.Click 
    Dim wrd As Object = ComAutomationFactory.CreateObject("Word.Application") 
    Dim path As String = "C:\Users\me\test.dotx" 
    Dim wordDoc As Object = wrd.Documents.Add(path) 
    Dim fieldsCount As Integer = wordDoc.Fields.Count 
    Dim fieldResults As String = Nothing 
    For i As Integer = 1 To fieldsCount 
     fieldResults = fieldResults & " " & wordDoc.Fields.Item(i).Result.Text & vbNewLine 
    Next 
    TextBox1.Text = "Field Results: " & fieldResults 
End Sub 
+0

흥미 롭군요. 나는 똑같은 것을 시도했지만 오히려 일반적인 오류 메시지를 받았다. 나는 그 질문을 갱신 할 것이다. – James

+0

VB에서 C# 또는 Dim As Object로 'dynamic'을 사용하여 wordDoc.Fields.Item (i) .Result.Text를 설정하려고하면 위에서 언급 한 것과 같은 오류가 발생합니다. 그것은 작동하지만 String으로 치수를 기입하십시오. 그래서 Dim sixField as String = wordDoc.Fields.Item (6) .Result.Text라고 말할 수 있습니다. 오, 또 다른 한가지 - "내 필드를 반복 할 때까지는 제대로 작동합니다."라고 말하면 실제로 "동적 필드 = oWordDoc.Fields;"가 나옵니다. 왜냐하면 필드가 ComAutomationMetaObjectProvider 유형에 할당되기 때문입니다. 나는 "개체의 Ienumerable 같은 희미한 필드"같은 것들을 시도했지만 너무 실패합니다. –

+0

Fields.Item [i] .Result.Text를 통해 액세스하려고 할 때 여전히 HRESULT : 0x800A16E6 예외가 발생합니다.물론, 나는 내 VB를 C#으로 잘못 번역하고있을 수있다. 질문을 업데이트했습니다. – James

1

ComAutomationFactory의 Silverlight 4.0 구현과 관련이있을 수 있습니다. VS2K10 베타 2가 없으므로 확인할 수 없습니다. "동적"유형을 사용

은 '

dynamic oWord = //ComAutomationFactory.CreateObject("Word.Application"); 
    Activator.CreateInstance(Type.GetTypeFromProgID("Word.Application", true)); 

oWord.Visible = false; 

object oTemplatePath = "c:\\vishal.dotx"; 
dynamic oWordDoc = oWord.Documents.Add(ref oTemplatePath); 
dynamic fields = oWordDoc.Fields; 

Console.WriteLine("template has {0} merge flds", fields.Count); 

//Method 1 
Console.WriteLine(string.Join("\n", ((IEnumerable)oWordDoc.Fields).Cast<dynamic>().Select(x=>(string)x.Result.Text).ToArray())); 

//Method 2 
foreach (dynamic fld in fields) 
Console.WriteLine(fld.Result.Text);