tbl = MyDoc.Tables.Add(myRange, ClassTable.Count(), 3, missing, missing);
예외에게가 "범위는 삭제할 수 없습니다"라는 메시지와 함께 실행있어 2 시간을 던졌습니다 라인입니다. 이 예외는 Word에서 삼켜 버리지 만 추가 실행을 중지합니다. tryin/catch를 추가하고 breakboint를 설정하면 도움이되었을 것입니다.
나는 생긴 예외를 재현 찾기 위해 다음에 코드를 편집 :
var myRange = Globals.ThisAddIn.Application.ActiveDocument.Range();
foreach (List<List<string>> ClassTable in new List<List<List<string>>> { new List<List<string>> { new List<string> { "A" }, new List<string> { "B" } }, new List<List<string>> { new List<string> { "C" }, new List<string> { "D" } } })
{
// tbl is a "Microsoft.Office.Interop.Word.Table"
// myRange is like MyDoc.Range(ref missing, ref missing)
Microsoft.Office.Interop.Word.Table tbl = null;
try
{
tbl = Globals.ThisAddIn.Application.ActiveDocument.Tables.Add(myRange, ClassTable.Count(), 3);
tbl.Borders.Enable = 1;
int RowCounter = 1;
foreach (var item in ClassTable)
{
int ColumnCounter = 1;
foreach (string str in item)
{
tbl.Cell(RowCounter, ColumnCounter).Range.Text = str;
ColumnCounter++;
}
RowCounter++;
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message);
}
}
docs at msdn 상태 :
필수 Range 개체. 표를 표시 할 범위입니다. 범위가 축소되지 않으면 표가 범위를 대체합니다.
필요한 경우 축소하려면 범위 끝까지 '이동'해야합니다. 그렇게하면 다른 단어 문제로 빠져 나갈 것입니다. 문서 단어에서 서로의 직후에 두 개의 표가 있으면 자동으로 표가 하나의 표로 결합됩니다. 고정 된 코드는 결국 1 개의 테이블에 더 많은 행을 추가하게되고 처음 몇 개의 행을 값으로 계속 덮어 씁니다. 이 모든 문제를 해결해야 다음 코드로 연결 :
var myRange = Globals.ThisAddIn.Application.ActiveDocument.Range();
foreach (List<List<string>> ClassTable in new List<List<List<string>>> { new List<List<string>> { new List<string> { "A" }, new List<string> { "B" } }, new List<List<string>> { new List<string> { "C" }, new List<string> { "D" } } })
{
// tbl is a "Microsoft.Office.Interop.Word.Table"
// myRange is like MyDoc.Range(ref missing, ref missing)
Microsoft.Office.Interop.Word.Table tbl = null;
try
{
tbl = Globals.ThisAddIn.Application.ActiveDocument.Tables.Add(myRange, ClassTable.Count(), 3);
tbl.Borders.Enable = 1;
int RowCounter = 1;
foreach (var item in ClassTable)
{
int ColumnCounter = 1;
foreach (string str in item)
{
tbl.Cell(RowCounter, ColumnCounter).Range.Text = str;
ColumnCounter++;
}
RowCounter++;
}
// Move to the end
myRange.Collapse(Microsoft.Office.Interop.Word.WdCollapseDirection.wdCollapseEnd);
// Now add something behind the table to prevent word from joining tables into one
myRange.InsertParagraphAfter();
// gosh need to move to the end again
myRange.Collapse(Microsoft.Office.Interop.Word.WdCollapseDirection.wdCollapseEnd);
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message);
}
}
마지막 경고는이 세그먼트의 첫 줄을 읽이다 :
var myRange = Globals.ThisAddIn.Application.ActiveDocument.Range();
경우 작동이 범위에 테이블을 추가 문서가 비어 있으면 그렇지 않으면 우리는이 경우에 끝나지 않으므로 동일한 예외가 발생합니다. .Collapse()는 거기에서도 그것을 해결합니다.
이것은 훌륭하지만 단락을 삽입 할 수 있는지 궁금합니다. 그러나 새 테이블 사이에 전체 줄 바꿈이 없어도 이상한 사양입니다. 테이블을 서로 겹치기를 원합니다. range.InsertParagraphAfter()를 사용하여 단락의 spaceAbove 및 spaceBelow를 어떻게 추가 할 수 있습니까? – sooprise
이것은 대단합니다. 정말 고마워요, 제 하루를 만들어 줬습니다. –