从C#的Windows窗体应用程序中访问Office项目类

3
我正在创建一个管理项目,从用户那里获取一些输入,并在适当的格式下打印输出。
我已经创建了两个项目:
1. Windows窗体应用程序(用来接收字符串和数据表格的输入)
2. Office项目(用于对第一个项目中的数据进行格式化和打印)
我已经将Office项目及其.dll文件导入到我的第一个项目中。但问题是如何将参数(字符串和数据表格)传递给Office项目中的thisdocument类。它已经有一些参数,我不知道如何传递内置和新参数到第一个项目中。
private void printButton_Click(object sender, EventArgs e) { 
dataGridView.Rows.Add("1", "a", "1", "1"); 
dataGridView.Rows.Add("2", "b", "2", "2"); 
dataGridView.Rows.Add("3", "c", "3", "3"); 
WordDocumentProject.ThisDocument = new ThisDocument(); 
}

我之前问过你是否可以展示一些代码来更好地说明问题,这是一个非常活跃的网站,所以当你提出问题时,请尽量留在现场。祝你好运! - Jeremy Thompson
//这是2号项目(office)类的构造函数 public ThisDocument(Microsoft.Office.Tools.Word.Factory factory, global::System.IServiceProvider serviceProvider):base(factory, serviceProvider, "ThisDocument", "ThisDocument") { Globals.Factory = factory; } - Bilal Haider
//第一个项目(winForm)数据 private void printButton_Click(object sender, EventArgs e) { dataGridView.Rows.Add("1", "a", "1", "1"); dataGridView.Rows.Add("2", "b", "2", "2"); dataGridView.Rows.Add("3", "c", "3", "3"); //这里有错误,如何传递此文档构造函数的参数(在上面的注释中给出) WordDocumentProject.ThisDocument TDObj = new ThisDocument( } - Bilal Haider
请不要使用评论来发布代码,请像我向您展示的那样编辑您的问题 :) 如果您需要澄清,可以随时在我的答案下评论。 - Jeremy Thompson
1个回答

0

这都有文档记录,这里有一个很好的例子:如何使用Visual C#自动化Microsoft Word创建新文档

因此,要将datagridview中的字符串传递给word进行打印,您可以像这样操作:

//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);

//Insert a datagridview info into the document.
DataTable dt = (DataTable)datagridview1.DataSource;
foreach(DataRow dr in dt.Rows)
{
Word.Paragraph oPara1;
oPara1 = oDoc.Content.Paragraphs.Add(ref oMissing);
oPara1.Range.Text = dr[0].ToString();
oPara1.Range.Font.Bold = 1;
oPara1.Format.SpaceAfter = 24;    //24 pt spacing after paragraph.
oPara1.Range.InsertParagraphAfter();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接