MS Word互操作:单元格中可以容纳多少文本



是否有可能告诉多少给定的文本可以放入一个表格单元格?本例将所有内容放在第一个单元格中,我需要将其分成两个单元格,而不需要调整第一个单元格的大小或更改字体。

using System.IO;
using System.Reflection;
using Word = Microsoft.Office.Interop.Word;
class Program
{
static void Main()
{
string filename = "example.docx";
string text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor";
var wordApp = new Word.Application { Visible = false };
string path = Path.Combine(Directory.GetCurrentDirectory(), filename);
var doc = wordApp.Documents.Open(path, ReadOnly: false, Visible: true);
doc.Activate();
var table = doc.Tables[1];

// todo: truncate text by the cell's size
table.Cell(1, 1).Range.Text = text;
string text2 = "";
// todo: put the remainder of the truncated text to text2
table.Cell(2, 1).Range.Text = text2;

doc.Save();
object missing = Missing.Value;
doc.Close(ref missing, ref missing, ref missing);
wordApp.Quit(ref missing, ref missing, ref missing);
}
}

@macropod让我想到了一个肮脏的hack(并不是说有任何干净的方法来使用Word):只是不断地将文本推入单元格,直到它的高度改变。这对于我的目的来说已经足够了,但是也可以检查宽度。

我使用下一行的Y位置来确定前一行的高度。因此,作为限制,下面应该至少再多一行。此外,页码也应该检查。

using System.Diagnostics;
using System.IO;
using System.Reflection;
using Word = Microsoft.Office.Interop.Word;
class Program
{
static void Main()
{
string filename = "example.docx";
string text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor";
int row = 1;
int column = 1;

var wordApp = new Word.Application { Visible = true };
string path = Path.Combine(Directory.GetCurrentDirectory(), filename);
var doc = wordApp.Documents.Open(path, ReadOnly: false, Visible: true);
doc.Activate();
var table = doc.Tables[1];

// Add as much text to the cell (row,column) as possible without changing the height of the cell.
// Row's bottom Y coordinate can be determined by the position of the next row and its page number.
Debug.Assert(table.Rows.Count > row, "Need at least 1 more row below");
table.Rows[row + 1].Select();
float oldBottom = wordApp.Selection.Information[Word.WdInformation.wdVerticalPositionRelativeToPage];
int oldPage = wordApp.Selection.Information[Word.WdInformation.wdActiveEndPageNumber];
// Binary-searching the length of the longest fitting substring
int min = 0;
int max = text.Length;
int length = 0;
while (min < max)
{
length = (min + max) / 2;
table.Cell(row, column).Range.Text = text.Substring(0, length);
float bottom = wordApp.Selection.Information[Word.WdInformation.wdVerticalPositionRelativeToPage];
float page = wordApp.Selection.Information[Word.WdInformation.wdActiveEndPageNumber];
if (page > oldPage || bottom > oldBottom)
max = length - 1;
else
min = length + 1;
}

// Don't split words
while (length > 0 && char.IsLetterOrDigit(text[length - 1]))
length--;
table.Cell(row, column).Range.Text = text.Substring(0, length);

doc.Save();
object missing = Missing.Value;
doc.Close(ref missing, ref missing, ref missing);
wordApp.Quit(ref missing, ref missing, ref missing);
}
}

相关内容

  • 没有找到相关文章

最新更新