尝试在 C# 中写入 table 单元格时出错

Error while trying to write on table cells in C#

我试图在 Visual Studio C#[=14= 的帮助下创建一个内部带有 table 和一些文本的自定义 Word 文档]

这是我的代码。

object oMissing = System.Reflection.Missing.Value;
object oEndOfDoc = "\endofdoc"; /* \endofdoc is a predefined bookmark */

//Start Word and create a new document.
Word._Application oWord;
Word._Document oDoc;
oWord = new Word.Application();
oWord.Visible = true;
oDoc = oWord.Documents.Add(ref oMissing, ref oMissing,
ref oMissing, ref oMissing);


Word.Table newTable;
Word.Range wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
newTable = oDoc.Tables.Add(wrdRng, 1, 3, ref oMissing, ref oMissing);
newTable.Borders.InsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;
newTable.Borders.OutsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;
// newTable.AllowAutoFit = true;

// Formattazione prima tabella
newTable.Cell(0, 1).Range.Text = "Olivero SRL";
newTable.Cell(0, 2).Range.Text = "PSQ/18/01/A8";
newTable.Cell(0, 3).Range.Text = "Vers. 0.1";
        

newTable.Cell(0, 1).Range.FormattedText.Font.Size = 14;
newTable.Cell(0, 1).Range.FormattedText.Bold = 1;
newTable.Cell(0, 1).Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;

newTable.Cell(0, 2).Range.FormattedText.Font.Size = 14;
newTable.Cell(0, 2).Range.FormattedText.Bold = 1;
newTable.Cell(0, 2).Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;

newTable.Cell(0, 3).Range.FormattedText.Font.Size = 14;
newTable.Cell(0, 3).Range.FormattedText.Bold = 1;

这是MSDN提供的一种经典的Word文档创建方式。
当涉及到这一行时 newTable.Cell(0, 1).Range.Text = "Olivero SRL"; 因此,当我尝试在第一个 table 单元格中插入一些值时,出现以下错误

The remote procedure call failed. (Exception from HRESULT: 0x800706BE)

在互联网上搜索我只找到了一般性修复,但与 c# 或编码相比没有任何修复。

Word 单元格(行和列)索引编号将从 1 开始,而不是 0。 您可以在 MSDN article.

中查看示例

因此将您的代码更改为:

newTable.Cell(1, 1).Range.Text = "Olivero SRL";
newTable.Cell(1, 2).Range.Text = "PSQ/18/01/A8";
newTable.Cell(1, 3).Range.Text = "Vers. 0.1";
... rest of the code