最近接到了一个小任务:使用word将数据输出,datatable也好datagridview也罢,生成才是第一要义。
一、
首先肯定是在网上找资料了,然后找到一个微软官方解释说明文档,特别好。
如何: 使用 Visual c # 自动化 Microsoft Word 创建新文档
本分步指南介绍了如何使用 Microsoft Visual c # 2005 或 Microsoft Visual c # .NET 中的自动化功能在 Microsoft Word 中创建新文档。
本文中的示例代码演示了如何执行以下操作:
若要使用 Visual c # 2005 或 Visual c # .NET 中的自动化功能创建新的 Word 文档, 请按照以下步骤操作:
- 插入包含文本和格式的段落。
- 浏览和修改文档中的各种区域。
- 插入表格、设置表格格式并使用数据填充表格。
- 添加图表。
代码完成后, 检查为您创建的文档。 该文档包含两页的格式段落、表格和图表
单击 "Button1" 以启动 Word Automation 并创建文档。
按 F5 生成并运行该程序。
private void button1_Click(object sender, System.EventArgs e) { 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); //Insert a paragraph at the beginning of the document. Word.Paragraph oPara1; oPara1 = oDoc.Content.Paragraphs.Add(ref oMissing); oPara1.Range.Text = "Heading 1"; oPara1.Range.Font.Bold = 1; oPara1.Format.SpaceAfter = 24; //24 pt spacing after paragraph. oPara1.Range.InsertParagraphAfter(); //Insert a paragraph at the end of the document. Word.Paragraph oPara2; object oRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; oPara2 = oDoc.Content.Paragraphs.Add(ref oRng); oPara2.Range.Text = "Heading 2"; oPara2.Format.SpaceAfter = 6; oPara2.Range.InsertParagraphAfter(); //Insert another paragraph. Word.Paragraph oPara3; oRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; oPara3 = oDoc.Content.Paragraphs.Add(ref oRng); oPara3.Range.Text = "This is a sentence of normal text. Now here is a table:"; oPara3.Range.Font.Bold = 0; oPara3.Format.SpaceAfter = 24; oPara3.Range.InsertParagraphAfter(); //Insert a 3 x 5 table, fill it with data, and make the first row //bold and italic. Word.Table oTable; Word.Range wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; oTable = oDoc.Tables.Add(wrdRng, 3, 5, ref oMissing, ref oMissing); oTable.Range.ParagraphFormat.SpaceAfter = 6; int r, c; string strText; for(r = 1; r <= 3; r++) for(c = 1; c <= 5; c++) { strText = "r" + r + "c" + c; oTable.Cell(r, c).Range.Text = strText; } oTable.Rows[1].Range.Font.Bold = 1; oTable.Rows[1].Range.Font.Italic = 1; //Add some text after the table. Word.Paragraph oPara4; oRng = oDoc.Bookmarks.get_Item(ref oEnd