C#richtextbox 读取word
方法如下:1. 新建一个winform工程,添加两个button控件和一个textbox控件。
2. 添加引用com文件Microsoft word 11.0 Object Library。
3. 并在代码中添加命名空间using Word //注意首字母大写。
4. 定义全局变量//创建word_Application app=new Word.Application();//创建word文档_Document doc=null;注意word和word文档是不同的。
5. 读取word文档string temp = doc.Paragraphs[i].Range.Text.Trim();//变量i为第i段textBox1.Text = temp; //将第i段内容复制到textbox中。
word 文件批量重命名???
楼上的 你能不能改写下这个例子啊? 我这个只能导出字符 不能导出表格 string title = "个人信息"; object titleLengh = title.Length; string first = "\n 公司最近需要利用C#对项目进行编程,其" + "中存在一个功能就是可自动生成WORD文档,但一直以来都" + "找不到什么好办法,无奈之下,只有自已学着写一个了."; object firstLengh = first.Length; string second = "\n 如果能真正生成WORD文档的好处有:"; object secondLengh = second.Length; string third = "\n1、根据数据库信息自动生成文档;"; object thirdLengh = third.Length; string forth = "\n2、免去书写文档之苦;"; object forthLengh = forth.Length; string fifth = "\n3、可以通过邮件方式传出文档。
"; object fifthLengh = fifth.Length; object missing; object zero = 0; object c = 10; object one = 1; object two = 2; object tree = 3; object four = 4; object five = 5; object six = 6; object seven = 7; object eight = 8; object nine = 9; object ten = 10; Object Nothing = System.Reflection.Missing.Value; Microsoft.Office.Interop.Word.ApplicationClass wa = new Microsoft.Office.Interop.Word.ApplicationClass(); Microsoft.Office.Interop.Word.Document WordDoc = wa.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing); missing = System.Reflection.Missing.Value; wa.Visible = true; wa.Documents.Add(ref missing, ref missing, ref missing, ref missing); Microsoft.Office.Interop.Word.Range myRange = wa.ActiveDocument.Range(ref zero, ref zero); object r = myRange; Microsoft.Office.Interop.Word.Paragraph p = wa.ActiveDocument.Paragraphs.Add(ref r); p.Range.InsertBefore(title); //p.Range.Font.Size = 1; Microsoft.Office.Interop.Word.Range titleRange = wa.ActiveDocument.Range(ref zero, ref titleLengh); //titleRange.Font.Size = 1; titleRange.Font.Name = "幼圆"; titleRange.Font.Color = Microsoft.Office.Interop.Word.WdColor.wdColorBlue; //MessageBox.Show("NO.1"); //titleRange.Paragraphs.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight; Microsoft.Office.Interop.Word.Range firstR = wa.ActiveDocument.Paragraphs[1].Range;//.Item(2).Range; Microsoft.Office.Interop.Word.Table table = WordDoc.Tables.Add(titleRange, 3, 3, ref Nothing, ref Nothing); r = firstR; p = wa.ActiveDocument.Paragraphs.Add(ref r); firstR.Font.Size = 40; firstR.Paragraphs.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;//在表格第一单元格中添加自定义的文字内容 table.Cell(1, 1).Range.Text = "lllll"; firstR.InsertAfter(first);//firstR.InsertParagraphAfter(); //firstR=wa.ActiveDocument.Paragraphs.Item(3).Range; firstR.InsertAfter(second); firstR.InsertAfter(third); firstR.InsertAfter(forth); firstR.InsertAfter(fifth); Context.Response.Write("成功");
自动为批量Word文档重命名等
可以用脚本来做。
1、用记事本新建一个文本文件,把它保存为“批量重命名.vbs”(注意不要弄成了“批量重命名.vbs.txt”,也就是要确保其扩展名为“.vbs”);2、把下列代码粘贴到这个VBS文件中:Option Explicit Const g_strRootPath = "c:\Temp\docs\Word\ToRename\" ' 指定存放所有文件的目录,可以有子目录 Const g_nTitleMaxLen = 16 ' 指定获取文档里面第一段中的前多少个字符来作为文件名 Call Main' 主函数入口 Sub Main() Dim fso, oFolder, oWordApp Set oWordApp = CreateObject("Word.Application") Set fso = CreateObject("Scripting.FileSystemObject") Set oFolder = fso.GetFolder(g_strRootPath) RenameDocFilesUnderFolder oWordApp, fso, oFolder oWordApp.Quit Set oWordApp = Nothing MsgBox "完成!" End Sub' 重命名指定文件夹(递归)下面的所有Word文件,按照文件里面的第一句可见的文字命名 Sub RenameDocFilesUnderFolder(oWordApp, fso, oFolder) Dim oSubFolder, oFile, oDoc Dim strTitle, strFileName For Each oSubFolder In oFolder.SubFolders RenameDocFilesUnderFolder oWordApp, fso, oSubFolder Next For Each oFile In oFolder.Files Set oDoc = oWordApp.Documents.Open(oFile.Path) strTitle = GetFirstVisibleTextContent(oDoc) oDoc.Close Set oDoc = Nothing If Len(strTitle) 0 Then strFileName = fso.BuildPath(fso.GetParentFolderName(oFile.Path), strTitle & "." & fso.GetExtensionName(oFile.Path)) strFileName = GetUniqueFileName(fso, strFileName) fso.MoveFile oFile.Path, strFileName End If Next End Sub' 获取指定文档第一行可见文字 Function GetFirstVisibleTextContent(oDoc) Dim oParagraph Dim strContent For Each oParagraph In oDoc.Paragraphs strContent = GetSafeFileName(oParagraph.Range.Text) If Len(strContent) 0 Then GetFirstVisibleTextContent = strContent Exit Function End If Next GetFirstVisibleTextContent = "" End Function' 过滤文件名里面的无效字符 Function GetSafeFileName(strFileName) Dim arrUnsafeCharacters, strUnsafeChar Dim nIndex arrUnsafeCharacters = Array("\", "/", ":", "*", "?", """", "", "|") For nIndex = 0 To &H2F strFileName = Replace(strFileName, Chr(nIndex), "") Next For Each strUnsafeChar In arrUnsafeCharacters strFileName = Replace(strFileName, strUnsafeChar, "") Next GetSafeFileName = Left(Trim(strFileName), g_nTitleMaxLen) End Function' 获取不重复的文件名,如果有重名则在文件名后面附加“_1”、“_2”…… Function GetUniqueFileName(fso, strFullName) Dim strParentFolder, strBaseName, strExtensionName Dim nIndex If Not fso.FileExists(strFullName) Then GetUniqueFileName = strFullName Exit Function End If strParentFolder = fso.GetParentFolderName(strFullName) strBaseName = fso.GetBaseName(strFullName) strExtensionName = fso.GetExtensionName(strFullName) nIndex = 0 While fso.FileExists(strFullName) nIndex = nIndex + 1 strFullName = fso.BuildPath(strParentFolder, strBaseName & "_" & nIndex & "." & strExtensionName) Wend GetUniqueFileName = strFullName End Function3、修改代码中开始部分的两个设置,即:存放等待重命名的Word文件的根目录,以及获取文档第一段内容时最多保留多少个字符。
4、保存这个VBS文件,在资源管理器中双击运行它,直到看见“完成”!5、检查所有文件是否已自动重命名。
注意:如果有两个以上的文档依据其内容提取出来的文字相同,则会自动在文件名后面附加“_1”、“_2”、“_3”……。
如果有什么问题,请和我联系。
如何利用Java
1. 初始化com的线程,非常重要,否则第二次创建com对象的时候会出现can't co-create object异常 (参见jacob的帮助文档),完成操作com组件后要调用 realease方法 ComThread.InitSTA();// 初始化com的线程,非常重要!!使用结束后要调用 realease方法 2. 初始化word应用程序,新建一个空白文档,取得文档内容对象//Instantiate objWord //Declare word object ActiveXComponent objWord = new ActiveXComponent("Word.Application"); //Assign a local word object Dispatch wordObject = (Dispatch) objWord.getObject(); //Create a Dispatch Parameter to show the document that is opened Dispatch.put((Dispatch) wordObject, "Visible", new Variant(true));// new Variant(true)表示word应用程序可见 Tip:设置一个对象的属性的时候,利用Dispatch的put方法,给属性赋值。
上面这行语句相当于vb的 wordObject.Visible = true 语句 //Instantiate the Documents Property Dispatch documents = objWord.getProperty("Documents").toDispatch(); //documents表示word的所有文档窗口,(word是多文档应用程序) //Add a new word document, Current Active Document Dispatch document = Dispatch.call(documents, "Add").toDispatch(); // 使用Add命令创建一个新文档,用Open命令可以打开一个现有文档 Tip:调用一个对象的方法的时候,利用Dispatch的call方法,上面的语句相当于vb的document = documents.Add() 语句。
Dispatch wordContent = Dispatch.get(document, "Content").toDispatch(); // 取得word文件的内容 Tip:取得一个对象的成员变量(属性)时利用Dispatch的get方法,上面的语句相当于vb的wordContent = document.Content语句 3. 取得word文档的内容后,可以对其内容进行操作 Dispatch.call(wordContent, "InsertAfter", "这里是一个段落的内容");//插入一个段落 4. 设置刚插入的段落的文字格式 Dispatch paragraphs = Dispatch.get(wordContent, "Paragraphs").toDispatch(); // 所有段落 int paragraphCount = Dispatch.get(paragraphs, "Count").toInt(); // 一共的段落数 // 找到刚输入的段落,设置格式 Dispatch lastParagraph = Dispatch.call(paragraphs, "Item", new Variant(paragraphCount)). toDispatch(); // 最后一段 Dispatch lastParagraphRange = Dispatch.get(lastParagraph, "Range"). toDispatch(); Dispatch font = Dispatch.get(lastParagraphRange, "Font").toDispatch(); Dispatch.put(font, "Bold", new Variant(true)); // 设置为黑体 Dispatch.put(font, "Italic", new Variant(true)); // 设置为斜体 Dispatch.put(font, "Name", new Variant("宋体")); // Dispatch.put(font, "Size", new Variant(12)); //小四 注意:如果想插入一个新的空白行,也需要设置段落的文字格式,否则新插入行的文字格式会于刚插入的段落的格式相同。
5. 将当前文档保存 Dispatch.call(document, "SaveAs", new Variant("C: abc.doc")); // 保存一个新文档 6. 释放COM线程 ComThread.Release();//释放com线程。
根据jacob的帮助文档,com的线程回收不由java的垃圾回收器处理 完整测试代码:(StudyJacob.java 附件中有本文章和java源文件) import com.jacob.activeX.ActiveXComponent; import com.jacob.com.Dispatch; import com.jacob.com.Variant; import com.jacob.com.ComThread; public class StudyJacob { public static void main(String[] args) { ComThread.InitSTA();// 初始化com的线程,非常重要!!使用结束后要调用 realease方法 //Instantiate objWord //Declare word object ActiveXComponent objWord = new ActiveXComponent("Word.Application"); //Assign a local word object Dispatch wordObject = (Dispatch) objWord.getObject(); //Create a Dispatch Parameter to show the document that is opened Dispatch.put((Dispatch) wordObject, "Visible", new Variant(true));// new Variant(true)表示word应用程序可见 //Instantiate the Documents Property Dispatch documents = objWord.getProperty("Documents").toDispatch(); //documents表示word的所有文档窗口,(word是多文档应用程序) //Add a new word document, Current Active Document Dispatch document = Dispatch.call(documents, "Add").toDispatch(); // 使用Add命令创建一个新文档,用Open命令可以打开一个现有文档 Dispatch wordContent = Dispatch.get(document, "Content").toDispatch(); // 取得word文件的内容 Dispatch.call(wordContent, "InsertAfter", "这里是一个段落的内容");//插入一个段落 Dispatch paragraphs = Dispatch.get(wordContent, "Paragraphs").toDispatch(); // 所有段落 int paragraphCount = Dispatch.get(paragraphs, "Count").toInt(); // 一共的段落数 // 找到刚输入的段落,设置格式 Dispatch lastParagraph = Dispatch.call(paragraphs, "Item", new Variant(paragraphCount)). toDispatch(); // 最后一段 ...
如何用C#提取Word,Excel等文件的文本
下面分别使用Spire.Doc和Spire.XLS来提取的文本。
提取Word文本 (一)提取文段中的文本: //初始化文档并加载一个实例 Document document = new Document(); document.LoadFromFile(@"C:\Users\Administrator\Desktop\2017诺贝尔奖.docx"); //初始化一个StringBuilder类新实例 StringBuilder sb = new StringBuilder(); //遍历section及段落,将段落中的文本保存到StringBuilder实例 foreach (Section section in document.Sections) { foreach (Paragraph paragraph in section.Paragraphs) { sb.AppendLine(paragraph.Text); } } //将提取的文档保存为文本格式 File.WriteAllText("Extract.txt", sb.ToString());(二)提取文本框中的文本 //初始化文档并加载一个实例 Document document = new Document(); document.LoadFromFile(@"C:\Users\Administrator\Desktop\2017诺贝尔奖.docx"); //诊断文档是否含有文本框 if (document.TextBoxes.Count > 0) { //初始化一个StreamWriter类并保存提取的文档 using (StreamWriter sw = File.CreateText("result.txt")) { //从文本框提取文档 foreach (Section section in document.Sections) { foreach (Paragraph p in section.Paragraphs) { foreach (DocumentObject obj in p.ChildObjects) { if (obj.DocumentObjectType == DocumentObjectType.TextBox) { TextBox textbox = obj as TextBox; foreach (DocumentObject objt in textbox.ChildObjects) { if (objt.DocumentObjectType == DocumentObjectType.Paragraph) { sw.Write((objt as Paragraph).Text); } } } } } } } }提取Excel文本 //创建一个工作簿并加载Excel工作表 Workbook workbook = new Workbook(); workbook.LoadFromFile(@"..\ExceltoTxt.xls"); //获取首个工作表,并保存为txt格式 Worksheet sheet = workbook.Worksheets[0]; sheet.SaveToFile("ExceltoTxt.txt", " ", Encoding.UTF8);
如何用C#NET处理WORD的事件
导入COM库:Microsoft word 11.0 Object Library.引用里面就增加了:创建新Word object oMissing = System.Reflection.Missing.Value; Word._Application oWord; Word._Document oDoc; oWord = new Word.Application(); oWord.Visible = true; oDoc = oWord.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing); 打开文档: object oMissing = System.Reflection.Missing.Value; Word._Application oWord; Word._Document oDoc; oWord = new Word.Application(); oWord.Visible = true; object fileName = @"E:\CCCXCXX\TestDoc.doc"; oDoc = oWord.Documents.Open(ref fileName, 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); 导入模板 object oMissing = System.Reflection.Missing.Value; Word._Application oWord; Word._Document oDoc; oWord = new Word.Application(); oWord.Visible = true; object fileName = @"E:\XXXCCX\Test.doc"; oDoc = oWord.Documents.Add(ref fileName, ref oMissing, ref oMissing, ref oMissing);.添加新表 object oMissing = System.Reflection.Missing.Value; Word._Application oWord; Word._Document oDoc; oWord = new Word.Application(); oWord.Visible = true; oDoc = oWord.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing); object start = 0; object end = 0; Word.Range tableLocation = oDoc.Range(ref start, ref end); oDoc.Tables.Add(tableLocation, 3, 4, ref oMissing, ref oMissing);.表插入行 object oMissing = System.Reflection.Missing.Value; Word._Application oWord; Word._Document oDoc; oWord = new Word.Application(); oWord.Visible = true; oDoc = oWord.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing); object start = 0; object end = 0; Word.Range tableLocation = oDoc.Range(ref start, ref end); oDoc.Tables.Add(tableLocation, 3, 4, ref oMissing, ref oMissing); Word.Table newTable = oDoc.Tables[1]; object beforeRow = newTable.Rows[1]; newTable.Rows.Add(ref beforeRow);.单元格合并 object oMissing = System.Reflection.Missing.Value; Word._Application oWord; Word._Document oDoc; oWord = new Word.Application(); oWord.Visible = true; oDoc = oWord.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing); object start = 0; object end = 0; Word.Range tableLocation = oDoc.Range(ref start, ref end); oDoc.Tables.Add(tableLocation, 3, 4, ref oMissing, ref oMissing); Word.Table newTable = oDoc.Tables[1]; object beforeRow = newTable.Rows[1]; newTable.Rows.Add(ref beforeRow); Word.Cell cell = newTable.Cell(1, 1); cell.Merge(newTable.Cell(1, 2));.单元格分离 object oMissing = System.Reflection.Missing.Value; Word._Application oWord; Word._Document oDoc; oWord = new Word.Application(); oWord.Visible = true; oDoc = oWord.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing); object start = 0; object end = 0; Word.Range tableLocation = oDoc.Range(ref start, ref end); oDoc.Tables.Add(tableLocation, 3, 4, ref oMissing, ref oMissing); Word.Table newTable = oDoc.Tables[1]; object beforeRow = newTable.Rows[1]; newTable.Rows.Add(ref beforeRow); Word.Cell cell = newTable.Cell(1, 1); cell.Merge(newTable.Cell(1, 2)); object Rownum = 2; object Columnnum = 2; cell.Split(ref Rownum, ref Columnnum); 通过段落控制插入 object oMissing = System.Reflection.Missing.Value; object oEndOfDoc = "\\endofdoc"; /**//* \endofdoc is a predefined bookmark */ //Start Word and create a new document. Word._Application oWord; Word._Document oDoc; oWord = new Word.Application(); oWord.Visible = true; oDoc = oWord.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing); //Insert a paragraph at the beginning of the document. Word.Paragraph oPara1; oPara1 = oDoc.Content.Paragraphs.Add(ref oMissing); oPara1.Range.Text = "Heading 1"; oPara1.Range.Font.Bold = 1; oPara1.Format.SpaceAfter = 24; //24 pt spacing after paragraph. oPara1.Range.InsertParagraphAfter();
delphi中把查询出来的数据导入word中?
我将我的商用《旅行社管理系统》的 发团通知 部分奉献给您,望对您有所帮助。
procedure TFrmMain.N327Click(Sender: TObject); var FWord :Variant; FDoc :Variant; strSQL :string; begin //首先创造对象,如果出现异常就做出提示 try FWord := CreateOleObject('Word.Application'); //WOrd程序的执行是否可见,值为false时,程序在后台运行。
FWord.Visible := True; except messagebox(0,'创建word对象失败!','警告',MB_OK+MB_ICONINFORMATION); exit; end; strSQL :='select * From "B_T_Company_Infor"'; with dm.ClientDataSet_Temp do begin if Active then Active:=False; CommandText:=strSQL; Open; end; //现在打开的Word中,创建一个新的页面,然后在其中键入需要的内容 try FDOC :=FWord.Documents.Add; {对于Word的新页面} FWord.Selection.Font.Name :='宋体'; FWord.Selection.Font.Size :=20; FWord.Selection.Font.Bold :=2; FWord.Selection.paragraphs.Alignment := wdAlignParagraphCenter; FWord.Selection.TypeText(dm.ClientDataSet_Temp.Fields[0].AsString); FWord.Selection.Typeparagraph;//换行 FWord.Selection.Typeparagraph; FWord.Selection.paragraphs.Alignment := wdAlignParagraphLeft; FWord.Selection.Font.Size :=12; FWord.Selection.Font.Bold :=0; FWord.Selection.TypeText(' 现将我社组团部的'); FWord.Selection.TypeText(' '); FWord.Selection.TypeText('团计划发出,各地请按下列行程做接待,并及早落实'+ '团队计划和选派优秀导游员。
各地代订住宿、火车票、机票务必安排好接待,日程'+ '如有变更,及时与下站接待社或本社联系,各地接团时请举【'+ dm.ClientDataSet_Temp.Fields[0].AsString+'】接站牌。
'); FWord.Selection.Typeparagraph;//换行 FWord.Selection.Typeparagraph;//换行 FWord.Selection.TypeText('请速回传真确认,谢谢合作!'); FWord.Selection.Typeparagraph;//换行 FWord.Selection.Typeparagraph;//换行 FWord.Selection.TypeText('人数:'); FWord.Selection.TypeText('人数:'); FWord.Selection.TypeText('国籍:'); FWord.Selection.TypeText('国籍:'); FWord.Selection.TypeText('等级:'); FWord.Selection.TypeText('等级:'); FWord.Selection.Typeparagraph;//换行 FWord.Selection.TypeText('这里是团队安排'); FWord.Selection.Typeparagraph;//换行 FWord.Selection.Typeparagraph;//换行 FWord.Selection.TypeText('TO: '); FWord.Selection.TypeText('12345678901234567890'); FWord.Selection.Typeparagraph;//换行 FWord.Selection.TypeText('TEL: '); FWord.Selection.TypeText('12345678901234567890'); FWord.Selection.Typeparagraph;//换行 FWord.Selection.TypeText('FAX: '); FWord.Selection.TypeText('12345678901234567890'); FWord.Selection.Typeparagraph;//换行 FWord.Selection.Typeparagraph;//换行 FWord.Selection.TypeText('______________________________________________'); FWord.Selection.Typeparagraph;//换行 FWord.Selection.Typeparagraph;//换行 FWord.Selection.TypeText('FROM: '); FWord.Selection.TypeText(dm.ClientDataSet_Temp.Fields[0].AsString); FWord.Selection.Typeparagraph;//换行 FWord.Selection.TypeText('TEL: '); FWord.Selection.TypeText(dm.ClientDataSet_Temp.Fields[3].AsString); FWord.Selection.Typeparagraph;//换行 FWord.Selection.TypeText('FAX: '); FWord.Selection.TypeText(dm.ClientDataSet_Temp.Fields[4].AsString); FWord.Selection.Typeparagraph;//换行 Except on e: Exception do Messagebox(0,Pchar(e.Message),'警告',MB_OK+MB_ICONINFORMATION); end; //保存文档 FWord.Caption := '组团计划保存在: '+ExtractFilePath(application.ExeName)+'Reports\GroupPlan.doc'; FDOC.SaveAS(ExtractFilePath(application.ExeName)+'Reports\GroupPlan.doc'); if messagebox(0,'组团计划已经保存成功!'+chr(13)+chr(13)+ '单击【确定】退出Word,返回到程序中!','您确信要退出Word吗?', MB_YESNO+MB_ICONINFORMATION+MB_DEFBUTTON2)=IDYES then begin FWord.Quit; FWord := Unassigned; end; end; ----------------------------- Delphi与Word之间的融合技术(1) 一、VBA代码含义 Microsoft Word是一个集成化环境,是美国微软公司的字处理系统,但是它决不仅仅是一个字处理系统,它集成了Microsoft Visual Basic,可以通过编程来实现对Word功能的扩展。
Microsoft Visual Basic在word中的代码即Word的宏,通过编写Word宏,可实现一些文档处理的自动化,如实现文档的自动备份、存盘等,可扩展Word文档的功能,因此,能够充分利用Word的特性,甚至使Word成为自己软件的一部分。
Word的宏既有有利的一部分,因为它能够帮助我们实现文档的自动化,但是Word的宏也不是纯粹的有利,有时它可能危害我们的文档、计算机系统甚 至网络,从最开始的Taiwan NO1宏病毒到现在的...
转载请注明出处51数据库 » c word paragraphs