C# 導出word文檔及批量導出word文檔(2)


     aspose.word主要是通過把讀取出來的數據放到datatable里,在datable里做相應的格式的調整,再導出到word文檔里。mvc和webform最后導出的語句略有不同,在mvc的controller,用的是base.File,對應的是FileContentResult,在webform里用的是Response。寫法分別為:

          //在WebForm中,保存文檔到流中,使用Response. BinaryWrite輸出該文件
         var docStream = new MemoryStream();
         doc.Save(docStream, SaveOptions.CreateSaveOptions(SaveFormat.Doc));
         Response.ContentType = "application/msword";
         Response.AddHeader("content-disposition", "attachment;  filename=Template.doc");
         Response.BinaryWrite(docStream.ToArray());
         Response.End();
         //在MVC中采用,保存文檔到流中,使用base.File輸出該文件
        var docStream = new MemoryStream();
        doc.Save(docStream, SaveOptions.CreateSaveOptions(SaveFormat.Doc));
        return base.File(docStream.ToArray(), "application/msword","Template.doc");
       本人的項目是基於mvc的,所以采用后者。
      首先項目需要對 aspose.word.dll進行添加引用, aspose.word.dll下載破解版的,版本過低會無法使用某些,如Aspose.Words.Saving等的相關屬性,就沒有SaveOptions.CreateSaveOptions方法,這個可以直接刪掉,對基本的導出功能沒有影響。之后將貼核心代碼,代碼都已經封裝好,只需調用,傳相關參數即可,后面解析代碼的功能。
      本人創建了一個WordHelper類,定義了公共屬性,因為只是當前類調用,所以設為了私有,調用首先需實例化模板,模板就是之前已經寫好的word模板,同時還寫了相應的方法轉化為可以接受中文值,比如性別是數據表里是bool類型,用false or true來代表男女,導出時則需轉化為對應的中文值:       
  1 /// <summary>
  2         /// 模板
  3         /// </summary>
  4         private string templateFile { get; set; }
  5         private Document doc { get; set; }
  6         private DocumentBuilder builder { get; set; }
  7         #region 實例化模板
  8         public WordHelper(string templateFile)
  9         {
 10             string templatePath = "Content/templates";
 11             if (Path.GetExtension(templateFile) != ".doc")    //如果傳的模板參數沒有擴展名,則加上擴展名
 12                 templateFile = templateFile + ".doc";
 13             templateFile = WordFilePath.GetFilePath(templatePath, templateFile); //獲取模板路徑
 14             doc = new Document(templateFile); //載入模板
 15             builder = new DocumentBuilder(doc);
 16         }
 17         #endregion
 18         #region 輸出文件流
 19         public MemoryStream DocStream
 20         {
 21             get
 22             {
 23                 var docStream = new MemoryStream();
 24                 doc.Save(docStream, SaveOptions.CreateSaveOptions(SaveFormat.Doc));
 25                 return docStream;
 26             }
 27         }
 28         #endregion 
 29         #region 轉化為對應的中文值
 30         /// <summary>
 31         /// 轉化為對應的中文值
 32         /// </summary>
 33         /// <param name="objName">值名稱</param>
 34         /// <param name="objValue">對應的值類型</param>
 35         /// <returns></returns>
 36         public static string SetChinaValue(object objName, object objValue)
 37         {
 38             object value = "";
 39             if (!string.IsNullOrEmpty(objValue.ToString()))
 40             {
 41                 if (Common.lstDictionaryCodes.Contains(objName)) //字典值
 42                 {
 43                     value = Common.GetDicName(Convert.ToInt32(objValue));
 44                 }
 45                 else if (Common.lstUserIDs.Contains(objName)) //人員檔案
 46                 {
 47                     string[] strValue = objValue.ToString().Split(',');
 48                     for (int i = 0; i < strValue.Length; i++)
 49                     {
 50                         value += Common.GetPersonName(strValue[i]) + ",";
 51                     }
 52                     value = !string.IsNullOrEmpty(value.ToString()) ? value.ToString().Substring(0, value.ToString().Length - 1) : "";
 53                 }
 54                 else if (objValue.GetType() == typeof(string))
 55                 {
 56                     value = objValue;
 57                 }
 58                 else if (objValue.GetType() == typeof(int) || objValue.GetType() == typeof(int?))
 59                 {
 60                     value = objValue;
 61                 }
 62                 else if (objValue.GetType() == typeof(DateTime) || objValue.GetType() == typeof(DateTime?))
 63                 {
 64                     value = Convert.ToDateTime(objValue).ToString("yyyy-MM-dd");
 65                 }
 66                 else if (objValue.GetType() == typeof(decimal) || objValue.GetType() == typeof(decimal?))
 67                 {
 68                     value = objValue;
 69                 }
 70                 else if (objValue.GetType() == typeof(bool) || objValue.GetType() == typeof(bool?))
 71                 {
 72                     if (objName.Equals("Sex"))
 73                     {
 74                         if (objValue.Equals(false))
 75                             value = "";
 76                         else
 77                             value = "";
 78                     }
 79                     else
 80                     {
 81                         if (objValue.Equals(true))
 82                             value = "☑是 □否";
 83                         else
 84                             value = "□是 ☑否";
 85                     }
 86                 }
 87             }
 88             return value.ToString();
 89         }
 90         #endregion
 91         #region 保存文件名
 92         /// <summary>
 93         /// 保存文件名
 94         /// </summary>
 95         /// <param name="name">姓名</param>
 96         /// <param name="value">編號</param>
 97         /// <returns></returns>
 98         public static string SaveDocName(string name, string value)
 99         {
100             string oDoc = "";
101             if (!string.IsNullOrEmpty(name))
102             {
103                 oDoc = name + "_" + value + ".doc";
104             }
105             else
106             {
107                 oDoc = DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".doc";
108             }
109             return oDoc;
110         }
111         #endregion
112         #region 保存合並后的文檔
113         public MemoryStream ExportDoc()
114         {
115             //保存合並后的文檔
116             var docStream = new MemoryStream();
117             doc.Save(docStream, SaveOptions.CreateSaveOptions(SaveFormat.Doc));
118             return docStream;
119         }
120         #endregion
121 
122         #region 通過DataTable導出基本信息
123         /// <summary>
124         /// 獲取導出文件的基本信息
125         /// </summary>
126         /// <param name="bllType">bll類</param>
127         /// <param name="dicWhere">查詢條件</param>
128         /// <returns></returns>
129         public void GetBasicInfo(Type bllType, Dictionary<string, string> dicWhere)
130         {
131             try
132             {
133                 NameValueCollection nvc = new NameValueCollection();
134                 foreach (var item in dicWhere)
135                 {
136                     if (!string.IsNullOrEmpty(item.Key))
137                     {
138                         nvc.Add(item.Key, item.Value);
139                     }
140                 }
141                 Assembly asmBLL = Assembly.Load(typeof(BLL.BLLBase).Namespace);
142                 BLL.IBLLBase ibllBase = (BLL.IBLLBase)asmBLL.CreateInstance(bllType.FullName);
143                 DataSet ds = ibllBase.GetData(nvc); //數據源
144                 DataTable dt = CreateNewTable(bllType, ds.Tables[0]);
145 
146                 doc.MailMerge.FieldMergingCallback = new HandleMergeFieldInsertDocument(); //圖片處理
147                 doc.MailMerge.Execute(dt); //合並模版,相當於頁面的渲染
148             }
149             catch (Exception)
150             {
151                 throw;
152             }
153         }
154         #endregion
155 
156         #region 通過二維數組獲取基本信息
157         /// <summary>
158         /// 通過二維數組獲取基本信息
159         /// </summary>
160         /// <param name="bllType">bll類</param>
161         /// <param name="templateFile">導出模板</param>
162         /// <param name="dicWhere">查詢條件</param>
163         /// <param name="lsField">導出的字段</param>
164         /// <returns></returns>
165         public void GetBasicInfo(Type bllType, Dictionary<string, string> dicWhere, List<string> lsField)
166         {
167             try
168             {
169                 decimal count = 0;
170                 NameValueCollection nvc = new NameValueCollection();
171                 foreach (var item in dicWhere)
172                 {
173                     if (!string.IsNullOrEmpty(item.Key))
174                     {
175                         nvc.Add(item.Key, item.Value);
176                     }
177                 }
178                 Assembly asmBLL = Assembly.Load(typeof(BLL.BLLBase).Namespace);
179                 BLL.IBLLBase ibllBase = (BLL.IBLLBase)asmBLL.CreateInstance(bllType.FullName);
180                 DataSet ds = ibllBase.GetData(nvc); //數據源
181 
182                 String[] arrNames = lsField.ToArray();
183                 Object[] objValues = new Object[arrNames.Length];
184 
185                 for (int j = 0; j < arrNames.Length; j++)
186                 {
187                     if (ds.Tables[0].Rows.Count > 0)                 
188                             objValues[j] = SetChinaValue(arrNames[j], ds.Tables[0].Rows[0][arrNames[j]]); 
189                   else                  
190                         objValues[j] = "";
191                 }
192                 doc.MailMerge.Execute(arrNames, objValues); //合並模版,相當於頁面的渲染
193             }
194             catch (Exception)
195             {
196                 throw;
197             }
198         }
199         #endregion 
200 
201         #region 通過域循環導出table列表
202         /// <summary>
203         /// 通過域循環導出table列表
204         /// </summary>
205         /// <param name="bllType">bll類</param>
206         /// <param name="dicWhere">查詢條件</param>
207         /// <param name="bookmark">模板書簽</param>
208         public void GetTableList(Type bllType, Dictionary<string, string> dicWhere, string bookmark)
209         {
210             NameValueCollection nvc = new NameValueCollection();
211             foreach (var item in dicWhere)
212             {
213                 if (!string.IsNullOrEmpty(item.Key))
214                 {
215                     nvc.Add(item.Key, item.Value);
216                 }
217             }
218             Assembly asmBLL = Assembly.Load(typeof(BLL.BLLBase).Namespace);
219             BLL.IBLLBase ibllBase = (BLL.IBLLBase)asmBLL.CreateInstance(bllType.FullName);
220             DataSet ds = ibllBase.GetData(nvc); //數據源
221             DataTable dt = CreateNewTable(bllType, ds.Tables[0], bookmark);
222 
223             //合並模版,相當於頁面的渲染
224             doc.MailMerge.ExecuteWithRegions(dt);
225         }
226         #endregion 
227        #region 通過書簽來循環導出數據列表
228         /// <summary>
229         /// 通過書簽來循環導出數據列表
230         /// </summary>
231         /// <param name="bllType">bll類</param>
232         /// <param name="dicWhere">查詢條件</param>
233         /// <param name="dicOrderby">排序條件</param>
234         /// <param name="bookmark">模板循環列表書簽</param>
235         public void GetListByMark(Type bllType, Dictionary<string, string> dicWhere, Dictionary<string, string> dicOrderby, string bookmark)
236         {
237             NameValueCollection nvc = new NameValueCollection();
238             foreach (var item in dicWhere)
239             {
240                 if (!string.IsNullOrEmpty(item.Key))
241                 {
242                     nvc.Add(item.Key, item.Value);
243                 }
244             }
245             NameValueCollection orderby = new NameValueCollection();
246             foreach (var item in dicOrderby) //查詢條件
247             {
248                 if (!string.IsNullOrEmpty(item.Key))
249                 {
250                     orderby.Add(item.Key, item.Value);
251                 }
252             }
253 
254             Assembly asmBLL = Assembly.Load(typeof(BLL.BLLBase).Namespace);
255             BLL.IBLLBase ibllBase = (BLL.IBLLBase)asmBLL.CreateInstance(bllType.FullName);
256             DataTable dt = ibllBase.GetData(nvc, orderby).Tables[0]; //數據源
257 
258             int count = 0;
259             //記錄要顯示多少列           
260             for (var i = 0; i < dt.Columns.Count; i++)
261             {
262                 string strMark = dt.Columns[i].ColumnName.Trim();
263                 if (doc.Range.Bookmarks[strMark] != null)
264                 {
265                     Bookmark mark = doc.Range.Bookmarks[strMark];
266                     mark.Text = "";
267                     count++;
268                 }
269             }
270             List<string> listcolumn = new List<string>(count);
271             for (var i = 0; i < count; i++)
272             {
273                 builder.MoveToCell(0, 0, i, 0); //移動單元格
274                 if (builder.CurrentNode.NodeType == NodeType.BookmarkStart)
275                 {
276                     listcolumn.Add((builder.CurrentNode as BookmarkStart).Name);
277                 }
278             }
279             double width = builder.CellFormat.Width;//獲取單元格寬度
280             if (doc.Range.Bookmarks[bookmark] != null)
281             {
282                 builder.MoveToBookmark(bookmark);        //開始添加值
283                 for (var m = 0; m < dt.Rows.Count; m++)
284                 {
285                     for (var i = 0; i < listcolumn.Count; i++)
286                     {
287                         builder.InsertCell();            // 添加一個單元格                    
288                         builder.CellFormat.Borders.LineStyle = LineStyle.Single;
289                         builder.CellFormat.Borders.Color = System.Drawing.Color.Black;
290                         builder.CellFormat.Width = width;
291                         builder.CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.None;
292                         builder.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;//垂直居中對齊
293                         builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;//水平居中對齊
294                         builder.Write(dt.Rows[m][listcolumn[i]].ToString());
295                     }
296                     builder.EndRow();
297                 }
298                 doc.Range.Bookmarks[bookmark].Text = "";
299             }
300         }
301         #endregion
302 
303         #region 創建DataTable,存放處理后的值進新的DataTable里
304         /// <summary>
305         /// 創建datatable
306         /// </summary>
307         /// <param name="dt">數據源</param>
308         /// <param name="bookmark">模板列表書簽</param>
309         /// <returns></returns>
310         private DataTable CreateNewTable(Type t, DataTable dt, string bookmark = null)
311         {
312             DataTable TableList = new DataTable();
313             if (!string.IsNullOrEmpty(bookmark))
314             {
315                 TableList.TableName = bookmark;
316             }
317             string strMark = "";
318             List<string> lsMark = new List<string>();
319             for (var i = 0; i < dt.Columns.Count; i++)
320             {
321                 strMark = dt.Columns[i].ColumnName.Trim();
322                 TableList.Columns.Add(strMark);
323                 //if (doc.Range.Bookmarks[strMark] != null) //按書簽添加到新表
324                 //{
325                 //    Bookmark mark = doc.Range.Bookmarks[strMark];
326                 //    mark.Remove();
327                 //    TableList.Columns.Add(strMark);
328                 //    lsMark.Add(strMark);
329                 //}
330             }
331 
332             if (dt.Rows.Count > 0)
333             {
334                 for (int i = 0; i < dt.Rows.Count; i++)
335                 {
336                     DataRow dr = TableList.NewRow();
337                     for (int j = 0; j < dt.Columns.Count; j++)
338                     {
339                         dr[j] = SetChinaValue(dt.Columns[j].ColumnName, dt.Rows[i][j]);
340                     }
341                     TableList.Rows.Add(dr);
342                 }
343             }
344             else //沒有值時,直接賦值為"",去掉文檔里的域值
345             {
346                 DataRow dr = TableList.NewRow();
347                 for (int j = 0; j < dt.Columns.Count; j++)
348                 {
349                     if (t.Name == "PrejobTraining") //崗前培訓為空時
350                     {
351                         dr[j] = "□是 □否";
352                     }
353                     else
354                     {
355                         dr[j] = "";
356                     }
357                 }
358                 TableList.Rows.Add(dr);
359             }
360             return TableList;
361         }
362         #endregion
363     }
364     #endregion 
WordHelper

   其它相關輔助類:
   HandleMergeFieldInsertDocument 類   

 1 #region 導出Word處理圖片
 2     /// <summary>
 3     /// 導出Word處理圖片
 4     /// </summary>
 5     public class HandleMergeFieldInsertDocument : IFieldMergingCallback
 6     {
 7         //文本處理在這里,如果寫在這一塊,則不起作用
 8         void IFieldMergingCallback.FieldMerging(FieldMergingArgs e)
 9         {
10         }
11         //圖片處理在這里
12         void IFieldMergingCallback.ImageFieldMerging(ImageFieldMergingArgs args)
13         {
14             if (args.DocumentFieldName.Equals("Photo"))
15             {
16                 // 使用DocumentBuilder處理圖片的大小
17                 DocumentBuilder builder = new DocumentBuilder(args.Document);
18                 builder.MoveToMergeField(args.FieldName);
19                 if (!string.IsNullOrEmpty((string)args.FieldValue))
20                 {
21                     string argsPath = HttpContext.Current.Server.MapPath(args.FieldValue.ToString());
22                     if (System.IO.File.Exists(argsPath)) //找到文件才添加
23                     {
24                         Shape shape = builder.InsertImage(argsPath);
25                         // 設置x,y坐標和高寬.
26                         shape.Left = 0;
27                         shape.Top = 0;
28                         shape.Width = 80;
29                         shape.Height = 120;
30                     }
31                 }
32             }
33         }
34     }
35     #endregion 
HandleMergeFieldInsertDocument

     


免責聲明!

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



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