MS Word Interop:多少文本可以适合单元格
是否可以说出给定文本有多少适合桌单元格?这个示例将所有内容都放在第一个单元格中,我需要将其分为两个,而不调整第一个单元格或更改字体。
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);
}
}
Is it possible to tell how much of a given text can fit into a table cell? This example puts everything in the first cell, I need to split it in two without resizing the first cell or changing the font.
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);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
@macropod带领我了解了一个肮脏的hack的想法(并不是说无论如何都有任何干净的方法):只要继续将文本推入单元,直到其高度变化为止。这足以满足我的目的,但是也可以检查宽度。
我使用下一行的Y位置来确定上一个的高度。因此,作为一个限制,下面至少应该再有一排。另外,也应检查页码。
@macropod led me to the idea of one dirty hack (not that there is any clean way to work with Word anyway): just keep pushing text into the cell until its height changes. This is enough for my purpose, but one can check width as well.
I use next row's Y position to determine previous one's height. So, as a limitation, there should be at least one more row below. Also, page number should be checked too.