在.net c#中,使用Interop.Word生成word表格文档非常方便
创建Word应用程序对象
首先,我们需要创建Word应用程序对象,代码如下:
using Word = Microsoft.Office.Interop.Word;
Word.Application wordApp = new Word.Application();
创建文档对象
接下来,我们需要创建一个新的文档对象,代码如下:
Word.Document doc = wordApp.Documents.Add();
下面是完整的代码:
public static bool ExportWord(DataTable tb, string filepath, bool isopen)
{
Word.Document mydoc = new Word.Document();
if (tb.Rows.Count == 0) { return false; }
Word.Table mytable;
Word.Selection mysel;
object myobj;
//建立Word对象
Word.Application word = new Word.Application();
myobj = System.Reflection.Missing.Value;
mydoc = word.Documents.Add(ref myobj, ref myobj, ref myobj, ref myobj);
word.Visible = isopen;
mydoc.Select();
mysel = word.Selection;
//将数据生成Word表格文件
mytable = mydoc.Tables.Add(mysel.Range, tb.Rows.Count + 1, tb.Columns.Count, ref myobj, ref myobj);
//设置列宽
mytable.Columns.SetWidth(50, Word.WdRulerStyle.wdAdjustNone);
//输出列标题数据
for (int i = 0; i < tb.Columns.Count; i++)
{
mytable.Cell(1, i + 1).Range.InsertAfter(tb.Columns[i].ColumnName);
}
//输出控件中的记录
for (int i = 0; i < tb.Rows.Count; i++)
{
for (int j = 0; j < tb.Columns.Count; j++)
{
mytable.Cell(i + 2, j + 1).Range.InsertAfter(tb.Rows[i][j].ToString());
}
}
if (!string.IsNullOrWhiteSpace(filepath)) { mydoc.SaveAs2(filepath); }
return true;
}
调用如下:
private void zbtnadd_Click(object sender, EventArgs e)
{
List<DataInfo> list = new List<DataInfo>();
for (int i = 0; i < 10; i++)
{
list.Add(new DataInfo() { name = "姓名" + i.ToString(), des = "描述" + i.ToString(), count = 1, time = DateTime.Now.AddDays(i) });
}
DataTable tb = ToWord.CreateTable<DataInfo>(list);
ToWord.ExportWord(tb, "", true);
}
public class DataInfo
{
/// <summary>
/// 名称
/// </summary>
public string name { get; set; }
/// <summary>
/// 描述
/// </summary>
public string des { get; set; }
/// <summary>
/// 数量
/// </summary>
public int count { get; set; }
/// <summary>
/// 时间
/// </summary>
public DateTime time { get; set; }
}
如果不设置路径,也可以直接打开,方便打印,效果如下:
当然也可以填写路径,保存到指定的路径中.