C#操作Word文件

添加项目引用

using MSWord = Microsoft.Office.Interop.Word;
using Microsoft.Office.Interop.Word;

1.构建Word

//生成Word文件名
filename = @"D:\" + "Temp\\" + DateTime.Now.ToString("yyyyMMddHHmm") + ".docx";
object newfilename = filename;
FileStream file = File.Create(filename.ToString());//如果不存在就创建
file.Close();

#region 开始构建Word
try
{
Object oMissing = System.Reflection.Missing.Value;
MSWord.Application WordApp = new MSWord.Application();
MSWord.Document WordDoc = WordApp.Documents.Open(ref newfilename, 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);

//获取摘要,要目
mcfile = GetFilesInfo.GetPublicOpinion(loginKey, serverip);//自己封装的方法 获取数据库信息
//移动焦点并换行
object count1 = 1;
object wdCharacter = MSWord.WdUnits.wdCharacter;
object WdLine1 = Microsoft.Office.Interop.Word.WdUnits.wdLine;//换一行;
WordApp.Selection.MoveDown(ref WdLine1, ref count1, ref oMissing);//移动焦点
//插入表格
MSWord.Table newTable = WordDoc.Tables.Add(WordApp.Selection.Range, 2, 2, ref oMissing, ref oMissing);
//表格border样式
newTable.Borders.OutsideLineStyle = MSWord.WdLineStyle.wdLineStyleNone;//设置表格无外边框
newTable.Cell(2, 2).Borders.OutsideLineStyle = MSWord.WdLineStyle.wdLineStyleSingle;//设置表格第二行第二列有边框
newTable.Cell(2, 2).Borders.OutsideLineWidth = MSWord.WdLineWidth.wdLineWidth150pt;//边框样式

//合并单元格
newTable.Cell(1, 1).Merge(newTable.Cell(1, 2));
WordApp.Selection.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphRight;
object count11 = 6;
WordApp.Selection.MoveLeft(ref wdCharacter, ref count11, ref oMissing);//左移
WordApp.Selection.Range.Text = "";
WordApp.Selection.MoveDown(ref WdLine1, ref count1, ref oMissing);//下移

WordApp.Selection.Font.Size = 16;
WordApp.Selection.Font.Bold = 2;
WordApp.Selection.Font.Name = "黑体";
WordApp.Selection.Paragraphs.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphCenter;
WordApp.Selection.TypeText("要 目");
WordApp.Selection.TypeParagraph();//插入段落

WordApp.Selection.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphLeft;
WordApp.Selection.Font.Name = "楷体_GB2312";
WordApp.Selection.Font.Size = 16;
WordApp.Selection.Font.Bold = 0;
//项目编号
object i = 1;
object a = MSWord.WdListApplyTo.wdListApplyToWholeList;
object listFormat = MSWord.WdDefaultListBehavior.wdWord10ListBehavior;
MSWord.ListTemplate listTemp = WordApp.ListGalleries[MSWord.WdListGalleryType.wdBulletGallery].ListTemplates.get_Item(ref i);
object bContinuousPrev = true;//是否为大圆点 true 大圆点
object bContinuousPrev1 = false;
object wdNumberParagraph = MSWord.WdNumberType.wdNumberParagraph;
#region 段落格式设定
WordApp.Selection.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphJustify;
WordApp.Selection.ParagraphFormat.LeftIndent = WordApp.CentimetersToPoints(float.Parse("0.05"));//左缩进
WordApp.Selection.ParagraphFormat.RightIndent = WordApp.CentimetersToPoints(float.Parse("0"));//右缩进
WordApp.Selection.ParagraphFormat.SpaceBefore = float.Parse("0");//段前间距
WordApp.Selection.ParagraphFormat.SpaceBeforeAuto = 0;//
WordApp.Selection.ParagraphFormat.SpaceAfter = float.Parse("0");//段后间距
WordApp.Selection.ParagraphFormat.SpaceAfterAuto = 0;//
WordApp.Selection.ParagraphFormat.LineSpacingRule = Microsoft.Office.Interop.Word.WdLineSpacing.wdLineSpaceExactly;//单倍行距
WordApp.Selection.ParagraphFormat.LineSpacing = float.Parse("23");
WordApp.Selection.ParagraphFormat.OutlineLevel = MSWord.WdOutlineLevel.wdOutlineLevelBodyText;
WordApp.Selection.ParagraphFormat.CharacterUnitLeftIndent = float.Parse("0.28");
WordApp.Selection.ParagraphFormat.CharacterUnitRightIndent = float.Parse("0");
WordApp.Selection.ParagraphFormat.CharacterUnitFirstLineIndent = float.Parse("-0.63");
WordApp.Selection.ParagraphFormat.LineUnitBefore = float.Parse("0");
WordApp.Selection.ParagraphFormat.LineUnitAfter = float.Parse("0");
WordApp.Selection.ParagraphFormat.BaseLineAlignment = MSWord.WdBaselineAlignment.wdBaselineAlignAuto;
#endregion
mcfile = GetFilesInfo.GetPublicOpinion(loginKey, serverip);//获取数据库信息
foreach (var m in mcfile)
{
WordApp.Selection.Range.ListFormat.ApplyListTemplate(listTemp, ref bContinuousPrev1, ref a, ref listFormat);//添加项目编号
WordApp.Selection.Range.ListFormat.ListTemplate.ListLevels[1].Font.Name = "Wingdings 2";
WordApp.Selection.Range.ListFormat.ListTemplate.ListLevels[1].NumberFormat = char.ConvertFromUtf32(61590);//设置项目编号为数字编号

WordApp.Selection.TypeText(m.subtitle);
WordApp.Selection.TypeParagraph();
}
WordApp.Selection.Range.ListFormat.RemoveNumbers(ref wdNumberParagraph);//移除项目编号

object count3 = 5;
WordApp.Selection.MoveDown(ref WdLine1, ref oMissing, ref oMissing);
WordApp.Selection.MoveDown(ref WdLine1, ref count3, ref oMissing);//换一行
WordApp.Selection.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphLeft;
WordApp.Selection.Font.Size = 21;
WordApp.Selection.Font.Name = "楷体_GB2312";
WordApp.Selection.Font.Bold = 2;
WordApp.Selection.TypeText("领导批示:");

WordApp.Selection.TypeParagraph();
WordApp.Selection.TypeParagraph();
WordApp.Selection.TypeParagraph();

MSWord.Paragraph par = WordDoc.Content.Paragraphs.Add(ref oMissing);
par.Range.InsertParagraphAfter();

WordApp.Selection.Font.Size = 15;
WordApp.Selection.Font.Name = "黑体";
WordApp.Selection.TypeText(" 关键词:");
WordApp.Selection.Font.Name = "楷体_GB2312";
WordApp.Selection.Font.Bold = 0;

//获取关键词
mcfile = GetFilesInfo.GetSubhead(loginKey, serverip);
if (mcfile.Count > 0)
{
foreach (var m in mcfile)
{
WordApp.Selection.TypeText(" " + m.subhead);
}
}
par.Range.InsertParagraphAfter();
WordApp.Selection.TypeParagraph();
WordApp.Selection.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphLeft;
//获取栏目名称,稿件名称,正文
List<Node> nodes = GetFilesInfo.GetNodeAll(loginKey, serverip);
foreach (var n in nodes)
{
mcfile = GetFilesInfo.GetMcfileByNodename(loginKey, serverip, n.Name);
mcfile2 = GetFilesInfo.GetMicroPick(loginKey, serverip);
if (mcfile.Count > 0)
{
WordApp.Selection.Font.Name = "黑体";
WordApp.Selection.Font.Size = 16;
WordApp.Selection.Font.Bold = 2;
WordApp.Selection.TypeText(n.Name);
WordApp.Selection.Range.ListFormat.ApplyListTemplate(listTemp, ref bContinuousPrev, ref a, ref listFormat);
WordApp.Selection.Range.ListFormat.ListTemplate.ListLevels[1].Font.Name = "Wingdings";
WordApp.Selection.TypeParagraph();

foreach (var mc in mcfile)
{
WordApp.Selection.Range.ListFormat.RemoveNumbers(ref wdNumberParagraph);
WordApp.Selection.Font.Size = 16;
WordApp.Selection.Font.Bold = 2;
WordApp.Selection.Font.Name = "楷体_GB2312";
WordApp.Selection.TypeText(" " + mc.name + " ");

WordApp.Selection.Font.Size = 16;
WordApp.Selection.Font.Bold = 0;
WordApp.Selection.Font.Name = "宋体 ";
var text = DelHTML(mc.content);
WordApp.Selection.TypeText(DelHTML(mc.content));

if (mc.Yanpan.Trim() != "")
{
WordApp.Selection.Font.Name = "楷体_GB2312 ";
WordApp.Selection.TypeText("研判认为:" + DelHTML(mc.Yanpan));
}
WordApp.Selection.TypeParagraph();
}
}
if (mcfile2.Count > 0 && n.Name.Equals("微博选摘"))
{
WordApp.Selection.Font.Name = "黑体";
WordApp.Selection.Font.Size = 16;
WordApp.Selection.Font.Bold = 2;
WordApp.Selection.TypeText(n.Name);
WordApp.Selection.Range.ListFormat.ApplyListTemplate(listTemp, ref bContinuousPrev, ref a, ref listFormat);
WordApp.Selection.Range.ListFormat.ListTemplate.ListLevels[1].Font.Name = "Wingdings";
WordApp.Selection.TypeParagraph();

foreach (var mc in mcfile2)
{
WordApp.Selection.Range.ListFormat.RemoveNumbers(ref wdNumberParagraph);
WordApp.Selection.Font.Size = 16;
WordApp.Selection.Font.Bold = 2;
WordApp.Selection.Font.Name = "楷体_GB2312";
WordApp.Selection.TypeText(" @" + mc.Sponsor + ": ");

WordApp.Selection.Font.Size = 16;
WordApp.Selection.Font.Bold = 0;
WordApp.Selection.Font.Name = "宋体 ";
var text = DelHTML(mc.content);
WordApp.Selection.TypeText(DelHTML(mc.content));
if (mc.Yanpan.Trim() != "")
{
WordApp.Selection.Font.Name = "楷体_GB2312 ";
WordApp.Selection.TypeText("研判认为:" + DelHTML(mc.Yanpan));
}
WordApp.Selection.TypeParagraph();
}
}
}
#region 涉沪微博排行
listMicroblog = GetFilesInfo.GetMicroblog(loginKey, serverip);//获取微博排行
object story = MSWord.WdUnits.wdStory;
if (listMicroblog.Count > 0)
{
WordApp.Selection.EndKey(ref story, ref oMissing);
WordApp.Selection.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphCenter;
WordApp.Selection.Font.Size = 14;
WordApp.Selection.Font.Bold = 2;
WordApp.Selection.Font.Name = "黑体";
WordApp.Selection.TypeText("涉沪微博排行");
WordApp.Selection.TypeParagraph();//插入段落

WordApp.Selection.Font.Name = "宋体 ";
WordApp.Selection.Font.Size = 12;
WordApp.Selection.Font.Bold = 0;
Microsoft.Office.Interop.Word.Table bottomTable = WordDoc.Tables.Add(WordApp.Selection.Range, 4, 4, ref oMissing, ref oMissing);
//设置表格样式
bottomTable.Borders.OutsideLineStyle = MSWord.WdLineStyle.wdLineStyleSingle;
bottomTable.Borders.InsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;

bottomTable.Columns[1].Width = 50;
bottomTable.Columns[2].Width = 265;
bottomTable.Columns[3].Width = 55;
bottomTable.Columns[4].Width = 50;
//插入数据
bottomTable.Cell(1, 1).Range.Text = "排名";
bottomTable.Cell(1, 1).Range.Bold = 2;
bottomTable.Cell(1, 2).Range.Text = "标题";
bottomTable.Cell(1, 2).Range.Bold = 2;
bottomTable.Cell(1, 3).Range.Text = "转发数";
bottomTable.Cell(1, 3).Range.Bold = 2;
bottomTable.Cell(1, 4).Range.Text = "评论数";
bottomTable.Cell(1, 4).Range.Bold = 2;

WordApp.Selection.Font.Name = "Times New Roman ";
bottomTable.Cell(2, 1).Range.Text = "1";
bottomTable.Cell(3, 1).Range.Text = "2";
bottomTable.Cell(4, 1).Range.Text = "3";

WordApp.Selection.Font.Name = "宋体 ";
foreach (var mi in listMicroblog)
{
bottomTable.Cell(2, 2).Range.Text = mi.userprop1;
bottomTable.Cell(2, 2).Range.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphLeft;
bottomTable.Cell(2, 3).Range.Text = mi.userprop2;
bottomTable.Cell(2, 3).Range.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphCenter;
bottomTable.Cell(2, 4).Range.Text = mi.userprop3;
bottomTable.Cell(2, 4).Range.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphCenter;

bottomTable.Cell(3, 2).Range.Text = mi.userprop4;
bottomTable.Cell(3, 2).Range.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphLeft;
bottomTable.Cell(3, 3).Range.Text = mi.userprop5;
bottomTable.Cell(3, 3).Range.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphCenter;
bottomTable.Cell(3, 4).Range.Text = mi.userprop7;
bottomTable.Cell(3, 4).Range.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphCenter;

bottomTable.Cell(4, 2).Range.Text = mi.userprop10;
bottomTable.Cell(4, 2).Range.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphLeft;
bottomTable.Cell(4, 3).Range.Text = mi.userprop6;
bottomTable.Cell(4, 3).Range.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphCenter;
bottomTable.Cell(4, 4).Range.Text = mi.userprop8;
bottomTable.Cell(4, 4).Range.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphCenter;
}
WordApp.Selection.EndKey(ref story, ref oMissing);
WordApp.Selection.Range.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphJustify;
WordApp.Selection.Font.Name = "仿宋_GB2312";
WordApp.Selection.TypeText("(本排行根据市网信办Weibook系统推荐的涉沪热点微博汇总而成,截至时间:");
WordApp.Selection.Font.Name = "Times New Roman";//仿宋_GB2312
WordApp.Selection.TypeText(expirtime + " 22:00");
WordApp.Selection.Font.Name = "仿宋_GB2312";//仿宋_GB2312
WordApp.Selection.TypeText(")");
WordApp.Selection.TypeParagraph();//插入段落
}
#endregion

WordDoc.SaveAs(ref newfilename, 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);
//关闭WordDoc文档对象 
WordDoc.Close(ref oMissing, ref oMissing, ref oMissing);

NAR(WordDoc);
//关闭WordApp组件对象 
WordApp.Quit(ref oMissing, ref oMissing, ref oMissing);
//添加到稿件的相关附件

NAR(WordApp);

#endregion

}

 

