• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

word导入与导出(java版和c#版)

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

由于我不擅长言辞与华丽的文采,就在这里直接贴出相应的代码,其中导入和导出都看个人而异。大致对word的操作都可以网上搜到。

1.JAVA版

  JAVA版我主要用的是JACOB。版本是jacob-1.14.3-x86,可以网上下到。由于代码太多,我就不一一贴出

 

代码
ComThread.InitSTA();// 初始化com的线程,非常重要!!使用结束后要调用 realease方法 
        /*
        完成初始化工作 
        
*/ 
        ActiveXComponent objWord 
= new ActiveXComponent("Word.Application");// Instantiate objWord and Declare word object 
        Dispatch wordObject = (Dispatch) objWord.getObject();// Assign a local word object 
        Dispatch.put((Dispatch) wordObject, "Visible"new Variant(true));// Variant(true)表示word应用程序可见 
        Dispatch documents = objWord.getProperty("Documents").toDispatch(); // documents表示word的所有文档窗口,(word是多文档应用程序) 
        Dispatch document = Dispatch.call(documents, "Add").toDispatch(); // 使用Add命令创建一个新文档,用Open命令可以打开一个现有文档 
        
         Dispatch ActiveWindow 
= objWord.getProperty("ActiveWindow")
            .toDispatch();
          Dispatch ActivePane 
= Dispatch.get(ActiveWindow, "ActivePane")
            .toDispatch();
        
        
/*
        *开始写word的工作,包括标题,正文(段落一、段落二) 
        
*/ 
        Dispatch wordContent 
= Dispatch.get(document, "Content").toDispatch(); // 取得word文件的内容 
        Dispatch selection = Dispatch.get(wordObject, "Selection").toDispatch(); 
        Dispatch paragraphFormat
=Dispatch.get(selection,"ParagraphFormat").getDispatch(); 
        Dispatch paragraphFormat1
=
            Dispatch.
get(selection,"ParagraphFormat").getDispatch(); 
        Dispatch.put(paragraphFormat1, 
"Alignment""1"); // 设置标题的对齐方式(1:置中 2:靠右 3:靠左) 
               
        Dispatch font 
= Dispatch.get(selection, "Font").toDispatch(); // 字型格式化需要的对象 
        Dispatch.put(font, "Bold""1");         // 字型租体
        Dispatch.put(font, "Size""15");        //字体大小
        Dispatch.call(selection, "TypeText""人员简历(编号:"+personalbaseinfo.getPersonno()+")"); // 写入标题内容 
        Dispatch.call(selection, "TypeParagraph"); // 空一行段落 
        Dispatch.put(font, "Size""10");
        
        Dispatch tables 
= Dispatch.get(wordContent, "Tables").toDispatch();  //所有的表格数
        String realPath = request.getRealPath("/").replace("\\.\\","\\").replace("/","\\\\\\\\");
        
        
        
//写页眉和页脚
        Dispatch View = Dispatch.get(ActivePane, "View").toDispatch();
        Dispatch.put(View, 
"SeekView""9"); //9是设置页眉
        Dispatch.put(paragraphFormat1, "Alignment""3"); // 置中
        String url="theme/default/images/gxa.jpg";
        Dispatch.call(Dispatch.
get(selection, "InLineShapes").toDispatch(),
                
"AddPicture", realPath+url);
        Dispatch.put(View, 
"SeekView""10"); // 10是设置页脚
        Dispatch.put(paragraphFormat1, "Alignment""2"); // 靠右
        Dispatch.put(selection, "Text""***********内容*****"); // 初始化从1开始
        Dispatch.call(selection, "EndKey",6); 
        String path
=realPath+"uploadfile\\tempfile";
        File file 
=new File(path);
        boolean flag 
= false;
        
if(!file.exists()){
            flag 
= file.mkdir();    
        }
else{
             delFolder(path);
            flag 
= file.mkdir();       
            flag
=true;
        }
        Date now 
= new Date();
        SimpleDateFormat sdf2 
= new SimpleDateFormat("yyyyMMddHHmmss");
        String name 
= sdf2.format(now)+".doc";
        
        
/*
        * 关闭文档 
        
*/ 
        Dispatch.call(document, 
"SaveAs"new Variant(path+"\\"+name)); // 保存一个新文档 
        Dispatch.call(objWord,"Quit",new Variant(true)); //关闭对象
        ComThread.Release();//释放com线程。根据jacob的帮助文档,com的线程回收不由java的垃圾回收器处理 

        
try {
            
if(flag){
                
this.onLoad();
                response.sendRedirect(
"uploadfile/tempfile/"+name);
                facesContext.responseComplete();
            }
        } 
catch (IOException e) {
        }
        
return (path+"\\test.doc");
    }

 

2.c#版

下面是一个用dot模板替换的列子,可解决替换过程中字符串过长,我想到的就是用递归来,哈哈。

 

代码
object _NullObject = System.Reflection.Missing.Value;

        
object _ReadOnly = true;
        ApplicationClass _Application 
= null;
        Document _DocumentClass 
= null;
        
protected void Page_Load(object sender, EventArgs e)
        {
            
//Import();
        }

        
/// <summary>
        
/// 创建红头批示
        
