C# html代碼生成word


首先引入 Microsoft.Office.Interop.Word

其次要先說一下,把一大段html代碼直接變成word文件,只能生成doc文件,docx文件應該是不行的

 

首先我們用IO生成一個doc文件

FileStream fs = new FileStream(路徑+文件名+.doc, FileMode.Create);
            StreamWriter sw = new StreamWriter(fs);
            sw.Write("<html>" + html代碼+ "</html>");
            sw.Close();
            sw.Dispose();
            fs.Close();
            fs.Dispose();

            createWord(FileName, SavaPath);

這時就會生成一個doc文件,里面內容也是我們想要的樣子,所以這就完成了嗎?當然不是

你把這個doc文件另存為一下,會發現它默認選中的格式是html

這是因為它本質還是一個html文件,只不過后綴名為doc而已,所以我們需要再把他變成真正的word文件

private string createWord(string filename,string savepath)
        {
            string file = ""; //路徑1(我們之前生成的文件路徑)
            string file2 = "";//路徑2
            file = savepath + filename + ".doc";
            string demo = System.Web.Hosting.HostingEnvironment.MapPath("路徑2");
            file2 = demo + filename + "_.doc";

            Object path = file as Object;
            Object path2 = file2 as Object;
            Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application();
            Object Nothing = Missing.Value;
            Object format = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatDocument;
            Microsoft.Office.Interop.Word.Document wordDoc = wordApp.Documents.Open(ref path, false); //打開之前生成的文件

            wordDoc.Activate();//設為當前操作的文件
            //指定要在頁面視圖中顯示的文檔元素
            wordApp.ActiveWindow.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekMainDocument;//設為主文檔



            //設置文檔為頁面視圖模式
            wordApp.ActiveWindow.View.Type = Microsoft.Office.Interop.Word.WdViewType.wdNormalView;



            wordApp.ActiveWindow.ActivePane.Selection.WholeStory();
            //指定要應用於段落的行距格式
            wordApp.ActiveWindow.ActivePane.Selection.ParagraphFormat.LineSpacingRule = Microsoft.Office.Interop.Word.WdLineSpacing.wdLineSpace1pt5;//1.5 倍行距。該行距相當於當前字號加 6 磅。
            //設置指定段落的段后間距
            wordApp.ActiveWindow.ActivePane.Selection.ParagraphFormat.LineUnitAfter = 0.5f;

            //把操作后的文件保存到路徑2
            wordDoc.SaveAs(ref path2, ref format, 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);
            wordDoc.Close(ref Nothing, ref Nothing, ref Nothing);
            wordApp.Quit(ref Nothing, ref Nothing, ref Nothing);
            //刪除原本生成的文件
            File.Delete(file);
            //把路徑2的文件剪切到路徑1
            File.Move(file2, file);
            //返回路徑
            return file;
        }

 

經過createWord方法后生成的文件就是真正的word文件了,而且展現的內容以及樣式也和html時的一樣,這樣就完成了

 

順便加個小知識點

如果要在文件中加入分頁符,就在html對應的地方加上這段代碼

<br clear=all style='page-break-before:always'>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM