C# 操作word文档

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值