2.读取Word内容

/// <summary>
/// 读取word中的内容
/// </summary>
/// <param name="filename"></param>
/// <returns></returns>
public static string GetWordContent(string sourcePath)
{

MSWord.ApplicationClass wordapp = null;
MSWord.Document worddoc = null;
object fileobj = sourcePath;
object nullobj = System.Reflection.Missing.Value;
object Readonly = true;
object noSaveChange = false;
string doc = "";
try
{
wordapp = new MSWord.ApplicationClass();
worddoc = wordapp.Documents.Open(ref fileobj, ref nullobj, ref Readonly, ref nullobj,
ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj,
ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj);
doc = worddoc.Content.Text;
doc.Replace("/a", ""); //替换空串为空。(word中/a代表空串,但在C#中,代表响铃 晕~~)否则显示控制台程序时会响
doc.Replace("/r", "/n"); //替换回车为回车换行
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (worddoc != null)
{
try
{
worddoc.Close(ref nullobj, ref nullobj, ref nullobj);
NAR(worddoc);
}
catch
{ }

}
if (wordapp != null)
{
try
{
wordapp.Quit(ref noSaveChange, ref nullobj, ref nullobj);
NAR(wordapp);
}
catch
{
}

}
System.Runtime.InteropServices.Marshal.ReleaseComObject(wordapp);
System.Runtime.InteropServices.Marshal.ReleaseComObject(worddoc);
worddoc = null;
wordapp = null;

GC.Collect();
GC.WaitForPendingFinalizers();
}
return doc;

}

catch (Exception ex)
{
LogHelper.WriteLog(ex.Message);
}

posted @ 2013-07-31 12:26  $我们都是好孩子$  阅读(1719)  评论(2编辑  收藏  举报