使用 C#.NET 在 Word 中创建动态表 [英] Creating Dynamic Tables in Word by C#.NET
问题描述
我有一个 C# 应用程序,我想在其中实现一个程序逻辑,该程序将打开 Word 文档并转到页面中的某个位置并创建一个表并将值放入其中.任何人都可以告诉我如何实现这一点.我正在使用 Visual Studio 2005
I have a C# application where i want to implement a logic for a programm which will open the word document and go to a certain place in the page and create a Table and put values in that. Can any one tell me how to implement this. I am using Visual studio 2005
推荐答案
这是将 datagridview 复制到 word 表的代码:
Here is code to copy datagridview to a word table:
参考是 Microsoft.Office.Interop.WordC:Program Files (x86)Microsoft Visual Studio 10.0Visual Studio Tools for OfficePIAOffice12Microsoft.Office.Interop.Word.dll
Reference is Microsoft.Office.Interop.Word C:Program Files (x86)Microsoft Visual Studio 10.0Visual Studio Tools for OfficePIAOffice12Microsoft.Office.Interop.Word.dll
using word = Microsoft.Office.Interop.Word;
public static void ExportToWord(DataGridView dgv)
{
SendMessage("Opening Word");
word.ApplicationClass word = null;
word.Document doc = null;
object oMissing = System.Reflection.Missing.Value;
object oEndOfDoc = "\endofdoc"; /* endofdoc is a predefined bookmark */
try
{
word = new word.ApplicationClass();
word.Visible = true;
doc = word.Documents.Add(ref oMissing, ref oMissing,ref oMissing, ref oMissing);
}
catch (Exception ex)
{
ErrorLog(ex);
}
finally
{
}
if (word != null && doc != null)
{
word.Table newTable;
word.Range wrdRng = doc.Bookmarks.get_Item(ref oEndOfDoc).Range;
newTable = doc.Tables.Add(wrdRng, 1, dgv.Columns.Count-1, 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;
foreach (DataGridViewCell cell in dgv.Rows[0].Cells)
{
newTable.Cell(newTable.Rows.Count, cell.ColumnIndex).Range.Text = dgv.Columns[cell.ColumnIndex].Name;
}
newTable.Rows.Add();
foreach (DataGridViewRow row in dgv.Rows)
{
foreach (DataGridViewCell cell in row.Cells)
{
newTable.Cell(newTable.Rows.Count, cell.ColumnIndex).Range.Text = cell.Value.ToString();
}
newTable.Rows.Add();
}
}
}
这篇关于使用 C#.NET 在 Word 中创建动态表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!