C# /windowForm/WPF/SilverLight里面操作Word帮助类提供给大家

很多的程序都需要用到对word的操作,数据库里面的表需要一书面的形式展示出来,
最近在的一个项

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Drawing;
using Word = Microsoft.Office.Interop.Word;
using Microsoft.Office.Interop.Word;
using System.Windows.Forms;
namespace jiankong
{
public class WorldToos
{
#region - 属性 -
private Microsoft.Office.Interop.Word._Application oWord = null;
private Microsoft.Office.Interop.Word._Document odoc = null;
private Microsoft.Office.Interop.Word._Document oDoc
{
get
{
if (odoc == null)
{
odoc = oWord.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing);
}
return odoc;
}
set
{
if (value != null)
{
odoc = value;
}
}
}
private object Nothing = System.Reflection.Missing.Value;
public enum Orientation { 横板, 竖板 }
public enum Alignment { 左对齐, 居中, 右对齐 }
#endregion
#region - 添加文档 -
#region - 创建并打开一个空的word文档进行编辑 -
public void OpenNewWordFileToEdit()
{
oDoc = oWord.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing);
}
#endregion
#endregion
#region - 创建新Word -
public bool CreateWord(bool isVisible)
{
try
{
oWord = new Microsoft.Office.Interop.Word.Application();
oWord.Visible = isVisible;
return true;
}
catch (Exception)
{
return false;
}
}
public bool CreateWord()
{
return CreateWord(false);
}
#endregion
#region - 打开文档 -
public bool Open(string filePath, bool isVisible)
{
try
{
oWord.Visible = isVisible;
object path = filePath;
oDoc = oWord.Documents.Open(ref path,
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);
return true;
}
catch (Exception)
{
return false;
}
}
#endregion
#region - 插入表格 -
public bool InsertTable(DataTable dt, bool haveBorder, double[] colWidths)
{
try
{
object Nothing = System.Reflection.Missing.Value;
int lenght = oDoc.Characters.Count - 1;
object start = lenght;
object end = lenght;
//表格起始坐标
Microsoft.Office.Interop.Word.Range tableLocation = oDoc.Range(ref start, ref end);
//添加Word表格
Microsoft.Office.Interop.Word.Table table = oDoc.Tables.Add(tableLocation, dt.Rows.Count,
dt.Columns.Count, ref Nothing, ref Nothing);
if (colWidths != null)
{
for (int i = 0; i < colWidths.Length; i++)
{
table.Columns[i + 1].Width = (float)(28.5F * colWidths[i]);
}
}
///设置TABLE的样式
table.Rows.HeightRule = Microsoft.Office.Interop.Word.WdRowHeightRule.wdRowHeightAtLeast;

table.Rows.Height = oWord.CentimetersToPoints(float.Parse("0.8"));
table.Range.Font.Size = 10.5F;
table.Range.Font.Name = "宋体";
table.Range.Font.Bold = 0;
table.Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
table.Range.Cells.VerticalAlignment = Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
if (haveBorder == true)
{
//设置外框样式
table.Borders.OutsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;
table.Borders.InsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;
//样式设置结束
}
for (int row = 0; row < dt.Rows.Count; row++)
{
for (int col = 0; col < dt.Columns.Count; col++)
{
table.Cell(row + 1, col + 1).Range.Text = dt.Rows[row][col].ToString();
}
}
return true;
}
catch (Exception e)
{
MessageBox.Show(e.ToString(), "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
finally
{
}
}
public bool InsertTable(DataTable dt, bool haveBorder)
{
return InsertTable(dt, haveBorder, null);
}
public bool InsertTable(DataTable dt)
{ return InsertTable(dt, false, null); }
#endregion
#region - 插入文本 -
public bool InsertText(string strText, System.Drawing.Font font, Alignment alignment, bool isAftre)
{
try
{
Word.Range rng = oDoc.Content;
int lenght = oDoc.Characters.Count - 1;
object start = lenght;
object end = lenght;
rng = oDoc.Range(ref start, ref end);
if (isAftre == true)
{
strText += "\r\n";
} rng.Text = strText;
rng.Font.Name = font.Name;
rng.Font.Size = font.Size;
if (font.Style == FontStyle.Bold) { rng.Font.Bold = 1; }
//设置单元格中字体为粗体
SetAlignment(rng, alignment);
return true;
}
catch (Exception)
{
return false;
}
}
public bool InsertText(string strText)
{
return InsertText(strText, new System.Drawing.Font("宋体", 10.5F, FontStyle.Bold), Alignment.左对齐, false);
}
#endregion
#region - 设置对齐方式 -
private Microsoft.Office.Interop.Word.WdParagraphAlignment SetAlignment(Range rng, Alignment alignment)
{
rng.ParagraphFormat.Alignment = SetAlignment(alignment);
return SetAlignment(alignment);
}
private Microsoft.Office.Interop.Word.WdParagraphAlignment SetAlignment(Alignment alignment)
{
if (alignment == Alignment.居中)
{
return Word.WdParagraphAlignment.wdAlignParagraphCenter;
}
else if (alignment == Alignment.左对齐)
{
return Word.WdParagraphAlignment.wdAlignParagraphLeft;
}
else
{ return Word.WdParagraphAlignment.wdAlignParagraphRight; }
}
#endregion
#region - 页面设置 -
public void SetPage(Orientation orientation, double width, double height, double topMargin, double leftMargin, double rightMargin, double bottomMargin)
{
oDoc.PageSetup.PageWidth = oWord.CentimetersToPoints((float)width);
oDoc.PageSetup.PageHeight = oWord.CentimetersToPoints((float)height);
if (orientation == Orientation.横板)
{
oDoc.PageSetup.Orientation = Microsoft.Office.Interop.Word.WdOrientation.wdOrientLandscape;
} oDoc.PageSetup.TopMargin = (float)(topMargin * 25);//上边距
oDoc.PageSetup.LeftMargin = (float)(leftMargin * 25);//左边距
oDoc.PageSetup.RightMargin = (float)(rightMargin * 25);//右边距
oDoc.PageSetup.BottomMargin = (float)(bottomMargin * 25);//下边距
}
public void SetPage(Orientation orientation, double topMargin, double leftMargin, double rightMargin, double bottomMargin)
{
SetPage(orientation, 21, 29.7, topMargin, leftMargin, rightMargin, bottomMargin);
}
public void SetPage(double topMargin, double leftMargin, double rightMargin, double bottomMargin)
{
SetPage(Orientation.竖板, 21, 29.7, topMargin, leftMargin, rightMargin, bottomMargin);
}
#endregion
#region - 插入分页符 -
public void InsertBreak()
{
Word.Paragraph para; para = oDoc.Content.Paragraphs.Add(ref Nothing);
object pBreak = (int)WdBreakType.wdSectionBreakNextPage; para.Range.InsertBreak(ref pBreak);
}
#endregion
#region - 关闭当前文档 -
public bool CloseDocument()
{
try
{
object doNotSaveChanges = Word.WdSaveOptions.wdDoNotSaveChanges;
oDoc.Close(ref doNotSaveChanges, ref Nothing, ref Nothing);
oDoc = null;
return true;
}
catch (Exception)
{
return false;
}
}
#endregion
#region - 关闭程序 -
public bool Quit()
{
try
{
object saveOption = Word.WdSaveOptions.wdDoNotSaveChanges;
oWord.Quit(ref saveOption, ref Nothing, ref Nothing);
return true;
}
catch (Exception)
{
return false;
}
}
#endregion
#region - 保存文档 -
public bool Save(string savePath)
{
return Save(savePath, false);
}
public bool Save(string savePath, bool isClose)
{
try
{
object fileName = savePath;
oDoc.SaveAs(ref fileName, ref Nothing, ref Nothing,
ref Nothing, ref Nothing, ref Nothing, ref Nothing,
ref Nothing, ref Nothing, ref Nothing, ref Nothing,
ref Nothing, ref Nothing, ref Nothing, ref Nothing,
ref Nothing);
if (isClose)
{
return CloseDocument();
}
return true;
}
catch (Exception)
{
return false;
}
}
#endregion
#region - 插入页脚 -
public bool InsertPageFooter(string text, System.Drawing.Font font, WorldToos.Alignment alignment)
{
try
{
oWord.ActiveWindow.View.SeekView = Word.WdSeekView.wdSeekCurrentPageFooter;//页脚
oWord.Selection.InsertAfter(text);
GetWordFont(oWord.Selection.Font, font);
SetAlignment(oWord.Selection.Range, alignment);
return true;
}
catch (Exception)
{
return false;
}
}
public bool InsertPageFooterNumber(System.Drawing.Font font, WorldToos.Alignment alignment)
{
try
{
oWord.ActiveWindow.View.SeekView = WdSeekView.wdSeekCurrentPageHeader;
oWord.Selection.WholeStory();
oWord.Selection.ParagraphFormat.Borders[WdBorderType.wdBorderBottom].LineStyle = WdLineStyle.wdLineStyleNone;
oWord.ActiveWindow.View.SeekView = Word.WdSeekView.wdSeekMainDocument;
oWord.ActiveWindow.View.SeekView = Word.WdSeekView.wdSeekCurrentPageFooter;//页脚
oWord.Selection.TypeText("第");
object page = WdFieldType.wdFieldPage;
oWord.Selection.Fields.Add(oWord.Selection.Range, ref page, ref Nothing, ref Nothing);
oWord.Selection.TypeText("页/共");
object pages = WdFieldType.wdFieldNumPages;
oWord.Selection.Fields.Add(oWord.Selection.Range, ref pages, ref Nothing, ref Nothing);
oWord.Selection.TypeText("页"); GetWordFont(oWord.Selection.Font, font);
SetAlignment(oWord.Selection.Range, alignment);
oWord.ActiveWindow.View.SeekView = Word.WdSeekView.wdSeekMainDocument;
return true;
}
catch (Exception)
{
return false;
}
}
#endregion
#region - 字体格式设定 -
public void GetWordFont(Microsoft.Office.Interop.Word.Font wordFont, System.Drawing.Font font)
{
wordFont.Name = font.Name;
wordFont.Size = font.Size;
if (font.Bold) { wordFont.Bold = 1; }
if (font.Italic) { wordFont.Italic = 1; }
if (font.Underline == true)
{
wordFont.Underline = Microsoft.Office.Interop.Word.WdUnderline.wdUnderlineNone;
}
wordFont.UnderlineColor = Microsoft.Office.Interop.Word.WdColor.wdColorAutomatic;
if (font.Strikeout)
{
wordFont.StrikeThrough = 1;//删除线
}
}
#endregion
#region - 获取Word中的颜色 -
public WdColor GetWordColor(Color c)
{
UInt32 R = 0x1, G = 0x100, B = 0x10000;
return (Microsoft.Office.Interop.Word.WdColor)(R * c.R + G * c.G + B * c.B);
}
#endregion
XAML 文件:
<Window x:Class="jiankong.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="450" Width="517" >
<Canvas Name="LayOut">
<Canvas Height="311" Width="503">
<Canvas.Background>
<ImageBrush ImageSource="/jiankong;component/Images/dd2.png" Stretch="Fill"/>
</Canvas.Background>
<Ellipse Width="50" Height="50" Stroke="Red" Canvas.Left="143" Canvas.Top="89">
</Ellipse>
<Image Panel.ZIndex="40" Width="40" Source="/jiankong;component/Images/dd.png" Canvas.Left="146" Canvas.Top="91" />
<Label Canvas.Left="6" Canvas.Top="270" Content="表盘读书:" Height="35" Name="label1" FontSize="16" Width="72" />
<TextBox Canvas.Left="84" Canvas.Top="272" Height="33" Name="ge" Width="31" Text="5" Background="Black" Foreground="Wheat" FontSize="20" />
<TextBlock Canvas.Left="121" Canvas.Top="273" Height="23" Name="textBlock1" Text="X1" />
<TextBox Canvas.Left="143" Canvas.Top="270" Height="35" Name="shi" Width="29" Text="8" Background="#FFEE4646" Foreground="GhostWhite" FontSize="20" />
<TextBlock Canvas.Left="170" Canvas.Top="272" Height="23" Name="textBlock2" Text="X10" />
<TextBox Canvas.Left="198" Canvas.Top="269" Height="36" Name="bai" Width="35" Text="0" Background="#FFCE3D3D" Foreground="#FFEEDFDF" FontSize="18" />
<TextBlock Canvas.Left="239" Canvas.Top="273" Height="23" Name="textBlock3" Text="X100" />
<TextBox Canvas.Left="274" Canvas.Top="272" Height="33" Name="qian" Width="35" Text="5" Foreground="#FFEED5D5" Background="#FFEE2222" FontSize="22" />
<TextBlock Canvas.Left="315" Canvas.Top="272" Height="23" Name="textBlock4" Text="X1000" />

</Canvas>
<Canvas Background="Silver">
<Label Canvas.Left="1" Canvas.Top="317" Content="水表编号:XX" Height="28" Name="label2" />
<Label Canvas.Left="84" Canvas.Top="317" Content="业主姓名: 张XXX" Height="28" Name="label3" />
<Label Canvas.Left="216" Canvas.Top="317" Content="上次抄表时间: 2012-07-25" Height="28" Name="label4" />
<Label Canvas.Left="6" Canvas.Top="349" Content="读数:" Height="28" Name="label5" />
<TextBox Canvas.Left="153" Canvas.Top="351" IsReadOnly="True" Height="23" Name="Span" Width="39" Text="10" />
<Label Canvas.Left="84" Canvas.Top="351" Content="现水费计价:" Height="28" />
<Label Canvas.Left="198" Canvas.Top="351" Content="元/吨" Height="28" Name="label6" />
<Label Canvas.Left="255" Canvas.Top="351" Content="当前表值:" Height="28" Name="label7" />
<Label Canvas.Left="331" Canvas.Top="351" Content="Label" Height="28" Name="lblCurrent" Width="55" />
<Button Canvas.Left="400" Canvas.Top="318" Content="抄表" Height="23" Name="button1" Width="75" />
<Label Canvas.Left="38" Canvas.Top="349" Content="3" Height="28" Name="Last" Width="28" />
</Canvas>
<Label Canvas.Left="6" Canvas.Top="383" Content="水费:" Height="28" Name="lblshu" Visibility="Hidden" />
<Label Canvas.Left="49" Canvas.Top="383" Content="Label" Height="28" Name="spanToltal" Visibility="Hidden" />
<Label Canvas.Left="132" Canvas.Top="383" Content="查表人:" Height="28" Name="lblchabiao" Visibility="Hidden" />
<TextBox Canvas.Left="198" Canvas.Top="385" Height="23" Name="txtPenname" Width="70" Text="王小虎" Visibility="Hidden" />
<Button Canvas.Left="400" Canvas.Top="349" Content="打单" Height="23" Name="button2" Width="75" Click="button2_Click" />
</Canvas>
</Window>
后台cs 文件
[只是个测试Dome]
private void button2_Click(object sender, RoutedEventArgs e)
{
string biaoNumber = label2.Content.ToString();//水表编号
string penName = label3.Content.ToString();//业主姓名
string lastDate = label4.Content.ToString();//上次抄表时间
string begNUmber = Last.Content.ToString();//开始数
string spanNow = this.Span.Text.ToString();//单位价格
string endNumber = this.lblCurrent.Content.ToString();//当前读书
string shuiMoney = this.spanToltal.Content.ToString();//应缴水费
string chkPenser = txtPenname.Text.ToString();//查表人
string dTime = DateTime.Now.Year.ToString() + "年 " + DateTime.Now.Month.ToString() + "月" + "水费缴费单";

WorldToos WordPlayer = new WorldToos();
if (WordPlayer.CreateWord() == false)
{
System.Windows.Forms. MessageBox.Show("文件创造失败.", "错误提示", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
return;
}
DataTable storedt = new DataTable();
storedt.Columns.Add("第一列");
storedt.Columns.Add("第二列");
storedt.Columns.Add("第三列");
storedt.Columns.Add("第四列");
storedt.Rows.Add("水表起始数:", begNUmber, "水表结束数:", endNumber);

storedt.Rows.Add("本月用水", yongshui.ToString() + "立方米", "当前计价单位:", spanNow+"立方米/元");
storedt.Rows.Add("本月应收费:", shuiMoney, "查表员:", chkPenser);
storedt.Rows.Add("收费人", "王大用", "付款人签字:", "");
WordPlayer.SetPage(WorldToos.Orientation.横板, 18.4, 26, 3, 2.4, 1.87, 2.1);
WordPlayer.InsertText(dTime, new Font("微软雅黑", 14, System.Drawing.FontStyle.Bold),
jiankong.WorldToos.Alignment.居中, true);
WordPlayer.InsertText(biaoNumber, new Font("微软雅黑", 14, System.Drawing.FontStyle.Bold),
jiankong.WorldToos.Alignment.居中, true);
WordPlayer.InsertText( penName + " ",
new Font("宋体", 12, System.Drawing.FontStyle.Regular),
jiankong.WorldToos.Alignment.左对齐, false);
WordPlayer.InsertTable(storedt, true);
WordPlayer.InsertText("查表时间:" + DateTime.Now.ToString(), new Font("宋体", 14, System.Drawing.FontStyle.Regular), jiankong.WorldToos.Alignment.右对齐, false);
WordPlayer.Save(@"F:" + "\\" + dTime + ".doc", true);
MessageBox.Show("文件已经生成存放到F盘" + dTime+".doc");

}

目里面用到了打印表单,在网上找了写资料整理出来和大家分废话不多说了,咱们看代码

时间: 2024-08-06 16:05:11

C# /windowForm/WPF/SilverLight里面操作Word帮助类提供给大家的相关文章

C#操作Word的+ CKEditor 輸出成Word文件(包含圖案上傳)

C#操作Word 参考博文: C#操作word类文件 https://www.cnblogs.com/walking/p/3571068.html C#中的Office操作专栏(21) http://blog.csdn.net/lzhui1987/article/category/6511234 c# 操作Word总结 http://www.cnblogs.com/eye-like/p/4121219.html C#操作WORD公用类 http://blog.csdn.net/liu793185

python操作word(改课文格式)【最终版】

python操作word的一些方法,前面写了一些感悟,有点跑题,改了下题目,方便能搜索到.心急的可以直接拉到最后看代码,我都加了比较详细的注释. 从8.3号早上9点,到8.8号下午5点半下班,终于把这个python代码写出来了,这五天简直是废寝忘食(扯淡),每天查资料到半夜2点(其实是天太热,洗完澡又晾干就要一个多小时了,在这里吐槽下今年的夏天,2016年北京的7月份简直了,平生第一次长痱子,连去年都没用过的凉席都翻出来了). 好吧,扯得有点远了.因为工作需要,要批量修改一批rtf文件里的文字格

C#操作Word的超详细总结

本文中用C#来操作Word,包括: 创建Word: 插入文字,选择文字,编辑文字的字号.粗细.颜色.下划线等: 设置段落的首行缩进.行距: 设置页面页边距和纸张大小: 设置页眉.页码: 插入图片,设置图片宽高以及给图片添加标题: 插入表格,格式化表格,往表格中插入数据: 保存Word,打印Word: 重新打开Word等. Visual studio版本:Visual Studio 2012(2010应该也可以) 准备工作: /* 1. 添加引用COM里面的 Microsoft Word 12.0

ASP.NET 操作WORD 遇到的两个问题之后的解决办法

因为用到ASP.NET操作word,根据网页内容在服务端生成word之后,供用户下载. 在本机测试时,一切正常,当我发布到服务器之后,问题来了 1,提示:未将对象引用设置到对象的实例. 搜素之后,按照网上的内容开始折腾,才发现这个问题真烦人. 根据网友的帖子,cmd 输入"dcomcnfg.exe", 如图所示,并没有出现帖子所描述的word之类的,唯一沾边的也就这个了,经过各种权限设置之后,还是不行(也可能时我设置的不对). 突然想起来服务器环境时64位,而开发环境时32位,搜索之后

用C#操作word替换字符,不用npoi,改用spire

这两天想写个小程序,是用C#操作word文档的.许多人都对微软本身的解决方案COM组件十分不看好,比如需要本机安装office等等,总之吐槽很多,直接放弃. 搜到一个国产的npoi库,据说操作简单功能强大,下载试用,发现操作excel还是不错的,但word不好使.而且官方网站文档不全,更新缓慢. 尝试文本替换,总是出错.加了官方群,问了问题,没人回应. 网上又找了找,发现有个spire的库不错,也有免费的dll可以用.(转个评价:这是一个免费又强大的C# word 组件,它不需要 Word au

C#中操作Word(1)—— word对象模型介绍

一.开发环境布置 C#中添加对Word的支持,只需添加对Microsoft.Office.Interop.Word的命名空间,如下图所示,右键点击“引用”,在弹出的“添加引用”对话框中选中COM标签页,找到“Microsoft Word 12.0 Object Library”. 点击确定按钮后,可在引用中添加显示名称为Microsoft.Office.Interop.Word的引用: 二.Word的对象模型介绍 Word中共有5种常用的对象模型:应用程序对象Application.文档对象Do

XDocReport 的简单使用 操作word 替换变量

XDocReport 主要是操作word,在word模版中定义变量并替换变量.(在word中还可替换动态图片,可进行循环.判断操作,可定义指令扩展程序,可转成pdf文件 等) 1,模版变量定义. 新建word,Ctrl + F9   编辑域   选择MergeField  编辑域代码 如图: 2,代码 /** * 根据模板导出word文件 * * @param reportData ReportData对象为数据对象,里面存储Map 数据 * @param templateName 模板文件路径

C#操作word时出现的office错误

每次运行WORD都会出现一个提示窗口--"此错误通常是由宏安全性设置造成的.如果您知道宏来自您信任的来源,则可将宏安全性设置更改为允许启用宏.宏安全性设置的更改方式取决于您使用的Microsoft Office System 程序." Word2007提示错误"此错误通常是由宏安全性设置造成"的解决方法有以下几种: 方法一: Word选项--加载项--管理[com加载项],转到--把几个勾勾都取消掉--确定,即可.Win7中注意要以管理员身份进行,因为这些写入了注册

WPF/Silverlight HierarchicalDataTemplate 模版的使用(转)

上一篇 对Wpf/Silverlight Template 进行了总结,本篇继续上一篇,主要是介绍 HierarchicalDataTemplate 的使用方法.HierarchicalDataTemplate 继承于DataTemplate,被称之为"层级式数据模板",主要是应用层级比较明显数据集合,其典型的应用就是对TreeView控件进行数据绑定,接下来就在Silverlight 5 下进行一下演示.最近有个卖凉茶的节目比较火,叫中国好声音,里面的导师和其歌手的分组就是个层级结构