C# 操作word文档

开发者福利!热门AI工具限时免费用 购周边即赠Coding Plan Lite,Claude Code、Cursor等20+工具畅享,效率翻倍! 阅读详情

object oFileName = @"C:/Documents and Settings/liush/My Documents/TestDoc.doc";
object oReadOnly = true;
object oMissing = System.Reflection.Missing.Value;

Word._Application oWord;
Word._Document oDoc;
oWord = new Word.Application();
oWord.Visible = true;//只是为了方便观察
oDoc = oWord.Documents.Open(ref oFileName, ref oMissing, ref oReadOnly, ref oMissing, ref oMissing,
    ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);

//MessageBox.Show(oDoc.Tables.Count.ToString());
for (int tablePos = 1; tablePos <= oDoc.Tables.Count; tablePos++)
{
    Word.Table nowTable = oDoc.Tables.Item(tablePos);
    string tableMessage = string.Format("第{0}/{1}个表:/n", tablePos, oDoc.Tables.Count);

    for (int rowPos = 1; rowPos <= nowTable.Rows.Count; rowPos++)
    {
for (int columPos = 1; columPos <= nowTable.Columns.Count; columPos++)
{
tableMessage += nowTable.Cell(rowPos, columPos).Range.Text;
tableMessage = tableMessage.Remove(tableMessage.Length - 2, 2);//remove /r/a
tableMessage += "/t";
}

tableMessage += "/n";
    }

    MessageBox.Show(tableMessage);
}

如果看过了上面kaneboy的文章(这是一个系列的之一),再看这段代码应该不会很难理解。打开一个已有文档,然后遍历其中的所有的表。这里只是简单的将信息显示出来,具体实践上可以对这些信息进行分析。做完这些后,终于找到了一些官方的支持文档,地址如下:
http://msdn2.microsoft.com/zh-CN/library/y1xatbkd.aspx
其中的word任务有对word各种操作的简单代码事例,用vb和c#写的。看完之后,我想每个人都会明白vb对com的支持比c#不是简单明了一点两点。(可以看下这个http://blog.joycode.com/kaneboy/archive/2005/08/03/61489.aspx)同样的代码,用vb实现打开word文档的操作,代码如下:

Dim fileName As String = "C:/Documents and Settings/liush/My Documents/TestDoc.doc"
Dim isReadOnly As Boolean = True

Dim wordApplication As Word.Application = New Word.Application()
Dim wordDocument As Word.Document
wordApplication.Visible = True
wordDocument = wordApplication.Documents.Open(fileName, , isReadOnly)

/***********************************************************************/

在CSDN上总是有网友问这个问题,自己也遇到过,因些写出来供参考:
症状:
oWordApplic = New Word.Application
当程序运行到这句时出现下面的错误:
检索 COM 类工厂中 CLSID 为 {000209FF-0000-0000-C000-000000000046} 的组件时失败,原因是出现以下错误: 80070005。
oWordApplic = New Word.Application
当程序运行到这句时出现下面的错误:
检索 COM 类工厂中 CLSID 为 {000209FF-0000-0000-C000-000000000046} 的组件时失败,原因是出现以下错误: 80070005。 
解决方法一:
控制面板-》管理工具-》组件服务-》计算机-》我的电脑-》DCom配置-》找到Microsoft Word文档
之后
单击属性打开此应用程序的属性对话框。 
2. 单击标识选项卡,然后选择交互式用户。
3.单击"安全"选项卡,分别在"启动和激活权限"和"访问权限"组中选中"自定义",然后
自定义->编辑->添加ASP.NET账户和IUSER_计算机名



* 这些帐户仅在计算机上安装有 IIS 的情况下才存在。
13. 确保允许每个用户访问,然后单击确定。
14. 单击确定关闭 DCOMCNFG。

解决方法二:
如果上述方法不能解决问题,就应该是权限问题,请尝试用下面的方法:
在web.config中使用身份模拟,在<system.web>节中加入  <identity impersonate="true" userName="你的用户名" password="密码"/>
 </system.web>

