- using System;
- using System.Collections.Generic;
- using System.Text;
- using Word = Microsoft.Office.Interop.Word;
- using System.Reflection;
- using System.Data;
- namespace ExportTest
- {
- /// <summary>
- /// 导出word
- /// </summary>
- public class ExportWord
- {
- /// <summary>
- /// 将数据表导出到word
- /// </summary>
- /// <param name="dt">数据表</param>
- /// <param name="isShowWord">是否显示word</param>
- /// <param name="fileName">导出到文件名</param>
- /// <param name="picName">导出到word中图片名</param>
- /// <returns></returns>
- public static bool ExportToWord(DataTable dt, bool isShowWord, object fileName, string picName)
- {
- if (System.IO.File.Exists(fileName.ToString()))
- {
- System.IO.File.Delete(fileName.ToString());
- }
- bool result = true;
- Object myobj = Missing.Value; ;
- if (dt == null || dt.Rows.Count == 0)
- {
- result = false;
- }
- else
- {
- //建立Word应用
- Word.Application word = new Word.Application();
- //word文档
- Word.Document mydoc = new Word.Document();
- mydoc = word.Documents.Add(ref myobj, ref myobj, ref myobj, ref myobj);
- word.Visible = isShowWord;
- mydoc.Select();
- Word.Selection mysel = word.Selection;
- //mysel.InlineShapes.AddPicture(picName, ref myobj, ref myobj, ref myobj);
- object top = 100;
- object left = 300;
- object hw = 100;
- //将数据生成Word表格文件
- Word.Table mytable = mydoc.Tables.Add(mysel.Range, dt.Rows.Count, dt.Columns.Count, ref myobj, ref myobj);
- //设置列宽
- mytable.Columns.SetWidth(50, Word.WdRulerStyle.wdAdjustNone);
- //输出列标题数据
- for (int i = 0; i < dt.Columns.Count; i++)
- {
- mytable.Cell(1, i + 1).Range.InsertAfter(dt.Columns[i].ColumnName);
- }
- //输出控件中的记录
- for (int i = 0; i < dt.Rows.Count - 1; i++)
- {
- for (int j = 0; j < dt.Columns.Count; j++)
- {
- mytable.Cell(i + 2, j + 1).Range.InsertAfter(dt.Rows[i][j].ToString());
- }
- }
- mydoc.Shapes.AddPicture(picName, ref myobj, ref myobj, ref left, ref top, ref hw, ref hw, ref myobj);
- //保存文本
- mydoc.SaveAs(ref fileName, ref myobj, ref myobj, ref myobj, ref myobj, ref myobj,
- ref myobj, ref myobj, ref myobj, ref myobj, ref myobj, ref myobj,
- ref myobj, ref myobj, ref myobj, ref myobj);
- }
- return result;
- }
- }
- }
复制代码 |