C#操作Word模板插入文本、图像与表格的完整指南
C#操作Word模板插入文本、图像与表格的完整指南
1. 创建Word模板文件
首先需要创建一个Word模板文件(例如:template.dot),并在其中使用书签标记需要填充数据的位置。这些书签将作为后续程序插入内容的定位点。
2. 添加必要的引用
在Web应用程序项目中,需要添加对Microsoft.Office.Interop.Word的引用。具体添加方法请参考Microsoft官方文档。
3. 实现代码示例
3.1 生成Word文档并填充数据
protected void GenerateReport_Click(object sender, EventArgs e)
{
Microsoft.Office.Interop.Word.WordApplication wordApp = null; // Word应用程序对象
Microsoft.Office.Interop.Word.Document wordDoc = null; // 文档对象
try
{
// 初始化Word应用程序
wordApp = new Microsoft.Office.Interop.Word.WordApplication();
wordApp.Visible = false;
// 定义必要对象
object isVisible = true;
object notVisible = false;
object templatePath = Server.MapPath("template.dot"); // 模板文件路径
documentType = WdDocumentType.wdTypeDocument;
// 基于模板创建新文档
wordDoc = (Document)wordApp.Documents.Add(ref templatePath, ref notVisible, ref documentType, ref isVisible);
// 定义书签名称
object nameBookmark = "bm_Name"; // 姓名书签
object genderBookmark = "bm_Gender"; // 性别书签
object birthBookmark = "bm_Birthdate"; // 出生日期书签
object imageBookmark = "bm_Image"; // 图片书签
object tableBookmark = "bm_Table"; // 表格书签
object missing = System.Reflection.Missing.Value;
// 准备测试数据
System.Data.DataTable dataTable = new DataTable();
dataTable.Columns.Add("personName");
dataTable.Columns.Add("personGender");
dataTable.Columns.Add("personBirthdate");
DataRow dataRow = dataTable.NewRow();
dataRow["personName"] = "李四";
dataRow["personGender"] = "女";
dataRow["personBirthdate"] = "1990-05-15";
dataTable.Rows.Add(dataRow);
// 向书签位置填充文本数据
wordDoc.Bookmarks.get_Item(ref nameBookmark).Range.Text = dataTable.Rows[0]["personName"].ToString();
wordDoc.Bookmarks.get_Item(ref genderBookmark).Range.Text = dataTable.Rows[0]["personGender"].ToString();
wordDoc.Bookmarks.get_Item(ref birthBookmark).Range.Text = dataTable.Rows[0]["personBirthdate"].ToString();
// 向书签位置插入图片
wordDoc.Bookmarks.get_Item(ref imageBookmark).Range.InlineShapes.AddPicture(@"D:\Images\photo.jpg", ref missing, ref missing, ref missing);
// 在书签位置创建表格
Microsoft.Office.Interop.Word.Table newTable = wordDoc.Tables.Add(wordDoc.Bookmarks.get_Item(ref tableBookmark).Range, 12, 3, ref missing, ref missing);
newTable.Borders.OutsideLineStyle = WdLineStyle.wdLineStyleSingle;
newTable.Borders.InsideLineStyle = WdLineStyle.wdLineStyleSingle;
// 在文档末尾添加内容
wordDoc.Paragraphs.Last.Range.Text = "";
// 保存Word文档
object outputFileName = Server.MapPath("~") + "\\Reports\\" + dataTable.Rows[0]["personName"].ToString() + ".doc";
object noParam = System.Reflection.Missing.Value;
wordDoc.SaveAs(ref outputFileName, ref noParam, ref noParam, ref noParam, ref noParam, ref noParam, ref noParam, ref noParam, ref noParam, ref noParam, ref noParam, ref noParam, ref noParam, ref noParam, ref noParam, ref noParam);
// 关闭文档和应用程序
object doNotSave = WdSaveOptions.wdDoNotSaveChanges;
wordDoc.Close(ref doNotSave, ref missing, ref missing);
wordApp.Application.Quit(ref missing, ref missing, ref missing);
// 释放资源
wordDoc = null;
wordApp = null;
}
catch (System.Exception ex)
{
// 异常处理,确保释放资源
string errorInfo = ex.ToString();
object miss = System.Reflection.Missing.Value;
object noSave = WdSaveOptions.wdDoNotSaveChanges;
if (wordDoc != null)
{
wordDoc.Close(ref noSave, ref miss, ref miss);
}
if (wordApp != null)
{
wordApp.Application.Quit(ref miss, ref miss, ref miss);
}
wordDoc = null;
wordApp = null;
}
}
3.2 常见问题解决
如果运行时遇到80070005错误,可以尝试以下解决方案:
解决方案一:修改DCOM配置
- 打开控制面板 → 管理工具 → 组件服务 → 计算机 → 我的电脑 → DCOM配置
- 找到"Microsoft Word文档",右键单击选择"属性"
- 在"标识"选项卡中,选择"交互式用户"
- 在"安全"选项卡中,分别在"启动和激活权限"和"访问权限"组中选中"自定义"
- 点击"自定义"→"编辑"→添加ASP.NET账户和IUSER_计算机名
- 确保允许每个用户访问,然后确定
- 关闭DCOMCNFG
解决方案二:使用身份模拟
在web.config文件的
<identity impersonate="true" userName="你的用户名" password="密码"/>
3.3 图片操作详细说明
// 定义文件路径
object docPath = @"C:\\WebRoot\\Project\\output.doc";
Word.Application wordApp = new Word.ApplicationClass();
object nothingValue = System.Reflection.Missing.Value;
// 打开Word文档
Word.Document wordDoc = wordApp.Documents.Open(ref docPath, ref nothingValue, ref nothingValue, ref nothingValue, ref nothingValue, ref nothingValue, ref nothingValue, ref nothingValue, ref nothingValue, ref nothingValue, ref nothingValue, ref nothingValue, ref nothingValue, ref nothingValue, ref nothingValue, ref nothingValue);
// 添加图片
InlineShape imageShape = wordApp.Selection.InlineShapes.AddPicture(@"C:\\Images\\photo.jpg", ref nothingValue, ref nothingValue, ref nothingValue);
// 设置图片尺寸
imageShape.Height = InchesToPoints(0.5);
imageShape.Width = InchesToPoints(0.5);
// 保存并关闭文档
wordDoc.Save();
wordDoc.Close(ref nothingValue, ref nothingValue, ref nothingValue);
wordApp.Quit(ref nothingValue, ref nothingValue, ref nothingValue);
3.4 向Word书签写入数据的专用类
using System;
using System.Data;
using System.Web;
using Microsoft.Office.Core;
using Microsoft.Office.Interop.Word;
namespace DocumentUtilities
{
public class WordDataWriter
{
private ApplicationClass wordApp = null; // Word应用程序对象
private Document wordDoc = null; // 文档对象
private object missing = System.Reflection.Missing.Value; // 空值对象
private object readOnly = false;
/// <summary>
/// 打开Word文档
/// </summary>
/// <param name="filePath">文档路径</param>
public void OpenDocument(string filePath)
{
object path = filePath;
wordApp = new ApplicationClass();
// 打开文档
wordDoc = wordApp.Documents.Open(ref path, ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing);
wordDoc.Activate(); // 激活文档
}
/// <summary>
/// 向Word文档中的书签写入数据
/// </summary>
/// <param name="bookmarkName">书签名称</param>
/// <param name="content">要写入的内容</param>
public void WriteToBookmark(string bookmarkName, string content)
{
object name = bookmarkName;
Bookmark bookmark = wordDoc.Bookmarks.get_Item(ref name);
bookmark.Range.Text = content;
}
/// <summary>
/// 保存文档并关闭
/// </summary>
/// <param name="savePath">保存路径</param>
public void SaveAndClose(string savePath)
{
object path = savePath;
Object saveOption = wordApp.Options.BackgroundSave;
// 保存文档
wordDoc.SaveAs(ref path, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
// 关闭文档和应用程序
wordDoc.Close(ref saveOption, ref missing, ref missing);
wordApp.Quit(ref missing, ref missing, ref missing);
}
}
}