首页 > 解决方案 > 尝试在 C# 中的表格单元格上写入时出错

问题描述

我正在尝试在Visual Studio C#的帮助下创建一个包含表格和一些文本的自定义 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;

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

远程过程调用失败。(来自 HRESULT 的异常:0x800706BE)

在互联网上搜索,我发现只有一般修复,但与 c# 或编码相比没有。

标签: c#wordword-interop

解决方案


Word 单元格(行和列)索引号将从 1 而不是 0 开始。您可以在此MSDN 文章中看到一个示例。

因此,将您的代码更改为:

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

推荐阅读