一、word代码改变文本格式
以前做过的代码找一段出来供参考。
Private Sub CommandButton4_Click() '排版格式
Dim T_WORD As String
Dim RNG As Range
Dim mypra As Paragraph
Set mydic = CreateObject("Scripting.Dictionary") '二级标题字符
mydic.Add "一", 1
mydic.Add "二", 1
mydic.Add "三", 1
mydic.Add "四", 1
mydic.Add "五", 1
mydic.Add "六", 1
mydic.Add "七", 1
mydic.Add "八", 1
mydic.Add "九", 1
mydic.Add "十", 1
T_WORD = TextBox1.Text
导出路径文件名 = ThisDocument.Path & "" & T_WORD
Set mydoc = Documents.Open(导出路径文件名)
mydoc.Activate
Selection.WholeStory '选中全部
Selection.ClearFormatting '清除全部格式
zz = 0
'For Each mypra In ActiveDocument.Paragraphs
For Each mypra In mydoc.Paragraphs
If Not mypra.Range.Information(wdWithInTable) = True Then '非表格段落
zz = zz + 1
MYSTR = mypra.Range.Text
mychar = Mid(MYSTR, 1, 1)
'mypra.Select
If zz = 1 Or zz = 2 Then '一级标题 黑体 小二 是 居中 1行 1行 固定值18磅 无
With mypra
.Range.Font.Name = "黑体"
.Range.Font.Size = 18 '(小二高度18磅)
.Range.Font.Bold = True
.Range.ParagraphFormat.Alignment = wdAlignParagraphCenter
.Range.ParagraphFormat.LineUnitBefore = 1
.Range.ParagraphFormat.LineUnitAfter = 1
'.Range.ParagraphFormat.SpaceBefore = 10.5 '段前 1123修改为5号10.5磅
'.Range.ParagraphFormat.SpaceAfter = 10.5 '段后
.FirstLineIndent = 0 '首行缩进无
.LineSpacingRule = wdLineSpaceExactly
'.LineSpacingRule = wdLineSpace1pt5
.Range.ParagraphFormat.LineSpacing = 18 '行间距18磅
End With
Else
If mydic.Exists(mychar) Then '二级标题 黑体 小四 是 两端对齐 1行 1行 固定值18磅 首行缩进2字符
With mypra
.Range.Font.Name = "黑体"
.Range.Font.Size = 12
.Range.Font.Bold = True
.Range.ParagraphFormat.Alignment = wdAlignParagraphJustify
.Range.ParagraphFormat.LineUnitBefore = 1
.Range.ParagraphFormat.LineUnitAfter = 1
'.Range.ParagraphFormat.SpaceBefore = 10.5 '段前 小四高度=12磅 1123修改为5号10.5磅
'.Range.ParagraphFormat.SpaceAfter = 10.5 '段后
'.FirstLineIndent = CentimetersToPoints(1.27) '首行缩进2字符 0.635*2=1.27
.FirstLineIndent = CentimetersToPoints(0.74) '首行缩进2字符 0.74 和正文相同
' .LineSpacingRule = wdLineSpace1pt5
.LineSpacingRule = wdLineSpaceExactly
.Range.ParagraphFormat.LineSpacing = 18 '行间距18磅
End With
Else '正文 宋体 五号 否 两端对齐 0行 0.5行 固定值18磅 首行缩进2字符
With mypra
.Range.Font.Name = "宋体"
.Range.Font.Size = 10.5
.Range.Font.Bold = False
.Range.ParagraphFormat.Alignment = wdAlignParagraphJustify
'.Range.ParagraphFormat.SpaceBefore = 0 '段前0
'.Range.ParagraphFormat.SpaceAfter = 5.25 '段后0.5*10.5=5.25
.Range.ParagraphFormat.LineUnitBefore = 0
.Range.ParagraphFormat.LineUnitAfter = 0.5
.FirstLineIndent = CentimetersToPoints(0.74) '0.37*2=0.74
.LineSpacingRule = wdLineSpaceExactly
.Range.ParagraphFormat.LineSpacing = 18 '行间距18磅
.Alignment = wdAlignParagraphJustify
End With
If zz = 3 Then '第3段落居中
With mypra
.Range.ParagraphFormat.Alignment = wdAlignParagraphCenter
End With
End If
End If
End If
End If
Next mypra
mydoc.Save
mydoc.Close False '关闭word文档
Set mydoc = Nothing '清空工作簿项目
End Sub
二、怎么sublime代码原格式到word
有时写文档时需要将代码粘贴到word中,但直接粘贴到word中的代码虽能保持换行与缩进等格式,但在一般代码编辑工具中的关键字高亮功能却无法实现,即粘贴到word中的代码不在具有丰富的色彩。使用一款免费软件——notepad++即可实现将关键字高亮的代码粘贴到word中。 首先用notepad++打开源代码文件。notepad++能识别C/C++、Java、matlab等多种语言的源代码。选中要粘贴的代码(如果该代码文件中的所有内容均需要粘贴,则无需选中文字)。然后在选择插件->NppExport->CopyHTMLtoclipboard 然后在word中粘贴即可。 此外,关键字的颜色也可以根据自己的需求在notepad++中进行设置,设置方法:菜单->格式->语言格式设置
三、如何将mht转成word格式
第一步,先制作了一个很简单的html模板。将动态内容用诸如“$htmldata[1]”来代替,等取出数据后用Replace函数进行替换。
http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
http://www.w3.org/1999/xhtml">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<style type="text/css">
* {
margin:0px;
padding:0px;
}
.article_s{
width:980px;
height:auto;
overflow:hidden;
margin:0 auto;
}
.article_s_t_f{
width:960px;
height:auto;
line-height: 30px;
font-size: 18px;
padding-top: 10px;
text-align: center;
font-weight:700;
margin:0 auto;
}
.article_s_t_s{
width:960px;
line-height: 30px;
text-align: center;
font-size: 13px;
border-bottom:1px dashed #CCC;
margin:0 auto;
}
.article_s_l{
width:960px;
margin:0 auto;
line-height:28px;
font-size:14px;
padding:10px 0px 10px 0px;
}
.article_s_c{
width:960px;
height:23px;
text-align:center;
margin-bottom:20px;
}
</style>
$htmldata[2]$htmldata[4]
第二步:
建立一个静态类,代码如下:
public class Function
{
static Function() { }
//根据html生成mht文件,需要引入相应的dll,如图所示
public static void HtmlToMht(string src, string dst)
{
CDO.Message msg = new CDO.MessageClass();
CDO.Configuration c = new CDO.ConfigurationClass();
msg.Configuration = c;
msg.CreateMHTMLBody(src, CDO.CdoMHTMLFlags.cdoSuppressNone, "", "");
ADODB.Stream stream = msg.GetStream();
stream.SaveToFile(dst, ADODB.SaveOptionsEnum.adSaveCreateOverWrite);
}
public static void WriteHtml(string name,string content,string addTime,string hits,stringuser)//参数内容都是从数据库读出来的文章信息,其中content就是ewebeditor生成的html代码
{
DateTime dt = DateTime.Parse(addTime);//将string型的日期格式转为DateTime型的因为默认的日期格式不能作为文件名,所以将日期的“:”替换为“-”
string Temp_Name = @"D:ApplicationVisual Studio 2010Projects富文本转Word富文本转WordtempArticles.html";//HTML模板的路径
string File_Name = @"D:ApplicationVisual Studio 2010Projects富文本转Word富文本转Wordhtml【" + dt.ToShortDateString().Replace("/","-") +"】" +name + ".html";//生成html文件的路径
string File_NameM = @"D:ApplicationVisual Studio 2010Projects富文本转Word富文本转Wordhtml【" + dt.ToShortDateString().Replace("/","-") +"】" +name + ".mht";//生成mht文件的路径
string File_Name2 = @"D:ApplicationVisual Studio 2010Projects富文本转Word富文本转Wordhtml【" + dt.ToShortDateString().Replace("/", "-") + "】" + name + ".doc";//生成Word文档的路径
StreamReader sr = new StreamReader(Temp_Name);
StringBuilder htmltext = new StringBuilder();
String line;
while ((line = sr.ReadLine()) != null)
{
htmltext.Append(line);//读取到html模板的内容
}
sr.Close();
//替换相应的内容到指定的位置
htmltext = htmltext.Replace("$htmldata[1]", name);
htmltext = htmltext.Replace("$htmldata[2]", name);
htmltext = htmltext.Replace("$htmldata[3]", ("点击数:" + hits + " 发布时间:" + addTime + " 发布者:" + user));
htmltext = htmltext.Replace("$htmldata[4]", content);
using (StreamWriter sw = new StreamWriter(File_Name, false, System.Text.Encoding.GetEncoding("UTF-8"))) //保存地址
{
//生成HTML文件
sw.WriteLine(htmltext);
sw.Flush();
sw.Close();
}
HtmlToMht(File_Name, File_NameM);//因为带图片的html直接转为Word的话,图片会以引用的形式展示(也就是说不是内置到word文档里去的,一旦断网或将图片放在别的路径之后,打开word文档图片会显示不出来,所以通过折冲的办法先生成html,然后转换为mht,再转为word)
WordAction.SaveAsWord(File_NameM, File_Name2);//生成word
}
}
建立另外一个操作word 的静态类,代码如下(代码都是拷的O(∩_∩)O):
public class WordAction
{
public static void SaveAsWord(string fileName, string pFileName)//使用原生方法将mht转换为word文档,不是那种直接修改后缀名的方式
{
object missing = System.Reflection.Missing.Value;
object readOnly = false;
object isVisible = true;
object file1 = fileName;
object html1 = pFileName;
object format = WdSaveFormat.wdFormatDocument;
ApplicationClass oWordApp = new ApplicationClass();
oWordApp.Visible = false;
Document oWordDoc = oWordApp.Documents.Open(ref file1, ref format, ref readOnly,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);
oWordApp.ActiveWindow.View.Type = Microsoft.Office.Interop.Word.WdViewType.wdPrintView;//将web视图修改为默认视图,不然打开word的时候会以web视图去展示,而不是默认视图。(唯独这句代码是自己加的 = =|||)
oWordDoc.SaveAs(ref html1, 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);
oWordDoc.Close(ref missing, ref missing, ref missing);
oWordDoc = null;
oWordApp.Application.Quit(ref missing, ref missing, ref missing);
oWordApp = null;
killAllProcess();
}
protected static void killAllProcess() // 杀掉所有winword.exe进程
{
System.Diagnostics.Process[] myPs;
myPs = System.Diagnostics.Process.GetProcesses();
foreach (System.Diagnostics.Process p in myPs)
{
if (p.Id != 0)
{
string myS = "WINWORD.EXE" + p.ProcessName + " ID:" + p.Id.ToString();
try
{
if (p.Modules != null)
if (p.Modules.Count > 0)
{
System.Diagnostics.ProcessModule pm = p.Modules[0];
myS += "n Modules[0].FileName:" + pm.FileName;
myS += "n Modules[0].ModuleName:" + pm.ModuleName;
myS += "n Modules[0].FileVersionInfo:n" + pm.FileVersionInfo.ToString();
if (pm.ModuleName.ToLower() == "winword.exe")
p.Kill();
}
}
catch
{ }
finally
{
}
}
}
}
}
第三步:
随便建了个aspx页面,写上以下代码。
string title = "";
string postuser = "";
string content = "";
string addTime = "";
string hits = "";
DataTable dt = CatalogAccess.GetArticles();//从数据库取出自己需要的数据
for (int i = 0; i < dt.Rows.Count; i++)
{
DataRow dr = dt.Rows[i];
title = dr["Title"].ToString();
postuser = dr["PostUser"].ToString();
addTime = dr["AddTime"].ToString();
hits = dr["Hits"].ToString();
content = dr["Content"].ToString();
content = content.Replace("src="/new/Editor/uploadfile/", "src="files/");//替换图片文件的引用目录,这个动作是非必要的,因为我把图片都下载到本地了,所以替换一下里面引用的图片路径,只要根据模板生成的html能正常显示图片就可以了
Function.WriteHtml(title, content, addTime, hits, postuser);//生成word文档
}
}
好了,大功告成啦。当然生成的word文档跟网页存在一点差别,在接受的范围内。