博客备份系统之一:PDF,Word,TXT文件操作类
2011年到了,在前几天的“2010岁末小记”中给自己定下了一个计划,其中有一条就是“每周至少写一篇技术博客。用博客的方式来督促自己学习和进步,记下学习的新知识和积累的知识点,构建自己的知识库。”。园子里高手很多,MVP就有好几位,看他们的文章真有“看君一博文,胜读四年书”之感。曾经对委托、事件云里雾里的我看了张子阳的“C#中的委托和事件”后终于明白了很多,园子里像这样的好文章还有很多,作为菜鸟我真的获益匪浅。
虽然自己现在水平很差,但高手都是从菜鸟成长起来的,因此我坚信只要努力学习,每天都有收获和进步,逐渐提高自己的编程水平,总有一天也能厚积薄发,写出一些比较好的博文与大家分享,帮助新手进步。作为新年第一篇博文,我打算写一个博客备份系统系列文章与园友们分享,晒晒自己的代码,非常欢迎大家提出意见和建议。
本文作为此系列的开篇,只写几个后面要用到的重要的类,PDF、Word、TXT文件操作类,其中Word、TXT文件操作类网上很多,这两个类的代码我只直接贴出来,重点说一下PDF文件操作类。
一、PDF文件操作类
本文PDF文件操作类用iTextSharp控件,这是一个开源项目(http://sourceforge.net/projects/itextsharp/),园子里也有这方面的文章,我的PDF操作类只是做了一点封装,使使用起来更方便。在贴出代码前先对其中几个比较关键的地方作一下说明。
1、文档的创建
PDF文档的创建是实例化一个Document对像,有三个构造函数:
public Document(Rectangle pageSize);
public Document(Rectangle pageSize, float marginLeft, float marginRight, float marginTop, float marginBottom);
第一个是默认大小,第二个是按给定的大小创建文档,第三个就是按给定的大小创建文档,并且文档内容离左、右、上、下的距离。其中的Rectangle也是iTextSharp中的一个表示矩形的类,这里只用来表示大小。不过要注意的是在向文档里写内容之前还要调用GetInstance方法哦,这个方法传进去一些文档相关信息(如路径,打开方式等)。
2、字体的设置
PDF文件字体在iTextSharp中有两个类,BaseFont和Font,BaseFont是一个抽象类,BaseFont和Font的构造函数如下:
BaseFont:
public static BaseFont CreateFont(PRIndirectReference fontRef);
public static BaseFont CreateFont(string name, string encoding, bool embedded);
public static BaseFont CreateFont(string name, string encoding, bool embedded, bool forceRead);
public static BaseFont CreateFont(string name, string encoding, bool embedded, bool cached, byte[] ttfAfm, byte[] pfb);
public static BaseFont CreateFont(string name, string encoding, bool embedded, bool cached, byte[] ttfAfm, byte[] pfb, bool noThrow);
public static BaseFont CreateFont(string name, string encoding, bool embedded, bool cached, byte[] ttfAfm, byte[] pfb, bool noThrow, bool forceRead);
默认的构造函数用的是英文字体,如果想用中文一般用的是第三个构造函数,这三个参数前两个意思是字体名子或字体资源路径,第三个参数我也没弄明白是什么意思。如果用字体名子其实用的是这个DLL内置字体,如果用字体资源名子可以用系统字体存放路径,如“C:\Windows\Fonts\SIMHEI.TTF”(windows系统),也可以把字体文件放在应用程序目录,然后取这个路径。
Font:
public Font(BaseFont bf);
public Font(Font other);
public Font(Font.FontFamily family);
public Font(BaseFont bf, float size);
public Font(Font.FontFamily family, float size);
public Font(BaseFont bf, float size, int style);
public Font(Font.FontFamily family, float size, int style);
public Font(BaseFont bf, float size, int style, BaseColor color);
public Font(Font.FontFamily family, float size, int style, BaseColor color);
一般用的是第五个构造函数,也就是从BaseFont创建,然后设置字体大小。因为iTestSharp在添加文字时字体参数用的都是Font,因些一般的做法是先创建BaseFont对象,再用这个对象加上大小来实例化Font对象。
3、添加段落
iTextSharp对段落分了三个级别,从小到大依次为Chunk、Phrase、Paragraph。Chunk : 块,PDF文档中描述的最小原子元,Phrase : 短语,Chunk的集合,Paragraph : 段落,一个有序的Phrase集合。你可以简单地把这三者理解为字符,单词,文章的关系。
Document对象添加内容的方法为:
Chunk、Phrase实现了IElement接口,Paragraph继承自Phrase,因些Document可直接添加这三个对象。
Paragraph的构造函数是:
public Paragraph(Chunk chunk);
public Paragraph(float leading);
public Paragraph(Phrase phrase);
public Paragraph(string str);
public Paragraph(float leading, Chunk chunk);
public Paragraph(float leading, string str);
public Paragraph(string str, Font font);
public Paragraph(float leading, string str, Font font);
大家可以看到Chunk、Phrase都可以实例化Paragraph,不过我用的比较多的是倒数第二个。当然了,Paragraph还有一些属性可以让我们给段落设定一些格式,比如对齐方式,段前空行数,段后空行数,行间距等。 这些属性如下:
protected float indentationLeft;
protected float indentationRight;
protected bool keeptogether;
protected float multipliedLeading;
protected float spacingAfter;
protected float spacingBefore;
略作解释:alignmant为对齐方式(1为居中,0为居左,2为居右),indentationLeft为左缩进,indentationRight为右缩进,keeptogether保持在一起(常用在对内容绝对定位),multipliedLeading为行间距,spacingAfter为段前空行数,spacingBefore为段后空行数。
4、内部链接和外部链接
链接在iTextSharp中有Anchor对象,它有两个属性,name和reference,name自然就是链接的名称了,reference就是链接的地址了,如果是外部链接reference直接就是一个网址,如果是内部链接,就跟html中的锚一样,用'#'加上name名,示例如下:
Anchor anchor = new Anchor("博客园", font);
anchor.Reference = "http://www.cnblogs.com";
anchor.Name = "博客园";
//内部链接示例
Anchor anc1 = new Anchor("This is an internal link test");
anc1.Name = "test";
Anchor anc2 = new Anchor("Click here to jump to the internal link test");
anc2.Reference = "#test";
5、插入图片
在PDF中插入图片用的是iTextSharp中的Image类。这个类的构造函数很简单:
public Image(Uri url);
常用的就是用图片的Uri来实例化一个图片。因为这个数继承自Rectangle,而Rectangle又实现了IElement接口,因些可以直接将图片添加到文档中。Image有很多属性用来控制格式,不过常用的也就是对齐方式(Alignment),图片大小的控制了。不过值得一提的就是ScaleAbsolute方法:
看参数就知道是给图片重新设定宽度和高度的,我的做法是如果图片宽度大于文档宽度就按比例缩小,否则不处理:
/// 添加图片
/// </summary>
/// <param name="path">图片路径</param>
/// <param name="Alignment">对齐方式(1为居中,0为居左,2为居右)</param>
/// <param name="newWidth">图片宽(0为默认值,如果宽度大于页宽将按比率缩放)</param>
/// <param name="newHeight">图片高</param>
public void AddImage(string path, int Alignment, float newWidth, float newHeight)
{
Image img = Image.GetInstance(path);
img.Alignment = Alignment;
if (newWidth != 0)
{
img.ScaleAbsolute(newWidth, newHeight);
}
else
{
if (img.Width > PageSize.A4.Width)
{
img.ScaleAbsolute(rect.Width, img.Width * img.Height / rect.Height);
}
}
document.Add(img);
}
其中的rect是我定义的一个文档大小属性。
好了,下面就贴出我的PDF文档操作类吧。为了达到封装的目地(这里说的封装意思是调用的类可以不引用iTextSharp这个DLL),我在传参过程中做了一点更改。如设置页面大小时Document的构造函数中提供了用Rectangle对象实例化,但因为这个类是iTextSharp中的,因此我改为传一个字符串(如"A4"),根据这个字符串实例化一个Rectangle对象,再来设置页面大小,其它地方类似。
using System.Collections.Generic;
using System.Linq;
using System.Text;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.IO;
namespace BlogBakLib
{
/// <summary>
/// PDF文档操作类
/// 作者:天行健,自强不息(http://www.cnblogs.com/durongjian)
/// 创建日期:2011年1月5日
/// </summary>
public class PDFOperation
{
//文档对象
private Document document;
//文档大小
private Rectangle rect;
//字体
private BaseFont basefont;
private Font font;
/// <summary>
/// 构造函数
/// </summary>
public PDFOperation()
{
rect = PageSize.A4;
document = new Document(rect);
}
/// <summary>
/// 构造函数
/// </summary>
/// <param name="type">页面大小(如"A4")</param>
public PDFOperation(string type)
{
SetPageSize(type);
document = new Document(rect);
}
/// <summary>
/// 构造函数
/// </summary>
/// <param name="type">页面大小(如"A4")</param>
/// <param name="marginLeft">内容距左边框距离</param>
/// <param name="marginRight">内容距右边框距离</param>
/// <param name="marginTop">内容距上边框距离</param>
/// <param name="marginBottom">内容距下边框距离</param>
public PDFOperation(string type,float marginLeft, float marginRight, float marginTop, float marginBottom)
{
SetPageSize(type);
document = new Document(rect,marginLeft,marginRight,marginTop,marginBottom);
}
/// <summary>
/// 构造函数
/// </summary>
/// <param name="type">页面大小(如"A4")</param>
public PDFOperation(string type)
{
SetPageSize(type);
document = new Document(rect);
}
/// <summary>
/// 设置页面大小
/// </summary>
/// <param name="type">页面大小(如"A4")</param>
public void SetPageSize(string type)
{
switch (type.Trim())
{
case "A4":
rect = PageSize.A4;
break;
case "A8":
rect = PageSize.A8;
break;
}
}
/// <summary>
/// 设置字体
/// </summary>
public void SetBaseFont(string path)
{
basefont = BaseFont.CreateFont(path, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
}
/// <summary>
/// 设置字体
/// </summary>
/// <param name="size">字体大小</param>
public void SetFont(float size)
{
font = new Font(basefont, size);
}
/// <summary>
/// 实例化文档
/// </summary>
/// <param name="os">文档相关信息(如路径,打开方式等)</param>
public void GetInstance(Stream os)
{
PdfWriter.GetInstance(document, os);
}
/// <summary>
/// 打开文档对象
/// </summary>
/// <param name="os">文档相关信息(如路径,打开方式等)</param>
public void Open(Stream os)
{
GetInstance(os);
document.Open();
}
/// <summary>
/// 关闭打开的文档
/// </summary>
public void Close()
{
document.Close();
}
/// <summary>
/// 添加段落
/// </summary>
/// <param name="content">内容</param>
/// <param name="fontsize">字体大小</param>
public void AddParagraph(string content, float fontsize)
{
SetFont(fontsize);
Paragraph pra = new Paragraph(content,font);
document.Add(pra);
}
/// <summary>
/// 添加段落
/// </summary>
/// <param name="content">内容</param>
/// <param name="fontsize">字体大小</param>
/// <param name="Alignment">对齐方式(1为居中,0为居左,2为居右)</param>
/// <param name="SpacingAfter">段后空行数(0为默认值)</param>
/// <param name="SpacingBefore">段前空行数(0为默认值)</param>
/// <param name="MultipliedLeading">行间距(0为默认值)</param>
public void AddParagraph(string content, float fontsize, int Alignment, float SpacingAfter, float SpacingBefore, float MultipliedLeading)
{
SetFont(fontsize);
Paragraph pra = new Paragraph(content, font);
pra.Alignment = Alignment;
if (SpacingAfter != 0)
{
pra.SpacingAfter = SpacingAfter;
}
if (SpacingBefore != 0)
{
pra.SpacingBefore = SpacingBefore;
}
if (MultipliedLeading != 0)
{
pra.MultipliedLeading = MultipliedLeading;
}
document.Add(pra);
}
/// <summary>
/// 添加链接
/// </summary>
/// <param name="Content">链接文字</param>
/// <param name="FontSize">字体大小</param>
/// <param name="Reference">链接地址</param>
public void AddAnchorReference(string Content, float FontSize, string Reference)
{
SetFont(FontSize);
Anchor auc = new Anchor(Content, font);
auc.Reference = Reference;
document.Add(auc);
}
/// <summary>
/// 添加链接点
/// </summary>
/// <param name="Content">链接文字</param>
/// <param name="FontSize">字体大小</param>
/// <param name="Name">链接点名</param>
public void AddAnchorName(string Content, float FontSize, string Name)
{
SetFont(FontSize);
Anchor auc = new Anchor(Content, font);
auc.Name = Name;
document.Add(auc);
}
/// <summary>
/// 添加图片
/// </summary>
/// <param name="path">图片路径</param>
/// <param name="Alignment">对齐方式(1为居中,0为居左,2为居右)</param>
/// <param name="newWidth">图片宽(0为默认值,如果宽度大于页宽将按比率缩放)</param>
/// <param name="newHeight">图片高</param>
public void AddImage(string path, int Alignment, float newWidth, float newHeight)
{
Image img = Image.GetInstance(path);
img.Alignment = Alignment;
if (newWidth != 0)
{
img.ScaleAbsolute(newWidth, newHeight);
}
else
{
if (img.Width > PageSize.A4.Width)
{
img.ScaleAbsolute(rect.Width, img.Width * img.Height / rect.Height);
}
}
document.Add(img);
}
}
}
好了,PDF操作类就写到这儿吧!因为本人编程是自学的,在编码规范方面可能做的不好,大家对这个类中的代码有什么改进意见请在评论中指出来哦!
二、WORD文档操作类
这个就不说了,直接贴代码:
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.IO;
namespace BlogMoveLib
{
public class WordOperation
{
private Microsoft.Office.Interop.Word.ApplicationClass oWordApplic;
private Microsoft.Office.Interop.Word.Document oDoc;
object missing = System.Reflection.Missing.Value;
public Microsoft.Office.Interop.Word.ApplicationClass WordApplication
{
get { return oWordApplic; }
}
public WordOperation()
{
oWordApplic = new Microsoft.Office.Interop.Word.ApplicationClass();
}
public WordOperation(Microsoft.Office.Interop.Word.ApplicationClass wordapp)
{
oWordApplic = wordapp;
}
#region 文件操作
// Open a file (the file must exists) and activate it
public void Open(string strFileName)
{
object fileName = strFileName;
object readOnly = false;
object isVisible = true;
oDoc = oWordApplic.Documents.Open(ref fileName, ref missing, ref readOnly,
ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref isVisible, ref missing, ref missing, ref missing, ref missing);
oDoc.Activate();
}
// Open a new document
public void Open()
{
oDoc = oWordApplic.Documents.Add(ref missing, ref missing, ref missing, ref missing);
oDoc.Activate();
}
public void Quit()
{
oWordApplic.Application.Quit(ref missing, ref missing, ref missing);
}
/// <summary>
/// 附加dot模版文件
/// </summary>
private void LoadDotFile(string strDotFile)
{
if (!string.IsNullOrEmpty(strDotFile))
{
Microsoft.Office.Interop.Word.Document wDot = null;
if (oWordApplic != null)
{
oDoc = oWordApplic.ActiveDocument;
oWordApplic.Selection.WholeStory();
//string strContent = oWordApplic.Selection.Text;
oWordApplic.Selection.Copy();
wDot = CreateWordDocument(strDotFile, true);
object bkmC = "Content";
if (oWordApplic.ActiveDocument.Bookmarks.Exists("Content") == true)
{
oWordApplic.ActiveDocument.Bookmarks.get_Item
(ref bkmC).Select();
}
//对标签"Content"进行填充
//直接写入内容不能识别表格什么的
//oWordApplic.Selection.TypeText(strContent);
oWordApplic.Selection.Paste();
oWordApplic.Selection.WholeStory();
oWordApplic.Selection.Copy();
wDot.Close(ref missing, ref missing, ref missing);
oDoc.Activate();
oWordApplic.Selection.Paste();
}
}
}
///
/// 打开Word文档,并且返回对象oDoc
/// 完整Word文件路径+名称
/// 返回的Word.Document oDoc对象
public Microsoft.Office.Interop.Word.Document CreateWordDocument(string FileName, bool HideWin)
{
if (FileName == "") return null;
oWordApplic.Visible = HideWin;
oWordApplic.Caption = "";
oWordApplic.Options.CheckSpellingAsYouType = false;
oWordApplic.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
{
Microsoft.Office.Interop.Word.Document wordDoc = oWordApplic.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);
return wordDoc;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
public void SaveAs(Microsoft.Office.Interop.Word.Document oDoc, string strFileName)
{
object fileName = strFileName;
if (File.Exists(strFileName))
{
throw new Exception("文件已经存在!");
}
else
{
oDoc.SaveAs(ref fileName, 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);
}
}
public void SaveAsHtml(Microsoft.Office.Interop.Word.Document oDoc, string strFileName)
{
object fileName = strFileName;
//wdFormatWebArchive保存为单个网页文件
//wdFormatFilteredHTML保存为过滤掉word标签的htm文件,缺点是有图片的话会产生网页文件夹
if (File.Exists(strFileName))
{
throw new Exception("文件已经存在!");
}
else
{
object Format = (int)Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatWebArchive;
oDoc.SaveAs(ref fileName, ref Format, 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);
}
}
public void Save()
{
oDoc.Save();
}
public void Close()
{
oDoc.Close(ref missing, ref missing, ref missing);
//关闭wordApp组件对象
oWordApplic.Quit(ref missing, ref missing, ref missing);
}
public void SaveAs(string strFileName)
{
object FileName =strFileName;
object FileFormat = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatRTF;
object LockComments = false;
object AddToRecentFiles = true;
object ReadOnlyRecommended = false;
object EmbedTrueTypeFonts = false;
object SaveNativePictureFormat = true;
object SaveFormsData = true;
object SaveAsAOCELetter = false;
object Encoding = Microsoft.Office.Core.MsoEncoding.msoEncodingEBCDICSimplifiedChineseExtendedAndSimplifiedChinese;
object InsertLineBreaks = false;
object AllowSubstitutions = false;
object LineEnding = Microsoft.Office.Interop.Word.WdLineEndingType.wdCRLF;
object AddBiDiMarks = false;
try
{
oDoc.SaveAs(ref FileName, ref FileFormat, ref LockComments,
ref missing, ref AddToRecentFiles, ref missing,
ref ReadOnlyRecommended, ref EmbedTrueTypeFonts,
ref SaveNativePictureFormat, ref SaveFormsData,
ref SaveAsAOCELetter, ref Encoding, ref InsertLineBreaks,
ref AllowSubstitutions, ref LineEnding, ref AddBiDiMarks);
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
// Save the document in HTML format
public void SaveAsHtml(string strFileName)
{
object fileName = strFileName;
object Format = (int)Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatHTML;
oDoc.SaveAs(ref fileName, ref Format, 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);
}
#endregion
#region 添加菜单(工具栏)项
//添加单独的菜单项
public void AddMenu(Microsoft.Office.Core.CommandBarPopup popuBar)
{
Microsoft.Office.Core.CommandBar menuBar = null;
menuBar = this.oWordApplic.CommandBars["Menu Bar"];
popuBar = (Microsoft.Office.Core.CommandBarPopup)this.oWordApplic.CommandBars.FindControl(Microsoft.Office.Core.MsoControlType.msoControlPopup, missing, popuBar.Tag, true);
if (popuBar == null)
{
popuBar = (Microsoft.Office.Core.CommandBarPopup)menuBar.Controls.Add(Microsoft.Office.Core.MsoControlType.msoControlPopup, missing, missing, missing, missing);
}
}
//添加单独工具栏
public void AddToolItem(string strBarName,string strBtnName)
{
Microsoft.Office.Core.CommandBar toolBar = null;
toolBar = (Microsoft.Office.Core.CommandBar)this.oWordApplic.CommandBars.FindControl(Microsoft.Office.Core.MsoControlType.msoControlButton, missing, strBarName, true);
if (toolBar == null)
{
toolBar = (Microsoft.Office.Core.CommandBar)this.oWordApplic.CommandBars.Add(
Microsoft.Office.Core.MsoControlType.msoControlButton,
missing, missing, missing);
toolBar.Name = strBtnName;
toolBar.Visible = true;
}
}
#endregion
#region 移动光标位置
// Go to a predefined bookmark, if the bookmark doesn't exists the application will raise an error
public void GotoBookMark(string strBookMarkName)
{
// VB : Selection.GoTo What:=wdGoToBookmark, Name:="nome"
object Bookmark = (int)Microsoft.Office.Interop.Word.WdGoToItem.wdGoToBookmark;
object NameBookMark = strBookMarkName;
oWordApplic.Selection.GoTo(ref Bookmark, ref missing, ref missing, ref NameBookMark);
}
public void GoToTheEnd()
{
// VB : Selection.EndKey Unit:=wdStory
object unit;
unit = Microsoft.Office.Interop.Word.WdUnits.wdStory;
oWordApplic.Selection.EndKey(ref unit, ref missing);
}
public void GoToLineEnd()
{
object unit = Microsoft.Office.Interop.Word.WdUnits.wdLine;
object ext = Microsoft.Office.Interop.Word.WdMovementType.wdExtend;
oWordApplic.Selection.EndKey(ref unit, ref ext);
}
public void GoToTheBeginning()
{
// VB : Selection.HomeKey Unit:=wdStory
object unit;
unit = Microsoft.Office.Interop.Word.WdUnits.wdStory;
oWordApplic.Selection.HomeKey(ref unit, ref missing);
}
public void GoToTheTable(int ntable)
{
object what;
what = Microsoft.Office.Interop.Word.WdUnits.wdTable;
object which;
which = Microsoft.Office.Interop.Word.WdGoToDirection.wdGoToFirst;
object count;
count = 1;
oWordApplic.Selection.GoTo(ref what, ref which, ref count, ref missing);
oWordApplic.Selection.Find.ClearFormatting();
oWordApplic.Selection.Text = "";
}
public void GoToRightCell()
{
// Selection.MoveRight Unit:=wdCell
object direction;
direction = Microsoft.Office.Interop.Word.WdUnits.wdCell;
oWordApplic.Selection.MoveRight(ref direction, ref missing, ref missing);
}
public void GoToLeftCell()
{
// Selection.MoveRight Unit:=wdCell
object direction;
direction = Microsoft.Office.Interop.Word.WdUnits.wdCell;
oWordApplic.Selection.MoveLeft(ref direction, ref missing, ref missing);
}
public void GoToDownCell()
{
// Selection.MoveRight Unit:=wdCell
object direction;
direction = Microsoft.Office.Interop.Word.WdUnits.wdLine;
oWordApplic.Selection.MoveDown(ref direction, ref missing, ref missing);
}
public void GoToUpCell()
{
// Selection.MoveRight Unit:=wdCell
object direction;
direction = Microsoft.Office.Interop.Word.WdUnits.wdLine;
oWordApplic.Selection.MoveUp(ref direction, ref missing, ref missing);
}
#endregion
#region 插入操作
public void InsertText(string strText)
{
oWordApplic.Selection.TypeText(strText);
}
public void InsertLineBreak()
{
oWordApplic.Selection.TypeParagraph();
}
/// <summary>
/// 插入多个空行
/// </summary>
/// <param name="nline"></param>
public void InsertLineBreak(int nline)
{
for (int i = 0; i < nline; i++)
oWordApplic.Selection.TypeParagraph();
}
public void InsertPagebreak()
{
// VB : Selection.InsertBreak Type:=wdPageBreak
object pBreak = (int)Microsoft.Office.Interop.Word.WdBreakType.wdPageBreak;
oWordApplic.Selection.InsertBreak(ref pBreak);
}
// 插入页码
public void InsertPageNumber()
{
object wdFieldPage = Microsoft.Office.Interop.Word.WdFieldType.wdFieldPage;
object preserveFormatting = true;
oWordApplic.Selection.Fields.Add(oWordApplic.Selection.Range, ref wdFieldPage, ref missing, ref preserveFormatting);
}
// 插入页码
public void InsertPageNumber(string strAlign)
{
object wdFieldPage = Microsoft.Office.Interop.Word.WdFieldType.wdFieldPage;
object preserveFormatting = true;
oWordApplic.Selection.Fields.Add(oWordApplic.Selection.Range, ref wdFieldPage, ref missing, ref preserveFormatting);
SetAlignment(strAlign);
}
public void InsertImage(string strPicPath, float picWidth, float picHeight)
{
string FileName = strPicPath;
object LinkToFile = false;
object SaveWithDocument = true;
object Anchor = oWordApplic.Selection.Range;
oWordApplic.ActiveDocument.InlineShapes.AddPicture(FileName, ref LinkToFile, ref SaveWithDocument, ref Anchor).Select();
oWordApplic.Selection.InlineShapes[1].Width = picWidth; // 图片宽度
oWordApplic.Selection.InlineShapes[1].Height = picHeight; // 图片高度
// 将图片设置为四面环绕型
Microsoft.Office.Interop.Word.Shape s = oWordApplic.Selection.InlineShapes[1].ConvertToShape();
s.WrapFormat.Type = Microsoft.Office.Interop.Word.WdWrapType.wdWrapInline;
}
public void InsertLine(float left, float top, float width, float weight, int r, int g, int b)
{
//SetFontColor("red");
//SetAlignment("Center");
object Anchor = oWordApplic.Selection.Range;
//int pLeft = 0, pTop = 0, pWidth = 0, pHeight = 0;
//oWordApplic.ActiveWindow.GetPoint(out pLeft, out pTop, out pWidth, out pHeight,missing);
//MessageBox.Show(pLeft + "," + pTop + "," + pWidth + "," + pHeight);
object rep = false;
//left += oWordApplic.ActiveDocument.PageSetup.LeftMargin;
left = oWordApplic.CentimetersToPoints(left);
top = oWordApplic.CentimetersToPoints(top);
width = oWordApplic.CentimetersToPoints(width);
Microsoft.Office.Interop.Word.Shape s = oWordApplic.ActiveDocument.Shapes.AddLine(0, top, width, top, ref Anchor);
s.Line.ForeColor.RGB = RGB(r, g, b);
s.Line.Visible = Microsoft.Office.Core.MsoTriState.msoTrue;
s.Line.Style = Microsoft.Office.Core.MsoLineStyle.msoLineSingle;
s.Line.Weight = weight;
}
/// <summary>
/// 添加页眉
/// </summary>
/// <param name="Content">页眉内容</param>
/// <param name="Alignment">对齐文式</param>
public void InsertHeader(string Content, string Alignment)
{
oWordApplic.ActiveWindow.View.Type = Microsoft.Office.Interop.Word.WdViewType.wdOutlineView;
oWordApplic.ActiveWindow.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekPrimaryHeader;
oWordApplic.ActiveWindow.ActivePane.Selection.InsertAfter(Content);
SetAlignment(Alignment);// 设置右对齐
oWordApplic.ActiveWindow.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekMainDocument;
}
/// <summary>
/// 添加页脚
/// </summary>
/// <param name="Content">页脚内容</param>
/// <param name="Alignment">对齐文式</param>
public void InsertFooter(string Content, string Alignment)
{
oWordApplic.ActiveWindow.View.Type = Microsoft.Office.Interop.Word.WdViewType.wdOutlineView;
oWordApplic.ActiveWindow.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekPrimaryFooter;
oWordApplic.ActiveWindow.ActivePane.Selection.InsertAfter(Content);
SetAlignment(Alignment);// 设置对齐
oWordApplic.ActiveWindow.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekMainDocument;
}
/// <summary>
/// 插入页码
/// </summary>
/// <param name="strformat">样式</param>
/// <param name="strAlign">格式</param>
public void InsertAllPageNumber(string strformat,string strAlign)
{
object IncludeFootnotesAndEndnotes = false;
int pageSum =oDoc.ComputeStatistics(Microsoft.Office.Interop.Word.WdStatistic.wdStatisticPages, ref IncludeFootnotesAndEndnotes);
GoToTheBeginning();
for (int i = 0; i < pageSum;i++ )
{
InsertPageNumber();
oDoc.Application.Browser.Next();//下一页
}
}
#endregion
#region 设置样式
/// <summary>
/// Change the paragraph alignement
/// </summary>
/// <param name="strType"></param>
public void SetAlignment(string strType)
{
switch (strType.ToLower())
{
case "center":
oWordApplic.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
break;
case "left":
oWordApplic.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft;
break;
case "right":
oWordApplic.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;
break;
case "justify":
oWordApplic.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphJustify;
break;
}
}
// if you use thif function to change the font you should call it again with
// no parameter in order to set the font without a particular format
public void SetFont(string strType)
{
switch (strType)
{
case "Bold":
oWordApplic.Selection.Font.Bold = 1;
break;
case "Italic":
oWordApplic.Selection.Font.Italic = 1;
break;
case "Underlined":
oWordApplic.Selection.Font.Subscript = 0;
break;
}
}
// disable all the style
public void SetFont()
{
oWordApplic.Selection.Font.Bold = 0;
oWordApplic.Selection.Font.Italic = 0;
oWordApplic.Selection.Font.Subscript = 0;
}
public void SetFontName(string strType)
{
oWordApplic.Selection.Font.Name = strType;
}
public void SetFontSize(float nSize)
{
SetFontSize(nSize, 100);
}
public void SetFontSize(float nSize, int scaling)
{
if (nSize > 0f)
oWordApplic.Selection.Font.Size = nSize;
if (scaling > 0)
oWordApplic.Selection.Font.Scaling = scaling;
}
public void SetFontColor(string strFontColor)
{
switch (strFontColor.ToLower())
{
case "blue":
oWordApplic.Selection.Font.Color = Microsoft.Office.Interop.Word.WdColor.wdColorBlue;
break;
case "gold":
oWordApplic.Selection.Font.Color = Microsoft.Office.Interop.Word.WdColor.wdColorGold;
break;
case "gray":
oWordApplic.Selection.Font.Color = Microsoft.Office.Interop.Word.WdColor.wdColorGray875;
break;
case "green":
oWordApplic.Selection.Font.Color = Microsoft.Office.Interop.Word.WdColor.wdColorGreen;
break;
case "lightblue":
oWordApplic.Selection.Font.Color = Microsoft.Office.Interop.Word.WdColor.wdColorLightBlue;
break;
case "orange":
oWordApplic.Selection.Font.Color = Microsoft.Office.Interop.Word.WdColor.wdColorOrange;
break;
case "pink":
oWordApplic.Selection.Font.Color = Microsoft.Office.Interop.Word.WdColor.wdColorPink;
break;
case "red":
oWordApplic.Selection.Font.Color = Microsoft.Office.Interop.Word.WdColor.wdColorRed;
break;
case "yellow":
oWordApplic.Selection.Font.Color = Microsoft.Office.Interop.Word.WdColor.wdColorYellow;
break;
}
}
public void SetPageNumberAlign(string strType, bool bHeader)
{
object alignment;
object bFirstPage = false;
object bF = true;
//if (bHeader == true)
//WordApplic.Selection.HeaderFooter.PageNumbers.ShowFirstPageNumber = bF;
switch (strType)
{
case "Center":
alignment = Microsoft.Office.Interop.Word.WdPageNumberAlignment.wdAlignPageNumberCenter;
//WordApplic.Selection.HeaderFooter.PageNumbers.Add(ref alignment,ref bFirstPage);
//Microsoft.Office.Interop.Word.Selection objSelection = WordApplic.pSelection;
oWordApplic.Selection.HeaderFooter.PageNumbers[1].Alignment = Microsoft.Office.Interop.Word.WdPageNumberAlignment.wdAlignPageNumberCenter;
break;
case "Right":
alignment = Microsoft.Office.Interop.Word.WdPageNumberAlignment.wdAlignPageNumberRight;
oWordApplic.Selection.HeaderFooter.PageNumbers[1].Alignment = Microsoft.Office.Interop.Word.WdPageNumberAlignment.wdAlignPageNumberRight;
break;
case "Left":
alignment = Microsoft.Office.Interop.Word.WdPageNumberAlignment.wdAlignPageNumberLeft;
oWordApplic.Selection.HeaderFooter.PageNumbers.Add(ref alignment, ref bFirstPage);
break;
}
}
/// <summary>
/// 设置页面为标准A4公文样式
/// </summary>
private void SetA4PageSetup()
{
oWordApplic.ActiveDocument.PageSetup.TopMargin = oWordApplic.CentimetersToPoints(3.7f);
//oWordApplic.ActiveDocument.PageSetup.BottomMargin = oWordApplic.CentimetersToPoints(1f);
oWordApplic.ActiveDocument.PageSetup.LeftMargin = oWordApplic.CentimetersToPoints(2.8f);
oWordApplic.ActiveDocument.PageSetup.RightMargin = oWordApplic.CentimetersToPoints(2.6f);
//oWordApplic.ActiveDocument.PageSetup.HeaderDistance = oWordApplic.CentimetersToPoints(2.5f);
//oWordApplic.ActiveDocument.PageSetup.FooterDistance = oWordApplic.CentimetersToPoints(1f);
oWordApplic.ActiveDocument.PageSetup.PageWidth = oWordApplic.CentimetersToPoints(21f);
oWordApplic.ActiveDocument.PageSetup.PageHeight = oWordApplic.CentimetersToPoints(29.7f);
}
#endregion
#region 替换
///<summary>
/// 在word 中查找一个字符串直接替换所需要的文本
/// </summary>
/// <param name="strOldText">原文本</param>
/// <param name="strNewText">新文本</param>
/// <returns></returns>
public bool Replace(string strOldText, string strNewText)
{
if (oDoc == null)
oDoc = oWordApplic.ActiveDocument;
this.oDoc.Content.Find.Text = strOldText;
object FindText, ReplaceWith, Replace;//
FindText = strOldText;//要查找的文本
ReplaceWith = strNewText;//替换文本
Replace = Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll;/**//*wdReplaceAll - 替换找到的所有项。
* wdReplaceNone - 不替换找到的任何项。
* wdReplaceOne - 替换找到的第一项。
* */
oDoc.Content.Find.ClearFormatting();//移除Find的搜索文本和段落格式设置
if (oDoc.Content.Find.Execute(
ref FindText, ref missing,
ref missing, ref missing,
ref missing, ref missing,
ref missing, ref missing, ref missing,
ref ReplaceWith, ref Replace,
ref missing, ref missing,
ref missing, ref missing))
{
return true;
}
return false;
}
public bool SearchReplace(string strOldText, string strNewText)
{
object replaceAll = Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll;
//首先清除任何现有的格式设置选项,然后设置搜索字符串 strOldText。
oWordApplic.Selection.Find.ClearFormatting();
oWordApplic.Selection.Find.Text = strOldText;
oWordApplic.Selection.Find.Replacement.ClearFormatting();
oWordApplic.Selection.Find.Replacement.Text = strNewText;
if (oWordApplic.Selection.Find.Execute(
ref missing, ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing, ref missing,
ref replaceAll, ref missing, ref missing, ref missing, ref missing))
{
return true;
}
return false;
}
#endregion
#region rgb转换函数
/// <summary>
/// rgb转换函数
/// </summary>
/// <param name="r"></param>
/// <param name="g"></param>
/// <param name="b"></param>
/// <returns></returns>
int RGB(int r, int g, int b)
{
return ((b << 16) | (ushort)(((ushort)g << 8) | r));
}
#endregion
#region RGBToColor
/// <summary>
/// RGBToColor
/// </summary>
/// <param name="color">颜色值</param>
/// <returns>Color</returns>
Color RGBToColor(int color)
{
int r = 0xFF & color;
int g = 0xFF00 & color;
g >>= 8;
int b = 0xFF0000 & color;
b >>= 16;
return Color.FromArgb(r, g, b);
}
#endregion
#region 读取相关
/// <summary>
/// 读取第i段内容
/// </summary>
/// <param name="i">段索引</param>
/// <returns>string</returns>
public string readParagraph(int i)
{
try
{
string temp = oDoc.Paragraphs[i].Range.Text.Trim();
return temp;
}
catch (Exception e) {
throw new Exception(e.Message);
}
}
/// <summary>
/// 获得总段数
/// </summary>
/// <returns>int</returns>
public int getParCount()
{
return oDoc.Paragraphs.Count;
}
#endregion
}
}
三、TXT文档操作类
这个就是一个.NET中的文件操作类:
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Data;
namespace BlogMoveLib
{
public class FileHelper : IDisposable
{
private bool _alreadyDispose = false;
#region 构造函数
public FileHelper()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
~FileHelper()
{
Dispose(); ;
}
protected virtual void Dispose(bool isDisposing)
{
if (_alreadyDispose) return;
_alreadyDispose = true;
}
#endregion
#region IDisposable 成员
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
#region 取得文件后缀名
/****************************************
* 函数名称:GetPostfixStr
* 功能说明:取得文件后缀名
* 参 数:filename:文件名称
* 调用示列:
* string filename = "aaa.aspx";
* string s = EC.FileObj.GetPostfixStr(filename);
*****************************************/
/// <summary>
/// 取后缀名
/// </summary>
/// <param name="filename">文件名</param>
/// <returns>.gif|.html格式</returns>
public static string GetPostfixStr(string filename)
{
int start = filename.LastIndexOf(".");
int length = filename.Length;
string postfix = filename.Substring(start, length - start);
return postfix;
}
#endregion
#region 写文件
/****************************************
* 函数名称:WriteFile
* 功能说明:写文件,会覆盖掉以前的内容
* 参 数:Path:文件路径,Strings:文本内容
* 调用示列:
* string Path = Server.MapPath("Default2.aspx");
* string Strings = "这是我写的内容啊";
* EC.FileObj.WriteFile(Path,Strings);
*****************************************/
/// <summary>
/// 写文件
/// </summary>
/// <param name="Path">文件路径</param>
/// <param name="Strings">文件内容</param>
public static void WriteFile(string Path, string Strings)
{
if (!System.IO.File.Exists(Path))
{
System.IO.FileStream f = System.IO.File.Create(Path);
f.Close();
}
System.IO.StreamWriter f2 = new System.IO.StreamWriter(Path, false, System.Text.Encoding.GetEncoding("gb2312"));
f2.Write(Strings);
f2.Close();
f2.Dispose();
}
/// <summary>
/// 写文件
/// </summary>
/// <param name="Path">文件路径</param>
/// <param name="Strings">文件内容</param>
/// <param name="encode">编码格式</param>
public static void WriteFile(string Path, string Strings,Encoding encode)
{
if (!System.IO.File.Exists(Path))
{
System.IO.FileStream f = System.IO.File.Create(Path);
f.Close();
}
System.IO.StreamWriter f2 = new System.IO.StreamWriter(Path, false,encode);
f2.Write(Strings);
f2.Close();
f2.Dispose();
}
#endregion
#region 读文件
/****************************************
* 函数名称:ReadFile
* 功能说明:读取文本内容
* 参 数:Path:文件路径
* 调用示列:
* string Path = Server.MapPath("Default2.aspx");
* string s = EC.FileObj.ReadFile(Path);
*****************************************/
/// <summary>
/// 读文件
/// </summary>
/// <param name="Path">文件路径</param>
/// <returns></returns>
public static string ReadFile(string Path)
{
string s = "";
if (!System.IO.File.Exists(Path))
s = "不存在相应的目录";
else
{
StreamReader f2 = new StreamReader(Path, System.Text.Encoding.GetEncoding("gb2312"));
s = f2.ReadToEnd();
f2.Close();
f2.Dispose();
}
return s;
}
/// <summary>
/// 读文件
/// </summary>
/// <param name="Path">文件路径</param>
/// <param name="encode">编码格式</param>
/// <returns></returns>
public static string ReadFile(string Path,Encoding encode)
{
string s = "";
if (!System.IO.File.Exists(Path))
s = "不存在相应的目录";
else
{
StreamReader f2 = new StreamReader(Path, encode);
s = f2.ReadToEnd();
f2.Close();
f2.Dispose();
}
return s;
}
#endregion
#region 追加文件
/****************************************
* 函数名称:FileAdd
* 功能说明:追加文件内容
* 参 数:Path:文件路径,strings:内容
* 调用示列:
* string Path = Server.MapPath("Default2.aspx");
* string Strings = "新追加内容";
* EC.FileObj.FileAdd(Path, Strings);
*****************************************/
/// <summary>
/// 追加文件
/// </summary>
/// <param name="Path">文件路径</param>
/// <param name="strings">内容</param>
public static void FileAdd(string Path, string strings)
{
StreamWriter sw = File.AppendText(Path);
sw.Write(strings);
sw.Flush();
sw.Close();
}
#endregion
#region 拷贝文件
/****************************************
* 函数名称:FileCoppy
* 功能说明:拷贝文件
* 参 数:OrignFile:原始文件,NewFile:新文件路径
* 调用示列:
* string orignFile = Server.MapPath("Default2.aspx");
* string NewFile = Server.MapPath("Default3.aspx");
* EC.FileObj.FileCoppy(OrignFile, NewFile);
*****************************************/
/// <summary>
/// 拷贝文件
/// </summary>
/// <param name="OrignFile">原始文件</param>
/// <param name="NewFile">新文件路径</param>
public static void FileCoppy(string orignFile, string NewFile)
{
File.Copy(orignFile, NewFile, true);
}
#endregion
#region 删除文件
/****************************************
* 函数名称:FileDel
* 功能说明:删除文件
* 参 数:Path:文件路径
* 调用示列:
* string Path = Server.MapPath("Default3.aspx");
* EC.FileObj.FileDel(Path);
*****************************************/
/// <summary>
/// 删除文件
/// </summary>
/// <param name="Path">路径</param>
public static void FileDel(string Path)
{
File.Delete(Path);
}
#endregion
#region 移动文件
/****************************************
* 函数名称:FileMove
* 功能说明:移动文件
* 参 数:OrignFile:原始路径,NewFile:新文件路径
* 调用示列:
* string orignFile = Server.MapPath("../说明.txt");
* string NewFile = Server.MapPath("http://www.cnblogs.com/说明.txt");
* EC.FileObj.FileMove(OrignFile, NewFile);
*****************************************/
/// <summary>
/// 移动文件
/// </summary>
/// <param name="OrignFile">原始路径</param>
/// <param name="NewFile">新路径</param>
public static void FileMove(string orignFile, string NewFile)
{
File.Move(orignFile, NewFile);
}
#endregion
#region 在当前目录下创建目录
/****************************************
* 函数名称:FolderCreate
* 功能说明:在当前目录下创建目录
* 参 数:OrignFolder:当前目录,NewFloder:新目录
* 调用示列:
* string orignFolder = Server.MapPath("test/");
* string NewFloder = "new";
* EC.FileObj.FolderCreate(OrignFolder, NewFloder);
*****************************************/
/// <summary>
/// 在当前目录下创建目录
/// </summary>
/// <param name="OrignFolder">当前目录</param>
/// <param name="NewFloder">新目录</param>
public static void FolderCreate(string orignFolder, string NewFloder)
{
Directory.SetCurrentDirectory(orignFolder);
Directory.CreateDirectory(NewFloder);
}
#endregion
#region 递归删除文件夹目录及文件
/****************************************
* 函数名称:DeleteFolder
* 功能说明:递归删除文件夹目录及文件
* 参 数:dir:文件夹路径
* 调用示列:
* string dir = Server.MapPath("test/");
* EC.FileObj.DeleteFolder(dir);
*****************************************/
/// <summary>
/// 递归删除文件夹目录及文件
/// </summary>
/// <param name="dir"></param>
/// <returns></returns>
public static void DeleteFolder(string dir)
{
if (Directory.Exists(dir)) //如果存在这个文件夹删除之
{
foreach (string d in Directory.GetFileSystemEntries(dir))
{
if (File.Exists(d))
File.Delete(d); //直接删除其中的文件
else
DeleteFolder(d); //递归删除子文件夹
}
Directory.Delete(dir); //删除已空文件夹
}
}
#endregion
#region 将指定文件夹下面的所有内容copy到目标文件夹下面 果目标文件夹为只读属性就会报错。
/****************************************
* 函数名称:CopyDir
* 功能说明:将指定文件夹下面的所有内容copy到目标文件夹下面 果目标文件夹为只读属性就会报错。
* 参 数:srcPath:原始路径,aimPath:目标文件夹
* 调用示列:
* string srcPath = Server.MapPath("test/");
* string aimPath = Server.MapPath("test1/");
* EC.FileObj.CopyDir(srcPath,aimPath);
*****************************************/
/// <summary>
/// 指定文件夹下面的所有内容copy到目标文件夹下面
/// </summary>
/// <param name="srcPath">原始路径</param>
/// <param name="aimPath">目标文件夹</param>
public static void CopyDir(string srcPath, string aimPath)
{
try
{
// 检查目标目录是否以目录分割字符结束如果不是则添加之
if (aimPath[aimPath.Length - 1] != Path.DirectorySeparatorChar)
aimPath += Path.DirectorySeparatorChar;
// 判断目标目录是否存在如果不存在则新建之
if (!Directory.Exists(aimPath))
Directory.CreateDirectory(aimPath);
// 得到源目录的文件列表,该里面是包含文件以及目录路径的一个数组
//如果你指向copy目标文件下面的文件而不包含目录请使用下面的方法
//string[] fileList = Directory.GetFiles(srcPath);
string[] fileList = Directory.GetFileSystemEntries(srcPath);
//遍历所有的文件和目录
foreach (string file in fileList)
{
//先当作目录处理如果存在这个目录就递归Copy该目录下面的文件
if (Directory.Exists(file))
CopyDir(file, aimPath + Path.GetFileName(file));
//否则直接Copy文件
else
File.Copy(file, aimPath + Path.GetFileName(file), true);
}
}
catch (Exception ee)
{
throw new Exception(ee.ToString());
}
}
#endregion
}
}
注:在用以上代码时请注意引用命名空间。
出处:http://www.cnblogs.com/durongjian
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。