在C#中对Word进行操作
2015-05-22 17:14:29 访问(3780) 赞(0) 踩(0)
8.1 使用C#创建Word文档
在常见的信息管理系统中,经常涉及文件的收发、数据的整理及报表功能。除了使用应用程序本身进行显示、处理之外,还必须考虑到企业原有的办公系统。由于大部分企业仍然以使用Word进行字处理为主,一般需要添加进行Word文档输出的功能。本部分介绍如何使用C#创建Word文档的方法。
创建Word文档所使用的主要方法是通过微软公司提供的Microsoft Word X Object Library,其中X为版本号。Word 2007对应12.0,Word 2003对应11.0。通过在项目中添加该组件,即可使用微软公司提供的方法创建相应版本的Word文档。
1.目的说明
介绍创建Word文档的基本知识,通过实例演示如何创建Word 2003版本的Word文档和Word 2007版本的Word文档。
2.操作步骤
(1)创建一个Windows控制台应用程序,命名为CreateWordDemo。
(2)添加引用,如图8.1所示。
引用的库位于“COM”选项卡下,名称为Microsoft Word 12.0 Object Library。其中12.0是版本号,对应Microsoft Word 2007。Microsoft Word 2003对应的版本号为11.0。考虑到Microsoft Office 2007版本系列的软件能够比较方便地使用Microsoft Office 2003版本系列创建的文档,本节首先使用Microsoft Word 11.0 Object Library创建一个Word 2003文档。
添加后“解决方案资源管理器”面板的引用项中自动多出了三个引用,如图8.2所示。分别为Microsoft.Office.Core、Microsoft.Office.Interop.Word和VBIDE。
图8.1 添加引用 图8.2 “解决方案资源管理器”面板
(3)在“Program.cs”文件中添加如下引用。
using MSWord = Microsoft.Office.Interop.Word;
//using MSWord = Microsoft.Office.Interop.Word;经验证此行需要改正为
using MSWord = Word;
using System.IO;
using System.Reflection;
(4)直接修改“Program.cs”文件的代码如下。
class Program
{
static void Main(string[] args)
{
object path; //文件路径变量
string strContent; //文本内容变量
MSWord.Application wordApp; //Word应用程序变量
MSWord.Document wordDoc; //Word文档变量
path = @"C:\MyWord.doc"; //路径
wordApp = new MSWord.ApplicationClass(); //初始化
// wordApp = new MSWord.ApplicationClass();经验证此行需要改正为wordApp = new MSWord.Application();
//如果已存在,则删除
if (File.Exists((string)path))
{
File.Delete((string)path);
}
//由于使用的是COM库,因此有许多变量需要用Missing.Value代替
Object Nothing = Missing.Value;
wordDoc = wordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing);
//WdSaveFormat为Word文档的保存格式
object format =MSWord.WdSaveFormat.wdFormatDocument;
//将wordDoc文档对象的内容保存为DOC文档
wordDoc.SaveAs(ref path, ref format, 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文档对象
wordDoc.Close(ref Nothing, ref Nothing, ref Nothing);
//关闭wordApp组件对象
wordApp.Quit(ref Nothing, ref Nothing, ref Nothing);
Console.WriteLine(path + " 创建完毕!");
}
}
3.运行结果
运行程序,结果如图8.3所示。
打开C盘根目录,如图8.4所示。
图8.3 运行结果 图8.4 创建成功
可以看到,已经成功地创建了一个名为MyWord.doc的Word文档。该文档是Microsoft Word 2003默认的文档格式,大小约为22KB。下面介绍如何使用其创建一个Microsoft Word 2007默认文档格式的Word文档。
4.目的说明
在Microsoft.Office.Interop.Word命名空间下有一个枚举名为WdSaveFormat,设定了可用于保存的形式,如图8.5所示。对应于如图8.6所示的Word保存格式。
图8.5 WdSaveFormat枚举 图8.6 保存格式
可以看到,WdSaveFormat枚举中定义的格式更为详细,下面介绍如何创建一个Microsoft Word 2007格式的文档。
5.操作步骤
(1)创建一个Windows控制台应用程序,命名为CreateWordXDemo。
(2)添加对Microsoft Word 12.0 Object Library的引用(同之前的步骤,不再详述)。
(3)在“Program.cs”文件中添加如下引用。
using MSWord = Microsoft.Office.Interop.Word;
using System.IO;
using System.Reflection;
(4)直接修改“Program.cs”文件的代码如下。
class Program
{
static void Main(string[] args)
{
object path; //文件路径变量
string strContent; //文本内容变量
MSWord.Application wordApp; //Word应用程序变量
MSWord.Document wordDoc; //Word文档变量
path = @"C:\MyWord.docx"; //路径
wordApp = new MSWord.ApplicationClass(); //初始化
//如果已存在,则删除
if (File.Exists((string)path))
{
File.Delete((string)path);
}
//由于使用的是COM库,因此有许多变量需要用Missing.Value代替
Object Nothing = Missing.Value;
wordDoc = wordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing);
//strContent = "你好!\n";
//wordDoc.Paragraphs.Last.Range.Text = strContent;
//strContent = "Hello World";
//wordDoc.Paragraphs.Last.Range.Text = strContent;
//WdSaveFormat为Word 2007文档的保存格式
object format =MSWord.WdSaveFormat.wdFormatDocumentDefault;
//将wordDoc文档对象的内容保存为DOCX文档
wordDoc.SaveAs(ref path, ref format, 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文档对象
wordDoc.Close(ref Nothing, ref Nothing, ref Nothing);
//关闭wordApp组件对象
wordApp.Quit(ref Nothing, ref Nothing, ref Nothing);
Console.WriteLine(path + " 创建完毕!");
}
}
6.运行结果
运行程序,结果如图8.7所示。
图8.7 运行结果
打开C盘根目录,如图8.8所示。
图8.8 创建成功
可以看到,已经成功地创建了一个名为MyWord.docx的Word文档。该文档是Microsoft Word 2007默认的文档格式,大小约为11KB。
8.2 使用C#向Word文档中写入文本
文本是一个Word文档中最简单的元素,通过各种形式的文本与其他元素有机组合才形成了一个完整的Word文档。本节介绍如何使用C#向Word文档中写入文本信息。
在向Word文档中写入文本时,仍然需要使用上节介绍的Microsoft Word X Object Library COM组件。写入文本的方法主要为设置MSWord.Document.Paragraphs.Last.Range.Text属性,通过设置不同的字符串,即可达到写入文本的目的。
1.目的说明
介绍如何向Word文档中写入文本和如何向Word文档中写入多行文本。
2.操作步骤
(1)创建一个Windows控制台应用程序,命名为CreateWordXDemo。
(2)添加对Microsoft Word 12.0 Object Library的引用。
(3)在“Program.cs”文件中添加如下引用。
using MSWord = Microsoft.Office.Interop.Word;
using System.IO;
using System.Reflection;
(4)直接修改“Program.cs”文件的代码如下。
class Program
{
static void Main(string[] args)
{
object path; //文件路径变量
string strContent; //文本内容变量
MSWord.Application wordApp; //Word应用程序变量
MSWord.Document wordDoc; //Word文档变量
path = @"C:\MyWord.docx"; //路径
wordApp = new MSWord.ApplicationClass(); //初始化
//如果已存在,则删除
if (File.Exists((string)path))
{
File.Delete((string)path);
}
//由于使用的是COM库,因此有许多变量需要用Missing.Value代替
Object Nothing = Missing.Value;
wordDoc = wordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing);
strContent = "使用C#向Word文档中写入文本\n";
wordDoc.Paragraphs.Last.Range.Text = strContent;
strContent = "写入第二行文本";
wordDoc.Paragraphs.Last.Range.Text = strContent;
//WdSaveFormat为Word 2007文档的保存格式
object format =MSWord.WdSaveFormat.wdFormatDocumentDefault;
//将wordDoc文档对象的内容保存为DOCX文档
wordDoc.SaveAs(ref path, ref format, 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文档对象
wordDoc.Close(ref Nothing, ref Nothing, ref Nothing);
//关闭wordApp组件对象
wordApp.Quit(ref Nothing, ref Nothing, ref Nothing);
Console.WriteLine(path + " 创建完毕!");
}
}
3.运行结果
运行程序,结果如图8.9所示。
图8.9 运行结果
打开C盘根目录下的MyWord.docx,如图8.10所示。
图8.10 运行结果
8.3 使用C#向Word输出格式化的文本
一个Word文档不可能全部由无格式的普通文本组成,因此在从C#中向Word写入文本信息时经常要输出一些具有特殊字体、颜色的文本。本节介绍如何向Word输出格式化的文本。
Microsoft Word X Object Library COM组件中文本格式的设置主要是由文本所使用的字体决定的。该COM组件中可以直接设置C#中的Font类,使用非常方便。常用的格式属性有颜色、加粗、斜体、下画线等。
1.目的说明
分别介绍以下内容:
- 输出不同字体的文本。
- 输出不同颜色的文本。
- 输出带下画线的文本。
- 输出斜体文本。
- 输出加粗文本。
2.操作步骤
(1)创建一个Windows控制台应用程序,命名为CreateFormatWordDemo。
(2)添加对Microsoft Word 12.0 Object Library的引用。
(3)在“Program.cs”文件中添加如下引用。
using MSWord = Microsoft.Office.Interop.Word;
using System.IO;
using System.Reflection;
(4)直接修改“Program.cs”文件的代码如下。
class Program
{
static void Main(string[] args)
{
object path; //文件路径变量
string strContent; //文本内容变量
MSWord.Application wordApp; //Word应用程序变量
MSWord.Document wordDoc; //Word文档变量
path = @"C:\MyWord.docx"; //路径
wordApp = new MSWord.ApplicationClass(); //初始化
//如果已存在,则删除
if (File.Exists((string)path))
{
File.Delete((string)path);
}
//由于使用的是COM库,因此有许多变量需要用Missing.Value代替
Object Nothing = Missing.Value;
wordDoc = wordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing);
//写入普通文本
strContent = "普通文本普通文本普通文本普通文本普通文本\n";
wordDoc.Paragraphs.Last.Range.Text = strContent;
//写入黑体文本
strContent = "黑体文本黑体文本黑体文本黑体文本黑体文本\n";
wordDoc.Paragraphs.Last.Range.Font.Name = "黑体";
wordDoc.Paragraphs.Last.Range.Text = strContent;
//写入加粗文本
strContent = "加粗文本加粗文本加粗文本加粗文本加粗文本\n";
wordDoc.Paragraphs.Last.Range.Font.Bold = 1;
wordDoc.Paragraphs.Last.Range.Text = strContent;
//写入15号字体文本
strContent = "15号字体文本15号字体文本15号字体文本15号字体文本\n";
wordDoc.Paragraphs.Last.Range.Font.Size = 15;
wordDoc.Paragraphs.Last.Range.Text = strContent;
//写入斜体文本
strContent = "斜体文本斜体文本斜体文本斜体文本斜体文本\n";
wordDoc.Paragraphs.Last.Range.Font.Italic = 1;
wordDoc.Paragraphs.Last.Range.Text = strContent;
//写入蓝色文本
strContent = "蓝色文本蓝色文本蓝色文本蓝色文本蓝色文本\n";
wordDoc.Paragraphs.Last.Range.Font.Color = MSWord.WdColor.wdColorBlue;
wordDoc.Paragraphs.Last.Range.Text = strContent;
//写入下画线文本
strContent = "下画线文本下画线文本下画线文本下画线文本下画线文本\n";
wordDoc.Paragraphs.Last.Range.Font.Underline = MSWord.WdUnderline.wdUnderlineThick;
wordDoc.Paragraphs.Last.Range.Text = strContent;
//写入红色下画线文本
strContent = "红色下画线文本红色下画线文本红色下画线文本红色下画线文本\n";
wordDoc.Paragraphs.Last.Range.Font.Underline = MSWord.WdUnderline.wdUnderlineThick;
wordDoc.Paragraphs.Last.Range.Font.UnderlineColor = MSWord.WdColor.wdColorRed;
wordDoc.Paragraphs.Last.Range.Text = strContent;
//WdSaveFormat为Word 2007文档的保存格式
object format =MSWord.WdSaveFormat.wdFormatDocumentDefault;
//将wordDoc文档对象的内容保存为DOCX文档
wordDoc.SaveAs(ref path, ref format, 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文档对象
wordDoc.Close(ref Nothing, ref Nothing, ref Nothing);
//关闭wordApp组件对象
wordApp.Quit(ref Nothing, ref Nothing, ref Nothing);
Console.WriteLine(path + " 创建完毕!");
}
}
3.运行结果
运行程序,结果如图8.11所示。
打开C盘根目录下的MyWord.docx,如图8.12所示。
图8.11 运行结果 图8.12 运行结果
8.4 使用C#向Word文档中添加表格
除了简单的文本信息外,Microsoft Word也是一个处理表格的强大工具。许多数据报表也需要通过表格的形式在Word中体现。本节将介绍如何使用C#在Word中创建一个表格。
表格是由Microsoft Word X Object Library中的MSWord.Table定义的,通过在Word文档中的Tables集合中添加一个Table对象,即可在Word文档中创建一个表格。该表格的行数和列数等属性都可以在Tables的Add方法中定义,表格的内容可由Cell属性访问。
1.目的说明
介绍如何向Word文档中输出表格和如何向Word文档中的表格填充文本。
2.操作步骤
(1)创建一个Windows控制台应用程序,命名为CreateTableDemo。
(2)添加对Microsoft Word 12.0 Object Library的引用。
(3)在“Program.cs”文件中添加如下引用。
using MSWord = Microsoft.Office.Interop.Word;
using System.IO;
using System.Reflection;
(4)直接修改“Program.cs”文件的代码如下。
class Program
{
static void Main(string[] args)
{
object path; //文件路径变量
string strContent; //文本内容变量
MSWord.Application wordApp; //Word应用程序变量
MSWord.Document wordDoc; //Word文档变量
path = @"C:\MyWord.docx"; //路径
wordApp = new MSWord.ApplicationClass(); //初始化
//如果已存在,则删除
if (File.Exists((string)path))
{
File.Delete((string)path);
}
//由于使用的是COM库,因此有许多变量需要用Missing.Value代替
Object Nothing = Missing.Value;
wordDoc = wordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing);
//定义一个Word中的表格对象
MSWord.Table table = wordDoc.Tables.Add(wordApp.Selection.Range, 5, 5, ref Nothing, ref Nothing);
//默认创建的表格没有边框,这里修改其属性,使得创建的表格带有边框
table.Borders.Enable = 1;
//使用两层循环填充表格的内容
for (int i = 1; i <= 5; i++)
{
for (int j = 1; j <= 5; j++)
{
table.Cell(i,j).Range.Text = "第"+ i +"行,第"+ j +"列";
}
}
//WdSaveFormat为Word 2007文档的保存格式
object format =MSWord.WdSaveFormat.wdFormatDocumentDefault;
//将wordDoc文档对象的内容保存为DOCX文档
wordDoc.SaveAs(ref path, ref format, 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文档对象
wordDoc.Close(ref Nothing, ref Nothing, ref Nothing);
//关闭wordApp组件对象
wordApp.Quit(ref Nothing, ref Nothing, ref Nothing);
Console.WriteLine(path + " 创建完毕!");
}
}
3.运行结果
运行程序,结果如图8.13所示。
打开C盘根目录下的MyWord.docx,如图8.14所示。
图8.13 运行结果 图8.14 运行结果
8.5 使用C#向Word文档中插入图片
要想创建一个完整美观的Word文档,图片是必不可少的。本节将要介绍的内容就是如何从C#中向Word文档中写入一个图片文件。
在COM组件Microsoft Word X Object Library中,图片是由MSWord.Document. InlineShapes.AddPicture负责添加的,而没有单独表示图片的对象。只需用AddPicture方法给出图片的物理地址及一些简单的属性即可向Word文档中添加图片。
1.目的说明
本实例介绍的知识点为如何向Word文档中输出图片。
2.操作步骤
(1)创建一个Windows控制台应用程序,命名为CreatePicDemo。
(2)添加对Microsoft Word 12.0 Object Library的引用。
(3)在“Program.cs”文件中添加如下引用。
using MSWord = Microsoft.Office.Interop.Word;
using System.IO;
using System.Reflection;
(4)直接修改“Program.cs”文件的代码如下。
class Program
{
static void Main(string[] args)
{
object path; //文件路径变量
string strContent; //文本内容变量
MSWord.Application wordApp; //Word应用程序变量
MSWord.Document wordDoc; //Word文档变量
path = @"C:\MyWord.docx"; //路径
wordApp = new MSWord.ApplicationClass(); //初始化
//如果已存在,则删除
if (File.Exists((string)path))
{
File.Delete((string)path);
}
//由于使用的是COM库,因此有许多变量需要用Missing.Value代替
Object Nothing = Missing.Value;
wordDoc = wordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing);
//图片文件的路径
string filename = @"C:\BackgroundImage.jpg";
//要向Word文档中插入图片的位置
Object range = wordDoc.Paragraphs.Last.Range;
//定义该插入的图片是否为外部链接
Object linkToFile = false; //默认
//定义要插入的图片是否随Word文档一起保存
Object saveWithDocument = true; //默认
//使用InlineShapes.AddPicture方法插入图片
wordDoc.InlineShapes.AddPicture(filename, ref linkToFile, ref saveWithDocument, ref range);
//WdSaveFormat为Word 2007文档的保存格式
object format = MSWord.WdSaveFormat.wdFormatDocumentDefault;
//将wordDoc文档对象的内容保存为DOCX文档
wordDoc.SaveAs(ref path, ref format, 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文档对象
wordDoc.Close(ref Nothing, ref Nothing, ref Nothing);
//关闭wordApp组件对象
wordApp.Quit(ref Nothing, ref Nothing, ref Nothing);
Console.WriteLine(path + " 创建完毕!");
}
}
3.运行结果
运行程序,结果如图8.15所示。
图8.15 运行结果
打开C盘根目录下的MyWord.docx,如图8.16所示。
图8.16 运行结果
本文来自CSDN博客,转载请标明出处:<http://blog.csdn.net/lazy20018/archive/2009/08/12/4438311.aspx>
C#读取WorD表格中的数据
object missing = System.Reflection.Missing.Value;
object savech=WdSaveOptions.wdDoNotSaveChanges ;
mydoc=wordApp.Documents.Open(ref myobj,ref missing,ref myfalse,ref missing,ref missing,ref missing,ref missing,ref missing,ref missing,ref missing,ref missing,ref mytrue,ref missing,ref missing,ref missing,ref missing);
Word.Table mytable=mydoc.Tables[i];
//开始读取表格宽高,数据等
mytable.Rows.Count; //表行数
//Word.Range myRange; //RANGE对象
myRange = mytable.Rows[0].Cells[0].Range.Text.ToString();
if (mydoc!=null)
{
mydoc.Close(ref savech,ref missing,ref missing);
}
本文来自CSDN博客,转载请标明出处:<http://blog.csdn.net/sukey00/archive/2005/10/12/500303.aspx>
C# 对Word2007的新建,打开,添加段落
代码其实很简单:view plaincopy to clipboardprint?
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using Microsoft.Office.Interop.Word;
using Microsoft.Office.Core;
namespace TestWord
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Word 2007");
Microsoft.Office.Interop.Word._Application oWord = new Microsoft.Office.Interop.Word.Application();
oWord.Visible = true;
Microsoft.Office.Interop.Word._Document oDoc;
object oMissing = System.Reflection.Missing.Value;
object strFileName = "C:\\test.docx";
if (File.Exists((string)strFileName))
File.Delete((string)strFileName);
// Create An New Word
oDoc = oWord.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing);
oDoc.Paragraphs.Last.Range.Text = "Created An New word !\n\r";
oDoc.SaveAs(ref strFileName, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oMissing);
oDoc.Close(ref oMissing, ref oMissing, ref oMissing);
oWord.Quit(ref oMissing, ref oMissing, ref oMissing);
Console.WriteLine("Created An New word");
// Open the Word
oDoc = null;
oWord = null;
oWord = new Microsoft.Office.Interop.Word.Application();
oDoc = oWord.Documents.Open(ref strFileName,
ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);
oDoc.Paragraphs.Last.Range.Text = "Open The Word !\n\r";
Console.WriteLine("Open The New word");
// Insert a paragraph
Microsoft.Office.Interop.Word.Paragraph oPara1;
oPara1 = oDoc.Content.Paragraphs.Add(ref oMissing);
oPara1.Range.Text = "Heading 1";
oPara1.Range.Font.Bold = 1;
oPara1.Format.SpaceAfter = 24; //24 pt spacing after paragraph.
oPara1.Range.InsertParagraphAfter();
Console.WriteLine("Insert a paragraph");
// Close
oDoc.Save();
oDoc.Close(ref oMissing, ref oMissing, ref oMissing);
oWord.Quit(ref oMissing, ref oMissing, ref oMissing);
Console.WriteLine("Close . Over");
}
}
}
本文来自CSDN博客,转载请标明出处:<http://blog.csdn.net/LCL_data/archive/2009/07/21/4362961.aspx>
c#对excel和word的操作
2007-02-26 12:59
引用 <http://blog.csdn.net/jetxia/archive/2006/03/13/623643.aspx>
另外当然还需要引用Interop.Word.Dll. C#操作Excel(导入导出) 有很多朋友说需要C#导出到Excel的代码,现共享给大家 /// /// 读取Excel文档 /// /// 文件名称 /// 返回一个数据集 public DataSet ExcelToDS(string Path) { string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" +"Data Source="+ Path +";"+"Extended Properties=Excel 8.0;"; OleDbConnection conn = new OleDbConnection(strConn); conn.Open(); string strExcel = ""; OleDbDataAdapter myCommand = null; DataSet ds = null; strExcel="select * from [sheet1$]"; myCommand = new OleDbDataAdapter(strExcel, strConn); ds = new DataSet(); myCommand.Fill(ds,"table1"); return ds; } /// /// 写入Excel文档 /// /// 文件名称 public bool SaveFP2toExcel(string Path) { try { string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" +"Data Source="+ Path +";"+"Extended Properties=Excel 8.0;"; OleDbConnection conn = new OleDbConnection(strConn); conn.Open(); System.Data.OleDb.OleDbCommand cmd=new OleDbCommand (); cmd.Connection =conn; //cmd.CommandText ="UPDATE [sheet1$] SET 姓名='2005-01-01' WHERE 工号='日期'"; //cmd.ExecuteNonQuery (); for(int i=0;i { if(fp2.Sheets [0].Cells[i,0].Text!="") { cmd.CommandText ="INSERT INTO [sheet1$] (工号,姓名,部门,职务,日期,时间) VALUES('"+fp2.Sheets [0].Cells[i,0].Text+ "','"+ fp2.Sheets [0].Cells[i,1].Text+"','"+fp2.Sheets [0].Cells[i,2].Text+"','"+fp2.Sheets [0].Cells[i,3].Text+ "','"+fp2.Sheets [0].Cells[i,4].Text+"','"+fp2.Sheets [0].Cells[i,5].Text+"')"; cmd.ExecuteNonQuery (); } } conn.Close (); return true; } catch(System.Data.OleDb.OleDbException ex) { System.Diagnostics.Debug.WriteLine ("写入Excel发生错误:"+ex.Message ); } return false; } 导出到Excel的时候,创建一个Excel文件 object misvalueExcel = System.Reflection.Missing.Value; Excel.ApplicationClass exApp = new Excel.ApplicationClass(); exApp.DisplayAlerts = false; Excel.Workbook book = exApp.Workbooks.Add(misvalueExcel); book.SaveAs(fileName,misvalueExcel,misvalueExcel,misvalueExcel,misvalueExcel,misvalueExcel,Excel.XlSaveAsAccessMode.xlShared,misvalueExcel,misvalueExcel,misvalueExcel,misvalueExcel,misvalueExcel); book.Close(misvalueExcel,misvalueExcel,misvalueExcel); exApp.Quit();
C#对Word的操作(三)
.单元格分离
object oMissing = System.Reflection.Missing.Value;
Word._Application oWord;
Word._Document oDoc;
oWord = new Word.Application();
oWord.Visible = true;
oDoc = oWord.Documents.Add( oMissing,
ref oMissing, ref oMissing);
object start = 0;
object end = 0;
Word.Range tableLocation = oDoc.Range(ref start, ref end);
oDoc.Tables.Add(tableLocation, 3, 4, ref oMissing, ref oMissing);
Word.Table newTable = oDoc.Tables[1];
object beforeRow = newTable.Rows[1];
newTable.Rows.Add(ref beforeRow);
Word.Cell cell = newTable.Cell(1, 1);
cell.Merge(newTable.Cell(1, 2));
object Rownum = 2;
object Columnnum = 2;
cell.Split(ref Rownum, ref Columnnum);
本文来自CSDN博客,转载请标明出处:<http://blog.csdn.net/lifeng_2009/archive/2009/12/16/5011723.aspx>
C#对Word的操作(四)
记住要引入Word的dll文件 Interop.word.dll (如找不到可以直接根我联系)
在命名空间还有记得加入using System.Reflection;
//===========开始生成Word文档===============好麻烦呀这段=========
private void button5_Click(object sender, EventArgs e)
{
//==========以下程序来自http://support.microsoft.com/kb/316384/zh-cn
object oMissing = System.Reflection.Missing.Value;
object oEndOfDoc = "\\endofdoc"; /* \endofdoc is a predefined bookmark */
//==========开始创建一个Word文档==============
Word._Application oWord = new Word.Application();
Word._Document oDoc = oWord.Documents.Add(ref oMissing, ref oMissing,ref oMissing, ref oMissing);
oWord.Visible = true;
//在文档开始插入一段信息
Word.Paragraph oPara1;
oPara1 = oDoc.Content.Paragraphs.Add(ref oMissing);
oPara1.Range.Text = "TT_Article数据库各表说明";
oPara1.Range.Font.Bold = 1;
oPara1.Format.SpaceAfter = 24; //24 pt spacing after paragraph.
oPara1.Range.InsertParagraphAfter();
//Insert a paragraph at the end of the document.
Word.Paragraph oPara2;
object oRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
oPara2 = oDoc.Content.Paragraphs.Add(ref oRng);
oPara2.Range.Text = "Heading 2";
oPara2.Format.SpaceAfter = 6;
oPara2.Range.InsertParagraphAfter();
//Insert another paragraph.
Word.Paragraph oPara3;
oRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
oPara3 = oDoc.Content.Paragraphs.Add(ref oRng);
oPara3.Range.Text = "This is a sentence of normal text. Now here is a table:";
oPara3.Range.Font.Bold = 0;
oPara3.Format.SpaceAfter = 24;
oPara3.Range.InsertParagraphAfter();
//Insert a 3 x 5 table, fill it with data, and make the first row
//bold and italic.
Word.Table oTable;
Word.Range wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
oTable = oDoc.Tables.Add(wrdRng, 3, 5, ref oMissing, ref oMissing);
oTable.Range.ParagraphFormat.SpaceAfter = 6;
int r, c;
string strText;
for (r = 1; r <= 3; r++)
for (c = 1; c <= 5; c++)
{
strText = "r" + r + "c" + c;
oTable.Cell(r, c).Range.Text = strText;
}
oTable.Rows[1].Range.Font.Bold = 1;
oTable.Rows[1].Range.Font.Italic = 1;
本文来自CSDN博客,转载请标明出处:<http://blog.csdn.net/lifeng_2009/archive/2009/12/16/5011736.aspx>
C# 操作 Word 范例
view plaincopy to clipboardprint?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Word;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
object oMissing = System.Reflection.Missing.Value;
object oEndOfDoc = "\\endofdoc"; /* \endofdoc is a predefined bookmark */
//Start Word and create a new document.
Word._Application oWord;
Word._Document oDoc;
oWord = new Word.Application();
oWord.Visible = true;
oDoc = oWord.Documents.Add(ref oMissing, ref oMissing,
ref oMissing, ref oMissing);
//Paragraph
Word.Paragraph p5;
object range = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
p5 = oDoc.Content.Paragraphs.Add(ref range);
p5.Range.InsertParagraphBefore();
p5.Range.Text = "Paragraph";
p5.Format.SpaceAfter = 24;
p5.OutlineLevel = WdOutlineLevel.wdOutlineLevel1;
p5.Range.Font.Bold = 1;
p5.Range.Font.Name = "隶书";
p5.Range.Font.Size = 24;
p5.Range.InsertParagraphAfter();
//Insert a paragraph at the beginning of the document.
Word.Paragraph oPara1;
oPara1 = oDoc.Content.Paragraphs.Add(ref oMissing);
oPara1.Range.Text = "Heading 1";
oPara1.Range.Font.Bold = 1;
p5.OutlineLevel = WdOutlineLevel.wdOutlineLevel2;
oPara1.Format.SpaceAfter = 24; //24 pt spacing after paragraph.
oPara1.Range.InsertParagraphAfter();
//Insert a paragraph at the end of the document.
Word.Paragraph oPara2;
object oRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
oPara2 = oDoc.Content.Paragraphs.Add(ref oRng);
oPara2.Range.Text = "Heading 2";
p5.OutlineLevel = WdOutlineLevel.wdOutlineLevel2;
oPara2.Format.SpaceAfter = 6;
oPara2.Range.InsertParagraphAfter();
//Insert another paragraph.
Word.Paragraph oPara3;
oRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
oPara3 = oDoc.Content.Paragraphs.Add(ref oRng);
oPara3.Range.Text = "This is a sentence of normal text. Now here is a table:";
p5.OutlineLevel = WdOutlineLevel.wdOutlineLevelBodyText;
oPara3.Range.Font.Bold = 0;
oPara3.Format.SpaceAfter = 24;
oPara3.Range.InsertParagraphAfter();
//Insert a 3 x 5 table, fill it with data, and make the first row
//bold and italic.
Word.Table oTable;
Word.Range wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
oTable = oDoc.Tables.Add(wrdRng, 3, 5, ref oMissing, ref oMissing);
oTable.Range.ParagraphFormat.SpaceAfter = 6;
int r, c;
string strText;
for (r = 1; r <= 3; r++)
for (c = 1; c <= 5; c++)
{
strText = "r" + r + "c" + c;
oTable.Cell(r, c).Range.Text = strText;
}
oTable.Rows[1].Range.Font.Bold = 1;
oTable.Rows[1].Range.Font.Italic = 1;
//Add some text after the table.
Word.Paragraph oPara4;
oRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
oPara4 = oDoc.Content.Paragraphs.Add(ref oRng);
oPara4.Range.InsertParagraphBefore();
p5.OutlineLevel = WdOutlineLevel.wdOutlineLevelBodyText;
oPara4.Range.Text = "And here's another table:";
oPara4.Format.SpaceAfter = 24;
oPara4.Range.InsertParagraphAfter();
oWord.Selection.TypeParagraph();
//Insert a 5 x 4 table, fill it with data, and change the column widths.
wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
wrdRng.Font.Size = 12;
oTable = oDoc.Tables.Add(wrdRng, 5, 4, ref oMissing, ref oMissing);
oTable.Borders.OutsideLineStyle = Word.WdLineStyle.wdLineStyleSingle;
oTable.Columns.Borders.InsideLineStyle = Word.WdLineStyle.wdLineStyleSingle;
oTable.Range.ParagraphFormat.SpaceAfter = 6;
for (r = 1; r <= 5; r++)
for (c = 1; c <= 4; c++)
{
strText = "r" + r + "c" + c;
oTable.Cell(r, c).Range.Text = strText;
}
//Diagonal
oTable.Cell(4, 1).Borders[Word.WdBorderType.wdBorderDiagonalUp].LineStyle = Word.WdLineStyle.wdLineStyleSingle;
oTable.Columns[1].Width = oWord.InchesToPoints(1); //Change width of columns 1 & 2
oTable.Columns[2].Width = oWord.InchesToPoints(1);
// Diagonal value
oTable.Cell(4, 1).Select();
string str = oTable.Cell(4, 1).Range.Text;
oWord.Selection.TypeParagraph();
oTable.Cell(4, 1).Range.Text = str + " test";
/*cell.Range.Select();
app.Selection.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;
app.Selection.TypeText(text1);
app.Selection.TypeParagraph();
app.Selection.TypeText(text2);
app.Selection.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphRight;*/
//Merge
oTable.Cell(1, 1).Merge(oTable.Cell(1, 2));
oTable.Cell(1, 1).Merge(oTable.Cell(1, 2));
//Merge
oTable.Cell(3, 2).Merge(oTable.Cell(4, 2));
//insert image
string fileName = @"C:\1.jpg";
object linkToFile = false;
object saveWithDocument = true;
object anchor = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
oDoc.InlineShapes.AddPicture(fileName, ref linkToFile, ref saveWithDocument, ref anchor);
oDoc.InlineShapes[1].Width = 300;
oDoc.InlineShapes[1].Height = 500;
//Keep inserting text. When you get to 7 inches from top of the
//document, insert a hard page break.
object oPos;
double dPos = oWord.InchesToPoints(7);
oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range.InsertParagraphAfter();
do
{
wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
wrdRng.ParagraphFormat.SpaceAfter = 6;
wrdRng.InsertAfter("A line of text");
wrdRng.InsertParagraphAfter();
oPos = wrdRng.get_Information
(Word.WdInformation.wdVerticalPositionRelativeToPage);
}
while (dPos >= Convert.ToDouble(oPos));
object oCollapseEnd = Word.WdCollapseDirection.wdCollapseEnd;
object oPageBreak = Word.WdBreakType.wdPageBreak;
wrdRng.Collapse(ref oCollapseEnd);
wrdRng.InsertBreak(ref oPageBreak);
wrdRng.Collapse(ref oCollapseEnd);
wrdRng.InsertAfter("We're now on page 2. Here's my chart:");
wrdRng.InsertParagraphAfter();
//Add text after the chart.
wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
wrdRng.InsertParagraphAfter();
wrdRng.InsertAfter("THE END.");
//Close this form.
this.Close();
}
}
}
本文来自CSDN博客,转载请标明出处:<http://blog.csdn.net/qiume/archive/2010/03/16/5380304.aspx>
c#操作word2007
向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.Office.Interop.Word;
namespace WordTest
{
public partial class Form1 : Form
{
object strFileName;
Object Nothing;
Microsoft.Office.Interop.Word.Application myWordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
Document myWordDoc;
string strContent = "";
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
createWord();
//openWord();
}
private void createWord()
{
strFileName = System.Windows.Forms.Application.StartupPath + "test.doc";
if (System.IO.File.Exists((string)strFileName))
System.IO.File.Delete((string)strFileName);
Object Nothing = System.Reflection.Missing.Value;
myWordDoc = myWordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing);
#region 将数据库中读取得数据写入到word文件中
strContent = "你好\n\n\r";
myWordDoc.Paragraphs.Last.Range.Text = strContent;
strContent = "这是测试程序";
myWordDoc.Paragraphs.Last.Range.Text = strContent;
#endregion
//将WordDoc文档对象的内容保存为DOC文档
myWordDoc.SaveAs(ref strFileName, 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文档对象
myWordDoc.Close(ref Nothing, ref Nothing, ref Nothing);
//关闭WordApp组件对象
myWordApp.Quit(ref Nothing, ref Nothing, ref Nothing);
this.richTextBox1.Text = strFileName + "\r\n" + "创建成功";
}
private void openWord()
{
fontDialog1.ShowDialog();
System.Drawing.Font font = fontDialog1.Font;
object filepath = "D:\\asp.docx";
object oMissing = System.Reflection.Missing.Value;
myWordDoc = myWordApp.Documents.Open(ref filepath, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);
myWordDoc.Content.Font.Size = font.Size;
myWordDoc.Content.Font.Name = font.Name;
myWordDoc.Save();
richTextBox1.Text = myWordDoc.Content.Text;
myWordDoc.Close(ref oMissing, ref oMissing, ref oMissing);
myWordApp.Quit(ref oMissing, ref oMissing, ref oMissing);
}
}
本文来自CSDN博客,转载请标明出处:<http://blog.csdn.net/RainyLin/archive/2007/07/27/1711722.aspx>
.net操作word
public class operateWord
{
public operateWord()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
static int textFontSize = 12;
public Microsoft.Office.Interop.Word.ApplicationClass CreateWord() //创建一个word程序并打开一个文档
{
object missing = System.Reflection.Missing.Value;
Microsoft.Office.Interop.Word.ApplicationClass wordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
wordApp.Documents.Add(ref missing,ref missing,ref missing,ref missing);
return wordApp;
}
public void SaveDocument(Microsoft.Office.Interop.Word.Document doc) //保存word文档
{
doc.Save();
}
public void CloseWord(Microsoft.Office.Interop.Word.ApplicationClass app) //关闭word程序
{
object missing = System.Reflection.Missing.Value;
app.Application.Quit(ref missing, ref missing, ref missing);
}
Public void InsertText(int muluDeep,string strwordMulu,string strwordText,Microsoft.Office.Interop.Word.ApplicationClass app)
{
style sty = new style();
switch(muluDeep)
{
case 1:
app.Selection.Font.Size = 18; //标题字体大小
app.Selection.Font.Bold = 1;
app.Selection.TypeText(strwordMulu);
//app.Selection.ParagraphFormat.Alignment = ;
app.Selection.TypeParagraph();
app.Selection.Font.Size = operateWord.textFontSize;
app.Selection.Font.Bold = 0;
app.Selection.TypeText(strwordText);
app.Selection.TypeParagraph();
break;
case 2:
//app.Selection.Style = "标题 2";
app.Selection.Font.Size = 16; //标题字体大小
app.Selection.Font.Bold = 1;
app.Selection.TypeText(strwordMulu);
//app.Selection.ParagraphFormat.Alignment = ;
app.Selection.TypeParagraph();
app.Selection.Font.Size = 10;
app.Selection.Font.Bold = 0;
app.Selection.TypeText(strwordText);
app.Selection.TypeParagraph();
break;
case 3:
//app.Selection.Style = "标题 3";
app.Selection.Font.Size = 12; //标题字体大小
app.Selection.Font.Bold = 1;
app.Selection.TypeText(strwordMulu);
//app.Selection.ParagraphFormat.Alignment = ;
app.Selection.TypeParagraph();
app.Selection.Font.Size = 10; //内容字体大小
app.Selection.Font.Bold = 0;
app.Selection.TypeText(strwordText);
app.Selection.TypeParagraph();
break;
case 4:
//app.Selection.Style = "标题 4";
app.Selection.Font.Size =10; //标题字体大小
app.Selection.Font.Bold = 1;
app.Selection.TypeText(strwordMulu);
//app.Selection.ParagraphFormat.Alignment = ;
app.Selection.TypeParagraph();
app.Selection.Font.Size = 10;
app.Selection.Font.Bold = 0;
app.Selection.TypeText(strwordText);
app.Selection.TypeParagraph();
break;
}
}
}
本文来自CSDN博客,转载请标明出处:<http://blog.csdn.net/angel_303/archive/2005/08/25/464845.aspx>
.net 下word导入textbox
只需要引入Microsoft.Office.Interop.Word
Microsoft.Office.Interop.Word.Application app = new Application();
object missing = Type.Missing;
object obj = FileUpload1.PostedFile.FileName.ToString();
Microsoft.Office.Interop.Word.Document WDoc = app.Documents.Open(ref obj, 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);
txtText.Text = WDoc.Content.Text;
if (WDoc != null)
{
WDoc.Close(ref missing, ref missing, ref missing);
WDoc = null;
}
if (app != null)
{
app.Quit(ref missing, ref missing, ref missing);
app = null;
}
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/c_sharp_rookie/archive/2009/12/29/5100044.aspx
标签:
在C#中对Word进行操作 


上一条:
下一条:
相关评论
发表评论