日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程语言 > C# >内容正文

C#

C#导出Word总结

發(fā)布時(shí)間:2023/12/14 C# 22 豆豆
生活随笔 收集整理的這篇文章主要介紹了 C#导出Word总结 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

一、步驟:

1.在Word中建立書簽;
2.編寫C#代碼:?

(1) 數(shù)據(jù)準(zhǔn)備

/// <summary>/// 數(shù)據(jù)準(zhǔn)備/// </summary> /// <returns></returns>public static string CreateRoCreditCycleWord(RoCreditCycle objRoCreditCycle){string tempName = "RoPassengerCreditInfo";;string fileName = String.Format("RoPassengerCreditInfo{0}.{1}", new String[] { Guid.NewGuid().ToString("N"), "doc" });string mPath = SysConfig.RoCreditWordPath + DateTime.Now.ToString("yyyyMM") + "/";Hashtable htParam = new Hashtable();htParam.Add("lblOwnerLicenseNum", objRoCreditCycle.OwnerLicenseNum);htParam.Add("lblOwnerName1", objRoCreditCycle.OwnerName); IList<RoCreditCycleBranch> lstBranch = BaseBLLFactory.CreateService<RoCreditCycleService>().GetRoCreditCycleBranchList(objRoCreditCycle.CycleId);Utils.GenerateWord(tempName, fileName, htParam,lstBranch);return mPath + fileName;}(2)生成Word
/// <summary>/// 生成Word文檔/// </summary>/// <param name="temp">模板名稱</param>/// <param name="fileName">文件名稱</param>/// <param name="param">書簽鍵值對(duì)</param>/// <param name="lstBranch">表格數(shù)據(jù)</param> private static void GenerateWord(string temp, string fileName, Hashtable param, IList<RoCreditCycleBranch> lstBranch){Microsoft.Office.Interop.Word._Application appWord = new Microsoft.Office.Interop.Word.ApplicationClass();Microsoft.Office.Interop.Word._Document docFile = null;string mPhysicalPath = SysConfig.RoCreditWordPhysicalPath + DateTime.Now.ToString("yyyyMM") + "/";try{System.IO.Directory.CreateDirectory(mPhysicalPath);appWord.Visible = false;object objTrue = true;object objFalse = false;object objTemplate = SysConfig.CreditTemplatePhysicalPath + String.Format("{0}.dot", temp);object objDocType = Microsoft.Office.Interop.Word.WdDocumentType.wdTypeDocument;docFile = appWord.Documents.Add(ref objTemplate, ref objFalse, ref objDocType, ref objTrue);foreach (DictionaryEntry de in param){object mark = de.Key;if (docFile.Bookmarks.Exists(mark.ToString())&& de.Value != null&& !string.IsNullOrEmpty(de.Value.ToString())) //一般文本示例{docFile.Bookmarks.get_Item(ref mark).Range.Text = Convert.ToString(de.Value);}else if (mark.ToString() == "lblCurrentLevel") //CheckBox示例{string[] strcodes = Convert.ToString(de.Value).Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);foreach (string strcode in strcodes){switch (strcode){case "1":docFile.Bookmarks.get_Item("cbLevel1").Range.Text = "?";break;case "2":docFile.Bookmarks.get_Item("cbLevel2").Range.Text = "?";break;case "3":docFile.Bookmarks.get_Item("cbLevel3").Range.Text = "?";break;case "4":docFile.Bookmarks.get_Item("cbLevel4").Range.Text = "?";break;}}}? else if (mark.ToString() == "lblPhotoPath") //導(dǎo)入圖片{object oStart = docFile.Bookmarks.get_Item("lblPhoto");Object linkToFile = false; ? ? ? //圖片是否為外部鏈接?Object saveWithDocument = true; ?//圖片是否隨文檔一起保存 ?object range = docFile.Bookmarks.get_Item(ref oStart).Range;//圖片插入位置 ? ??FileInfo filePhotoInfo = new FileInfo(de.Value.ToString());if (filePhotoInfo.Exists == false)break;docFile.InlineShapes.AddPicture(de.Value.ToString(), ref linkToFile, ref saveWithDocument, ref range);docFile.Application.ActiveDocument.InlineShapes[1].Width = 60; ? //設(shè)置圖片寬度 ? ? ? ? ? ??docFile.Application.ActiveDocument.InlineShapes[1].Height = 70; ?//設(shè)置圖片高度 ?}}//表格數(shù)據(jù)示例if (docFile.Bookmarks.Exists("tbBranch")){object missing = System.Reflection.Missing.Value;object Bookmark = (int)Microsoft.Office.Interop.Word.WdGoToItem.wdGoToBookmark;object NameBookMark = "tbBranch";appWord.Selection.GoTo(ref Bookmark, ref missing, ref missing, ref NameBookMark);for (int i = 0; i < lstBranch.Count; i++){RoCreditCycleBranch objBranch = lstBranch[i];appWord.Selection.TypeText(Convert.ToString(i + 1));missing = System.Reflection.Missing.Value;object direction = Microsoft.Office.Interop.Word.WdUnits.wdCell;appWord.Selection.MoveRight(ref direction, ref missing, ref missing);appWord.Selection.TypeText(objBranch.BranchName);appWord.Selection.MoveRight(ref direction, ref missing, ref missing);appWord.Selection.TypeText(objBranch.Address); //appWord.Selection.MoveRight(ref direction, ref missing, ref missing);if (i < lstBranch.Count - 1) appWord.Selection.MoveRight(ref direction, ref missing, ref missing);}}object fullName = mPhysicalPath + String.Format("{0}", fileName);object miss = System.Reflection.Missing.Value;docFile.SaveAs(ref fullName, Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatDocument97, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss);object missingValue = Type.Missing;object doNotSaveChanges = Microsoft.Office.Interop.Word.WdSaveOptions.wdDoNotSaveChanges;docFile.Close(ref doNotSaveChanges, ref missingValue, ref missingValue);appWord.Quit(ref miss, ref miss, ref miss);docFile = null;appWord = null;}catch (Exception ex){object miss = System.Reflection.Missing.Value;object missingValue = Type.Missing;object doNotSaveChanges = Microsoft.Office.Interop.Word.WdSaveOptions.wdDoNotSaveChanges;docFile.Close(ref doNotSaveChanges, ref missingValue, ref missingValue);appWord.Quit(ref miss, ref miss, ref miss);docFile = null;appWord = null;throw ex;}}(3)調(diào)用方法,并下載生成的Word