/// </summary>
        
/// <param name="year"></param>
        
/// <param name="issuce"></param>
        
/// <param name="date"></param>
        
/// <param name="cgdw"></param>
        
/// <param name="publication"></param>
        
/// <param name="content"></param>
        
/// <param name="editor"></param>
        
/// <param name="sender"></param>
        private void CreateComment(string year,
            
string issuce,
            
string date,
            
string cgdw,
            
string publication,
            
string content,
            
string editor,
            
string sender)
        {
            
object _Path = HttpContext.Current.Server.MapPath("红头批示.dot");

            
try
            {
                _Application 
= new ApplicationClass();

                _DocumentClass 
= _Application.Documents.Add(ref _Path, ref _NullObject, ref _NullObject, ref _NullObject);

                
object replaceAll = Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll;

                Replace(
"[model:year]", year);
                Replace(
"[model:issuce]", issuce);
                Replace(
"[model:date]", date);
                Replace(
"[model:cgdw]", cgdw);
                Replace(
"[model:publication]", publication);
                Replace(
"[model:content]", content);
                Replace(
"[model:editor]", editor);
                Replace(
"[model:sender]", sender);

                
//_Application.Selection.Find.Execute(ref _NullObject, ref _NullObject, ref _NullObject, ref _NullObject, ref _NullObject,
                
//ref _NullObject, ref _NullObject, ref _NullObject, ref _NullObject, ref _NullObject,
                
//ref replaceAll, ref _NullObject, ref _NullObject, ref _NullObject, ref _NullObject);

                
object _Start = 2;
                
object _End = 2;

                
//if (_Application.Selection.Find.Execute(ref _NullObject, ref _NullObject, ref _NullObject, ref _NullObject, ref _NullObject,
                
//    ref _NullObject, ref _NullObject, ref _NullObject, ref _NullObject, ref _NullObject,
                
//    ref replaceAll, ref _NullObject, ref _NullObject, ref _NullObject, ref _NullObject))
                
//{
                
//}

                
object _Tp = HttpContext.Current.Server.MapPath(HttpContext.Current.Request.ApplicationPath + "\\红头批示");
                
object _FormateDate = WdSaveFormat.wdFormatDocument97;
                
                _DocumentClass.SaveAs(
ref _Tp, ref _FormateDate, ref _NullObject,
                
ref _NullObject, ref _NullObject, ref _NullObject,
                
ref _NullObject, ref _NullObject, ref _NullObject,
                
ref _NullObject, ref _NullObject, ref _NullObject,
                
ref _NullObject, ref _NullObject, ref _NullObject, ref _NullObject);
            }
            
catch
            {
            }
            
finally
            {
                
if (_DocumentClass != null)
                {
                    
try
                    {
                        _DocumentClass.Close(
ref _NullObject, ref _NullObject, ref _NullObject);
                    }
                    
catch
                    {
                    }
                }

                
if (_Application != null)
                {
                    
try
                    {
                        _Application.Quit(
ref _NullObject, ref _NullObject, ref _NullObject);
                    }
                    
catch
                    {
                    }
                }

                System.Runtime.InteropServices.Marshal.ReleaseComObject(_Application);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(_DocumentClass);

                _Application 
= null;
                _DocumentClass 
= null;

                GC.Collect();
            }

        }

///﹤summary﹥  
        
/// 浅析C#Word文档替换操作,在word 中查找一个字符串直接替换所需要的文本  
        
/// ﹤/summary﹥  
        
/// ﹤param name="strOldText"﹥原文本﹤/param﹥  
        
/// ﹤param name="strNewText"﹥新文本﹤/param﹥  
        
/// ﹤returns﹥﹤/returns﹥  
        public void Replace(string strOldText, string strNewText)
        {
            _DocumentClass.Content.Find.Text 
= strOldText;
            
object FindText, ReplaceWith, ReplaceType;
            
object MissingValue = Type.Missing;
            FindText 
= strOldText;//要查找的文本  
            ReplaceWith = strNewText;//替换文本     
            
//判断字符串内容是否过长,如果过长则自动切断
            if (strNewText.Length > 220)
            {
                ReplaceWith 
= strNewText.Substring(0220+ strOldText;
            }
            ReplaceType 
= Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll;  
            
/***
             * wdReplaceAll - 替换找到的所有项。    
             * wdReplaceNone - 不替换找到的任何项。 
             * wdReplaceOne - 替换找到的第一项。  
             **
*/
            _DocumentClass.Content.Find.ClearFormatting();  
//移除Find的搜索文本和段落格式设置  
            if (_DocumentClass.Content.Find.Execute(ref FindText, ref MissingValue, ref MissingValue, ref MissingValue,
                
ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref ReplaceWith, 
                
ref ReplaceType, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue))
            {
                
if (strNewText.Length > 220)
                {
                    Replace(FindText.ToString(), strNewText.Substring(
221, strNewText.Length-221));
                }
            }
        }

 

 

最后心情比较复杂,因为有个可爱的小笨蛋。有需要的可以向我要源码,网速太慢就不上传了。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
c#调用Dos命令(超捷)发布时间:2022-07-10
下一篇:
C#发送邮件发布时间:2022-07-10
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap