C#实现对Word文件读写[转]
手头上的一个项目报表相对比较简单,所以报表打印采用VBA引擎,通过定制Word模版,然后根据模版需要填充数据,然后OK,打印即可。
实现方法:首先需要引用VBA组建,我用的是Office2003 Professional,Dll版本号为Microsoft Word11.0
另外当然还需要引用Interop.Word.Dll.
代码如下:
///#region 打开Word文档,并且返回对象wDoc,wDoc
///
/// 打开Word文档,并且返回对象wDoc,wDoc
///
/// 完整Word文件路径+名称
/// 返回的Word.Document wDoc对象
/// 返回的Word.Application对象
public static void CreateWordDocument(string FileName,ref Word.Document wDoc,ref Word.Application WApp)
{
if(FileName == "") return;
Word.Document thisDocument = null;
Word.FormFields formFields = null;
Word.Application thisApplication = new Word.ApplicationClass();
thisApplication.Visible = true;
thisApplication.Caption = "";
thisApplication.Options.CheckSpellingAsYouType = false;
thisApplication.Options.CheckGrammarAsYouType = false; Object filename = FileName;
Object ConfirmConversions = false;
Object ReadOnly = true;
Object AddToRecentFiles = false; Object PasswordDocument = System.Type.Missing;
Object PasswordTemplate = System.Type.Missing;
Object Revert = System.Type.Missing;
Object WritePasswordDocument = System.Type.Missing;
Object WritePasswordTemplate = System.Type.Missing;
Object Format = System.Type.Missing;
Object Encoding = System.Type.Missing;
Object Visible = System.Type.Missing;
Object OpenAndRepair = System.Type.Missing;
Object DocumentDirection = System.Type.Missing;
Object NoEncodingDialog = System.Type.Missing;
Object XMLTransform = System.Type.Missing; try
{
Word.Document wordDoc =
thisApplication.Documents.Open(ref filename, ref ConfirmConversions,
ref ReadOnly, ref AddToRecentFiles, ref PasswordDocument, ref PasswordTemplate,
ref Revert,ref WritePasswordDocument, ref WritePasswordTemplate, ref Format,
ref Encoding, ref Visible, ref OpenAndRepair, ref DocumentDirection,
ref NoEncodingDialog, ref XMLTransform ); thisDocument = wordDoc;
wDoc = wordDoc;
WApp = thisApplication;
formFields = wordDoc.FormFields;
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
} }
#endregion 调用上面静态方法,打开目标文件并且把DataGrid中数据填充到对应Word标签中去 ///#region Word填充数据(For Example)
///
/// Word填充数据
///
private void WordLoadData()
{
Word.Document wDoc=null;
Word.Application wApp=null;
sysFun.CreateWordDocument("E:\\监测报告(new).dot",ref wDoc,ref wApp); //对标签"C"进行填充
object bkmC="C";
if(wApp.ActiveDocument.Bookmarks.Exists("C") == true)
{
wApp.ActiveDocument.Bookmarks.get_Item
(ref bkmC).Select();
}
wApp.Selection.TypeText(this.txt1.Text);
object bkmG = "TWaterTable3";
object unit;
object count; //移动数
object extend; extend = Word.WdMovementType.wdExtend;
unit = Word.WdUnits.wdCell;
//把DataGrid中数据填充到标签TWaterTable3上
if(wApp.ActiveDocument.Bookmarks.Exists("TWaterTable3") == true)
{
wApp.ActiveDocument.Bookmarks.get_Item
(ref bkmG).Select(); for(int i=;i {
if(i==)
{
count=;
}
else
{
count=;
}
//需填充5列数据
wApp.Selection.Move(ref unit,ref count);
wApp.Selection.TypeText(gridEX1.GetRow(i).Cells[].Text);
count=; wApp.Selection.Move(ref unit,ref count);
wApp.Selection.TypeText(gridEX1.GetRow(i).Cells[].Text); wApp.Selection.Move(ref unit,ref count);
wApp.Selection.TypeText(gridEX1.GetRow(i).Cells[].Text); wApp.Selection.Move(ref unit,ref count);
wApp.Selection.TypeText(gridEX1.GetRow(i).Cells[].Text); wApp.Selection.Move(ref unit,ref count);
wApp.Selection.TypeText(gridEX1.GetRow(i).Cells[].Text);
//换行
wApp.Selection.MoveRight(ref unit,ref count,ref extend);
}
}
}
#endregion 然后就OK了,在对标签表控制要注意列循环和换行. 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=;i {
if(fp2.Sheets [].Cells[i,].Text!="")
{
cmd.CommandText ="INSERT INTO [sheet1$] (工号,姓名,部门,职务,日期,时间) VALUES('"+fp2.Sheets [].Cells[i,].Text+ "','"+
fp2.Sheets [].Cells[i,].Text+"','"+fp2.Sheets [].Cells[i,].Text+"','"+fp2.Sheets [].Cells[i,].Text+
"','"+fp2.Sheets [].Cells[i,].Text+"','"+fp2.Sheets [].Cells[i,].Text+"')";
cmd.ExecuteNonQuery ();
}
}
conn.Close ();
return true;
}
catch(System.Data.OleDb.OleDbException ex)
{
System.Diagnostics.Debug.WriteLine ("写入Excel发生错误:"+ex.Message );
}
return false;
} 这种方法是相当有效的。
下附:VB.NET版实现word打开与关闭,有兴趣的朋友可以研究一下 VB.NET实现word打开与关闭 Imports Word '打开 Dim mWordapp As Word.Application 'word 应用程序 Dim mobjDoc As Word.Document 'word 文档 Dim fullFileName as string '文件路径 mWordapp = CreateObject("Word.Application") mobjDoc = mWordapp.Documents.Add(FullFileName) '关闭 Dim missing As Object = System.Reflection.Missing.Value mWordapp.Application.Quit() If Not mobjDoc Is Nothing Then '垃圾回收 System.Runtime.InteropServices.Marshal.ReleaseComObject(mobjDoc) mobjDoc = Nothing End If If Not mWordapp Is Nothing Then System.Runtime.InteropServices.Marshal.ReleaseComObject(mWordapp) mWordapp = Nothing End If '真正释放word进程
C#实现对Word文件读写[转]的更多相关文章
- Apache POI 实现对 Excel 文件读写
1. Apache POI 简介 Apache POI是Apache软件基金会的开放源码函式库. 提供API给Java应用程序对Microsoft Office格式档案读和写的功能. 老外起名字总是很 ...
- python 使用win32com实现对word文档批量替换页眉页脚
最近由于工作需要,需要将70个word文件的页眉页脚全部进行修改,在想到这个无聊/重复/没有任何技术含量的工作时,我的内心是相当奔溃的.就在我接近奔溃的时候我突然想到完全可以用python脚本来实现这 ...
- jeecms系统使用介绍——通过二次开发实现对word、pdf、txt等上传附件的全文检索
转载请注明出处:http://blog.csdn.net/dongdong9223/article/details/76912307 本文出自[我是干勾鱼的博客] 之前在文章<基于Java的门户 ...
- 【JAVA使用XPath、DOM4J解析XML文件,实现对XML文件的CRUD操作】
一.简介 1.使用XPath可以快速精确定位指定的节点,以实现对XML文件的CRUD操作. 2.去网上下载一个“XPath帮助文档”,以便于查看语法等详细信息,最好是那种有很多实例的那种. 3.学习X ...
- Java代码加密与反编译(二):用加密算法DES修改classLoader实现对.class文件加密
Java代码加密与反编译(二):用加密算法DES修改classLoader实现对.class文件加密 二.利用加密算法DES实现java代码加密 传统的C/C++自动带有保护机制,但java不同,只要 ...
- JDOM方法实现对XML文件的解析
首先要下载JDOM.jar包,下载地址:http://download.csdn.net/detail/ww6055/8880371 下载到JDOM.jar包之后导入到工程中去. 实例程序: book ...
- 利用COM组件实现对WORD书签各种操作大全,看这一篇就够了
有个需求是,程序导出一份word报告,报告中有各种各样的表格,导出时还需要插入图片. 脑海中迅速闪过好几种组件,openxml组件,com组件,npoi.为了减少程序画复杂表格,我们选用了com组件+ ...
- Windows下使用scapy+python2.7实现对pcap文件的读写操作
scapy在linux环境中对pcap文件进行操作非常方便,但在windows下,特别是在python2.7环境下却会碰到各种各样的依赖包无法使用的问题,最明显的可能就属dnet和pcap的pytho ...
- 实现对properties文件的有序读写
最近遇到一项需求,要求把properties文件中的内容读取出来供用户修改,修改完后需要再重新保存到properties文件中.很简单的需求吧,可问题是Properties是继承自HashTable的 ...
随机推荐
- 简单易用的AOP/IOC框架
Source: http://www.codeproject.com/KB/Articles/684613/Working/AopIoc.zip Introduction Supper framewo ...
- POJ 2728 Desert King 01分数规划,最优比率生成树
一个完全图,每两个点之间的cost是海拔差距的绝对值,长度是平面欧式距离, 让你找到一棵生成树,使得树边的的cost的和/距离的和,比例最小 然后就是最优比例生成树,也就是01规划裸题 看这一发:ht ...
- DateTime.ToString格式化日期,使用DateDiff方法获取日期时间的间隔数
一:DateTime.ToString格式化日期 二:代码 using System; using System.Collections.Generic; using System.Component ...
- <转>详解DNS的常用记录(上):DNS系列之二
详解DNS的常用记录(上) 在上篇博文中,我们介绍了DNS服务器的体系结构,从中我们了解到如果我们希望注册一个域名,那么必须经过顶级域名服务器或其下级的域名服务器为我们申请的域名进行委派,把解析权委派 ...
- 在ubuntu下配置android开发环境
http://developer.android.com/sdk/installing/index.html 基本上上面官网的链接可以解决所有问题,但是具体在安装过程中还是有一些坑. 说说具体流程 1 ...
- 题目1433:FatMouse (未解决)
题目描述: FatMouse prepared M pounds of cat food, ready to trade with the cats guarding the warehouse co ...
- 在eclipse中配置spark 0.9.1源码的开发环境
一.准备工作: 1.下载release版spark 0.9.1,本次用的版本是spark-0.9.1-bin-cdh4. 2.下载scala IDE 3.0.2,这个版本ide的支持scala 2.1 ...
- linux网络编程笔记——UDP
目前这部分代码会出现阻塞问题,暂时尚未解决 #include "udp.h" #include <stdio.h> #include <string.h> ...
- CentOS 7 最小化安装之后安装Mysql
启动网卡 验证网络管理器和网卡接口状态 # systemctl status NetworkManager.service # nmcli dev status 修改网卡配置文件 通过上一步可以看到有 ...
- FMX架构图