/// <summary>/// 導(dǎo)出文檔/// </summary>/// <returns></returns>protected void ExportRoCreditCycleWord(){string file = string.Empty;string FileName = string.Empty;string mPhysicalPath = SysConfig.RoCreditWordPhysicalPath + DateTime.Now.ToString("yyyyMM") + "/";string mPath = SysConfig.RoCreditWordPath + DateTime.Now.ToString("yyyyMM") + "/";RoCreditCycle objRoCreditCycle = BaseBLLFactory.CreateService<RoCreditCycleService>().GetRoCreditCycle(GetQueryString("CycleId"));file = Utils.CreateRoCreditCycleWord(objRoCreditCycle);FileName = file.Substring(file.LastIndexOf("/") + 1);FileInfo fileInfo = new FileInfo(mPhysicalPath + FileName);if (fileInfo.Exists == true){//以字符流的形式下載文件FileStream fs = new FileStream(fileInfo.FullName, FileMode.Open);byte[] bytes = new byte[(int)fs.Length];fs.Read(bytes, 0, bytes.Length);fs.Close();Response.ContentType = "application/octet-stream";//通知瀏覽器下載文件而不是打開Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileInfo.Name, System.Text.Encoding.UTF8));Response.BinaryWrite(bytes);Response.Flush();Response.End();}}

二、注意:

1.Word加完標(biāo)簽必須另存為:Word 97-2003模板(*.dot);
2.打開dot文檔時(shí)不能雙擊,要右擊“打開”;
3.顯示標(biāo)簽:選項(xiàng)-高級(jí)-勾選【顯示書簽】;
4.表格建立標(biāo)簽:只需要在第一行第一列建立一個(gè)標(biāo)簽;
5.表格設(shè)置:?
(1)表格屬性-列-最小值(不能是固定值);
(2)表格屬性-單元格-選項(xiàng)-勾選【自動(dòng)換行】;
(3)表格屬性-表格-選項(xiàng)-不勾選【自動(dòng)重調(diào)尺寸以適應(yīng)內(nèi)容】。
6.word組件設(shè)置:參見:http://blog.csdn.net/zzlrpg/article/details/7109752
(1)在服務(wù)器上安裝office.
(2)在"開始"->"運(yùn)行"中輸入dcomcnfg.exe啟動(dòng)"組件服務(wù)"
(3)依次雙擊"組件服務(wù)"->"計(jì)算機(jī)"->"我的電腦"->"DCOM配置"
(4)在"DCOM配置"中找到"Microsoft word 應(yīng)用程序",在它上面點(diǎn)擊右鍵,然后點(diǎn)擊"屬性",彈出"Microsoft word 應(yīng)用程序?qū)傩?#34;對(duì)話框
(5)點(diǎn)擊"標(biāo)識(shí)"標(biāo)簽,選擇"啟動(dòng)用戶"
(6)點(diǎn)擊"安全"標(biāo)簽,在"啟動(dòng)和激活權(quán)限"上點(diǎn)擊"自定義",然后點(diǎn)擊對(duì)應(yīng)的"編輯"按鈕,在彈出的"安全性"對(duì)話框中填加一個(gè)"NETWORK SERVICE"用戶(注意要選擇本計(jì)算機(jī)名),并給它賦予"本地啟動(dòng)"和"本地激活"權(quán)限.(如果還不行,就加 IUser用戶)
(7)依然是"安全"標(biāo)簽,在"訪問(wèn)權(quán)限"上點(diǎn)擊"自定義",然后點(diǎn)擊"編輯",在彈出的"安全性"對(duì)話框中也填加一個(gè)"NETWORK SERVICE"用戶,然后賦予"本地訪問(wèn)"權(quán)限.

(8)引入Word的 Interop.word.dll文件

(9)web.config中加入用戶權(quán)限配置:

<identity impersonate="true" password="sjstmbs123!@#!@#" userName="administrator" />

7.在DCOM 中不存在WORD、EXCEL等OFFICE組件的解決方法:

MMC進(jìn)入到我的視線里面。通過(guò)這個(gè)終于解決此問(wèn)題了。先簡(jiǎn)單說(shuō)下,操作步驟(項(xiàng)目演示完成后,補(bǔ)上圖):
(1)Run
(2)MMC -32


(3)File(文件)
(4)Add Remove Snap-in(添加/刪除管理單元)


(5)Component Services(組件服務(wù))
(6)Add(添加)
(7)OK(確定)


(8)Console Root(控制臺(tái)根節(jié)點(diǎn))
(9)Component Services(組件服務(wù))
(10)Computers(計(jì)算機(jī))
(11)My Computer(我的電腦)
(12)DCOM Config(DCOM配置)
(13)Microsoft Word Application
(14)…


8.參看網(wǎng)址:
(1)http://wenku.baidu.com/view/3963372c7375a417866f8f52.html
(2)http://www.cnblogs.com/eye-like/p/4121219.html

(3)http://blog.sina.com.cn/s/blog_74fe278f0101g75c.html

(4)http://www.cnblogs.com/BoyceLin/archive/2013/03/06/2945655.html(在DCOM 中不存在WORD、EXCEL等OFFICE組件的解決方法)

三、常見錯(cuò)誤

1.Word“消息篩選器顯示應(yīng)用程序正在使用中”

答:(1)解決方法僅需將Word的拼寫檢查取消,“文件”–>”選項(xiàng)”–>”校對(duì)”,將下圖紅框內(nèi)的勾選取消即可。


(2)也可在操作Word時(shí)添加如下代碼,將拼寫檢查和顯示拼寫錯(cuò)誤禁用。
Word.Document oDoc = new Word.Document();
oDoc.SpellingChecked=false;
oDoc.ShowSpellingErrors=false;


總結(jié)

以上是生活随笔為你收集整理的C#导出Word总结的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。