/************************************************************/

protected void Page_Load(object sender, EventArgs e)
        {
            Word.Application wdApplication;   //As   Word.Application();  
            Word.Document wdWords;   //As   Word.Document  
    
            wdApplication   =   new   Word.Application();
            Object filename = @"D:/web/image/a.doc";
            object oReadOnly = true;
            object oMissing = System.Reflection.Missing.Value;
            wdWords = wdApplication.Documents.Open(ref filename, ref oMissing, ref oReadOnly, ref oMissing, ref oMissing,
    ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);

            for (int tablePos = 1; tablePos <= wdWords.Tables.Count; tablePos++)
            {
                Word.Table nowTable = wdWords.Tables.Item(tablePos);
                string tableMessage = string.Format("第{0}/{1}个表:/n", tablePos, wdWords.Tables.Count);

                for (int rowPos = 1; rowPos <= nowTable.Rows.Count; rowPos++)
                {
                    for (int columPos = 1; columPos <= nowTable.Columns.Count; columPos++)
                    {
                        tableMessage += nowTable.Cell(rowPos, columPos).Range.Text;
                        tableMessage = tableMessage.Remove(tableMessage.Length - 2, 2);//remove /r/a
                        tableMessage += "/t";
                    }

                    tableMessage += "/n";
                }

                Response.Write(tableMessage);
            }

要使用C#操作word,首先要添加引用:
1、添加引用->COM->Microsoft Word 11.0 Object Library

2、在.cs文件中添加

using Word;
下面的例子中包括C#对Word文档的创建、插入表格、设置样式等操作:

(例子中代码有些涉及数据信息部分被省略,重要是介绍一些C#操作word文档的方法)

public string CreateWordFile( string CheckedInfo)
... {
string message = "" ;
try
... {
Object Nothing = System.Reflection.Missing.Value;
Directory.CreateDirectory( " C:/CNSI " ); // 创建文件所在目录
string name = " CNSI_ " + DateTime.Now.ToShortString() + " .doc " ;
object filename = " C://CNSI// " + name; // 文件保存路径
// 创建Word文档
Word.Application WordApp = new Word.ApplicationClass();
Word.Document WordDoc = WordApp.Documents.Add( ref Nothing, ref Nothing, ref Nothing, ref Nothing);

// 添加页眉
WordApp.ActiveWindow.View.Type = WdViewType.wdOutlineView;
WordApp.ActiveWindow.View.SeekView = WdSeekView.wdSeekPrimaryHeader;
WordApp.ActiveWindow.ActivePane.Selection.InsertAfter( " [页眉内容] " );
WordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight; // 设置右对齐
WordApp.ActiveWindow.View.SeekView = WdSeekVi
WordApp.ActiveWindow.View.SeekView = WdSeekView.wdSeekMainDocument; // 跳出页眉设置

WordApp.Selection.ParagraphFormat.LineSpacing = 15f; // 设置文档的行间距

// 移动焦点并换行
object count = 14 ;
object WdLine = Word.WdUnits.wdLine; // 换一行;
WordApp.Selection.MoveDown( ref WdLine, ref count, ref Nothing); // 移动焦点
WordApp.Selection.TypeParagraph(); // 插入段落

// 文档中创建表格
Word.Table newTable = WordDoc.Tables.Add(WordApp.Selection.Range, 12 , 3 , ref Nothing, ref Nothing);
// 设置表格样式
newTable.Borders.OutsideLineStyle = Word.WdLineStyle.wdLineStyleThickThinLargeGap;
newTable.Borders.InsideLineStyle = Word.WdLineStyle.wdLineStyleSingle;
newTable.Columns[ 1 ].Width = 100f;
newTable.Columns[ 2 ].Width = 220f;
newTable.Columns[ 3 ].Width = 105f;

// 填充表格内容
newTable.Cell( 1 , 1 ).Range.Text = " 产品详细信息表 " ;
newTable.Cell( 1 , 1 ).Range.Bold = 2 ; // 设置单元格中字体为粗体
// 合并单元格
newTable.Cell( 1 , 1 ).Merge(newTable.Cell( 1 , 3 ));
WordApp.Selection.Cells.VerticalAlignment = Word.WdCellVerticalAlignment.
WordApp.Selection.Cells.VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter; // 垂直居中
WordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter; // 水平居中

// 填充表格内容
newTable.Cell( 2 , 1 ).Range.Text = " 产品基本信息 " ;
newTable.Cell( 2 , 1 ).Range.Font.Color = Word.WdColor.wdColorDarkBlue; // 设置单元格内字体颜色
// 合并单元格
newTable.Cell( 2 , 1 ).Merge(newTable.Cell( 2 , 3 ));
WordApp.Selection.Cells.VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;

// 填充表格内容
newTable.Cell( 3 , 1 ).Range.Text = " 品牌名称: " ;
newTable.Cell( 3 , 2 ).Range.Text = BrandName;
// 纵向合并单元格
newTable.Cell( 3 , 3 ).Select(); // 选中一行
object moveUnit = Word.WdUnits.wdLine;
object moveCount = 5 ;
object moveExtend = Word.WdMovementType.wdExtend;
WordApp.Selection.MoveDown( ref moveUnit, ref moveCount, ref moveExtend);
WordApp.Selection.Cells.Merge();
// 插入图片
string FileName = Picture; // 图片所在路径
object LinkToFile = false ;
object SaveWithDocument = true ;
object Anchor = WordDoc.Application.Selection.Range;
WordDoc.Application.ActiveDocument.InlineShapes.AddPicture(FileName, ref LinkToFile, ref SaveWithDocument, ref Anchor);
WordDoc.Application.ActiveDocument.InlineShapes[ 1 ].Width = 100f; // 图片宽度
WordDoc.Application.ActiveDocument.InlineShapes[ 1 ].Height = 100f; // 图片高度
// 将图片设置为四周环绕型
Word.Shape s = WordDoc.Application.ActiveDocument.InlineShapes[ 1 ].ConvertToShape();
s.WrapFormat.Type = Word.WdWrapType.wdWrapSquare;

newTable.Cell( 12 , 1 ).Range.Text = " 产品特殊属性 " ;
newTable.Cell( 12 , 1 ).Merge(newTable.Cell( 12 , 3 ));
// 在表格中增加行
WordDoc.Content.Tables[ 1 ].Rows.Add( ref Nothing);

WordDoc.Paragraphs.Last.Range.Text = " 文档创建时间: " + DateTime.Now.ToString(); // “落款”
WordDoc.Paragraphs.Last.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight;

// 文件保存
WordDoc.SaveAs( ref filename, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref N
// 文件保存
WordDoc.SaveAs( ref filename, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing);
WordDoc.Close( ref Nothing, ref Nothing, ref Nothing);
WordApp.Quit( ref Nothing, ref Nothing, ref Nothing);
message = name + " 文档生成成功,以保存到C:CNSI下 " ;
}
catch
... {
message = " 文件导出异常! " ;
}
return message;
}
private void Excel()
{
int val = 0;
string connStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D://abs.xls;Extended Properties='Excel 8.0;HDR=YES;'";
OleDbConnection conn = new OleDbConnection(connStr);
conn.Open();
string strSql = "select * from [Sheet1$]";
//OleDbDataAdapter adp = new OleDbDataAdapter(strSql, conn);
//DataSet dst = new DataSet();
//adp.Fill(dst);
/*****************************************************/
OleDbCommand objCmd = new OleDbCommand(strSql, conn);
OleDbDataReader rdr = objCmd.ExecuteReader(CommandBehavior.CloseConnection);
while (rdr.Read())
{
string sql = "insert into WareInfos(name,gueigei,provider,danwu,wenghao,lPrice,type,gongleng,yongfa) values(@name,@gueigei,@provider,@danwu,@wenghao,@lPrice,@type,@gongleng,@yongfa)";

//SqlCommand objCmd = new SqlCommand(sql,conn);
SqlParameter[] parms = {new SqlParameter("@name",SqlDbType.VarChar,50),
new SqlParameter("@gueigei",SqlDbType.VarChar,50),
new SqlParameter("@provider",SqlDbType.Int),
new SqlParameter("@danwu",SqlDbType.VarChar,30),
new SqlParameter("@wenghao",SqlDbType.VarChar,20),
new SqlParameter("@lPrice",SqlDbType.Decimal),
new SqlParameter("@type",SqlDbType.Int),
new SqlParameter("@gongleng",SqlDbType.VarChar,800),
new SqlParameter("@yongfa",SqlDbType.VarChar,800)};

parms[0].Value = rdr.GetString(1);
parms[1].Value = rdr.GetString(2);
parms[2].Value = Convert.ToInt32(rdr[3]);
parms[3].Value = rdr.GetString(5);
parms[4].Value = rdr.GetString(6);
parms[5].Value = Convert.ToDouble(rdr[7]);
parms[6].Value = rdr[8];
parms[7].Value = rdr.GetString(9);
parms[8].Value = rdr.GetString(10);

val = SqlHelper.ExecuteNonQuery(CommandType.Text,sql,parms);


}
if (val > 0)
RegisterClientScriptBlock("dfsd", "<script>alert('搞定达');</script>");
else
RegisterClientScriptBlock("dfsd", "<script>alert('NNNNN');</script>");
}
#endregion


C#技术文档 C#(发音为 “C Sharp”)是一种面向对象的编程语言,由微软公司开发,主要运行在 .NET Framework 或 .NET Core 平台上。C# 结合了多种语言的优点,如 C++ 的高效性和 Java 的垃圾回收机制,同时提供了丰富的类库和框架支持。这是一个非常基础的文档概览,实际上,C# 的功能远不止于此,包括但不限于泛型、属性、事件、反射、动态类型、Lambda 表达式、异步编程、LINQ 等。服务生成的所有内容均由人工智能模型生成,其生成内容的准确性和完整性无法保证,不代表我们的态度或观。 阅读详情

相关推荐

C#操作Word (2)-- 打开&关闭Word文档

OK,接着上一篇“Word对象模型”,本文正式开始在VS2010中使用C#语言操作Word2007. 不是十分了解Word对象模型的朋友,请参考上一篇文章,或者下载:C#操作Word2007.pdf。 ----------------------------------华丽分割-------------------------------------------- 1.添加Refer

ruby97的专栏 2万+

csharp文档

csharp文档

C#利用内置的word五大对象操作word文档

public class WordHelper { ApplicationClass app = null; //定义应用程序对象 Document doc = null; //定义 word 文档对象 public void OpenDocument(strin

生面别开 4321

C Sharp 说明文档(微软)

C Sharp 说明文档(微软)对C#做的一些说明

C#学习参考文档

C# 简介C# 入门教程C# 编写代码语法C# 注释作用写法及示例代码C# 变量C# 类据类型C# 数据类型转换(Casting)C# 运算符(Operators)C# 字符串(String)的使用C# 布尔值(Boolean)C# 获取用户输入和输出信息C# 条件语句(If else)C# switch case 语句C# while循环语句C# for循环语句C# break和continue关键字C# 数组(Arrays)C# 方法C# 方法 参数C# 方法 重载C# 作用域C# 递归C# 面向对象编

亮亮的专栏 1216

Csharp编程指南+参考手册文档分享

 本节提供有关关键的 C# 语言功能和 C# 可通过 .NET Framework 访问的功能的详细信息。 本节中大部分内容都假定您已了解有关 C# 和一般编程概念的一些知识。如果您刚开始学习编程或 C#,则应从 Visual C# 指导教程开始。您可能还想访问 Visual C# 开发中心,此处提供很多教程、示例和视频,可帮助您入门。 有关特定的关键字、运算符和预处理器指令的信息

u013490060的专栏 4241

C#在WinForm中操作Word文档的实现

Word应用程序对象是Microsoft Office Word应用程序的顶级对象,它可以被用来访问Word中的所有可用对象,比如文档、范围、视图等。它类似于一个容器,内含应用程序的所有文档实例和其他相关对象。在.NET环境下,Word对象模型暴露于Microsoft.Office.Interop.Word命名空间中,使C#开发者能够方便地调用和操作。通过操作Word应用程序对象,开发者可以编程实现文档的创建、打开、保存、打印以及更多的高级功能,例如更改文档结构、插入图形元素、设置文本格式等。

weixin_33628677的博客 1686

C#操作word文档

<br />1.c#操作word 在指定书签插入文字或者图片 using Word = Microsoft.Office.Interop.Word; object Nothing = System.Reflection.Missing.Value; object format = Word.WdSaveFormat.wdFormatDocument; Word.Application wordApp = new Word.ApplicationClass();

托雷斯基的专栏 1580

c#操作Word文档

操作Word文档工具类,丰富的方法, 无论你是想要创建文档还是操作模板;无论你是想要添加图片,还是想要添加文字;无论你想要添加书签,还是操作书签;无论你是想要修改表格,还是添加表格;它都是你的选择

TIANDIZHUSHEN的专栏 1685

Csharp文件操作全收录

目前最为常用的C#经典操作文件的方法,具体内容如下:C#追加、拷贝、删除、移动文件、创建目录、递归删除文件夹及文件、指定文件夹下面的所有内容copy到目标文件夹下面、指定文件夹下面的所有内容Detele、读取文本文件、获取文件列表、读取日志文件、写入日志文件、创建HTML文件、CreateDirectory方法的使用C#追加文件

CSharp入门与实例

CSharp入门与实例,c#入门,c#实例.

C# WinForm操作Word文档的完整实现

命名空间提供了对 Word 应用程序的全面访问能力,主要包括以下核心类和接口:类/接口说明表示 Word 应用程序实例,是所有操作的起点Document表示一个打开的 Word 文档Range表示文档中的一段内容,支持插入、格式化等操作Paragraph表示段落,用于控制段落样式Selection表示当前选中的内容Table表示表格对象,支持行、列、单元格操作表示图片对象,支持内嵌或浮动布局。

weixin_35754676的博客 1636

C#操作Word文档

 using System;   using System.Collections.Generic;   using System.ComponentModel;   using System.Data;   using System.Drawing;   using System.Text;   using System.Windows.Forms;   using Microsoft.Offi

insiderc的专栏 1504

c# word文档基本操作 (上)

首先,基本的开发工具是Visual Studio 我使用的是vs2017版本的。 首先选中visual c# 选择window桌面 选择控制台应用 然后设置项目保存路径和项目名称,点击确定。  项目创建好后 我们可以看到这样的编辑界面 当然我们只是写一个可供调用的函数即可,所以我们在class Program中定义一个checkOperation的函数,分别传入path(文档路径)...

weixin_40212554的博客 4045

编程实现操作word文档 c#

建立一个自己的类 //word 类, /* 1. 添加引用COM里面的 Microsoft Word 12.0 Object. Library 引用(12.0表示Word 2007版本) 2. 导命名空间 using Word =Microsoft.Office.Interop.Word; using System.IO; using System.Reflection; 3. 把引用中的Microsoft.Office.Interop.Word的“属性”中的嵌入互操作设为False ...

sixtome 1944
上一篇: 在ASP.NET中把图片保存到SQL SERVER数据库(vb.net)
okin1
博客等级 码龄19年 12粉丝 4原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值