C# 导出word文档及批量导出word文档(2)
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了C# 导出word文档及批量导出word文档(2),小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含12581字,纯文字阅读大概需要18分钟。
内容图文
aspose.word主要是通过把读取出来的数据放到datatable里,在datable里做相应的格式的调整,再导出到word文档里。mvc和webform最后导出的语句略有不同,在mvc的controller,用的是base.File,对应的是FileContentResult,在webform里用的是Response。写法分别为:
本人创建了一个WordHelper类,定义了公共属性,因为只是当前类调用,所以设为了私有,调用首先需实例化模板,模板就是之前已经写好的word模板,同时还写了相应的方法转化为可以接受中文值,比如性别是数据表里是bool类型,用false or true来代表男女,导出时则需转化为对应的中文值:
1///<summary> 2/// 模板 3///</summary> 4privatestring templateFile { get; set; } 5private Document doc { get; set; } 6private DocumentBuilder builder { get; set; } 7#region 实例化模板 8public WordHelper(string templateFile) 9 { 10string templatePath = "Content/templates"; 11if (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 输出文件流 19public MemoryStream DocStream 20 { 21get 22 { 23var docStream = new MemoryStream(); 24 doc.Save(docStream, SaveOptions.CreateSaveOptions(SaveFormat.Doc)); 25return 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> 36publicstaticstring SetChinaValue(object objName, object objValue) 37 { 38object value = ""; 39if (!string.IsNullOrEmpty(objValue.ToString())) 40 { 41if (Common.lstDictionaryCodes.Contains(objName)) //字典值 42 { 43 value = Common.GetDicName(Convert.ToInt32(objValue)); 44 } 45elseif (Common.lstUserIDs.Contains(objName)) //人员档案 46 { 47string[] strValue = objValue.ToString().Split(‘,‘); 48for (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 } 54elseif (objValue.GetType() == typeof(string)) 55 { 56 value = objValue; 57 } 58elseif (objValue.GetType() == typeof(int) || objValue.GetType() == typeof(int?)) 59 { 60 value = objValue; 61 } 62elseif (objValue.GetType() == typeof(DateTime) || objValue.GetType() == typeof(DateTime?)) 63 { 64 value = Convert.ToDateTime(objValue).ToString("yyyy-MM-dd"); 65 } 66elseif (objValue.GetType() == typeof(decimal) || objValue.GetType() == typeof(decimal?)) 67 { 68 value = objValue; 69 } 70elseif (objValue.GetType() == typeof(bool) || objValue.GetType() == typeof(bool?)) 71 { 72if (objName.Equals("Sex")) 73 { 74if (objValue.Equals(false)) 75 value = "男"; 76else 77 value = "女"; 78 } 79else 80 { 81if (objValue.Equals(true)) 82 value = "?是 □否"; 83else 84 value = "□是 ?否"; 85 } 86 } 87 } 88return 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> 98publicstaticstring SaveDocName(string name, string value) 99 { 100string oDoc = ""; 101if (!string.IsNullOrEmpty(name)) 102 { 103 oDoc = name + "_" + value + ".doc"; 104 } 105else106 { 107 oDoc = DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".doc"; 108 } 109return oDoc; 110 } 111#endregion112#region 保存合并后的文档 113public MemoryStream ExportDoc() 114 { 115//保存合并后的文档116var docStream = new MemoryStream(); 117 doc.Save(docStream, SaveOptions.CreateSaveOptions(SaveFormat.Doc)); 118return docStream; 119 } 120#endregion121122#region 通过DataTable导出基本信息 123///<summary>124/// 获取导出文件的基本信息 125///</summary>126///<param name="bllType">bll类</param>127///<param name="dicWhere">查询条件</param>128///<returns></returns>129publicvoid GetBasicInfo(Type bllType, Dictionary<string, string> dicWhere) 130 { 131try132 { 133 NameValueCollection nvc = new NameValueCollection(); 134foreach (var item in dicWhere) 135 { 136if (!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]); 145146 doc.MailMerge.FieldMergingCallback = new HandleMergeFieldInsertDocument(); //图片处理147 doc.MailMerge.Execute(dt); //合并模版,相当于页面的渲染148 } 149catch (Exception) 150 { 151throw; 152 } 153 } 154#endregion155156#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>165publicvoid GetBasicInfo(Type bllType, Dictionary<string, string> dicWhere, List<string> lsField) 166 { 167try168 { 169decimal count = 0; 170 NameValueCollection nvc = new NameValueCollection(); 171foreach (var item in dicWhere) 172 { 173if (!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); //数据源181182 String[] arrNames = lsField.ToArray(); 183 Object[] objValues = new Object[arrNames.Length]; 184185for (int j = 0; j < arrNames.Length; j++) 186 { 187if (ds.Tables[0].Rows.Count > 0) 188 objValues[j] = SetChinaValue(arrNames[j], ds.Tables[0].Rows[0][arrNames[j]]); 189else190 objValues[j] = ""; 191 } 192 doc.MailMerge.Execute(arrNames, objValues); //合并模版,相当于页面的渲染193 } 194catch (Exception) 195 { 196throw; 197 } 198 } 199#endregion200201#region 通过域循环导出table列表 202///<summary>203/// 通过域循环导出table列表 204///</summary>205///<param name="bllType">bll类</param>206///<param name="dicWhere">查询条件</param>207///<param name="bookmark">模板书签</param>208publicvoid GetTableList(Type bllType, Dictionary<string, string> dicWhere, string bookmark) 209 { 210 NameValueCollection nvc = new NameValueCollection(); 211foreach (var item in dicWhere) 212 { 213if (!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); 222223//合并模版,相当于页面的渲染224 doc.MailMerge.ExecuteWithRegions(dt); 225 } 226#endregion227#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>235publicvoid GetListByMark(Type bllType, Dictionary<string, string> dicWhere, Dictionary<string, string> dicOrderby, string bookmark) 236 { 237 NameValueCollection nvc = new NameValueCollection(); 238foreach (var item in dicWhere) 239 { 240if (!string.IsNullOrEmpty(item.Key)) 241 { 242 nvc.Add(item.Key, item.Value); 243 } 244 } 245 NameValueCollection orderby = new NameValueCollection(); 246foreach (var item in dicOrderby) //查询条件247 { 248if (!string.IsNullOrEmpty(item.Key)) 249 { 250orderby.Add(item.Key, item.Value); 251 } 252 } 253254 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]; //数据源257258int count = 0; 259//记录要显示多少列 260for (var i = 0; i < dt.Columns.Count; i++) 261 { 262string strMark = dt.Columns[i].ColumnName.Trim(); 263if (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); 271for (var i = 0; i < count; i++) 272 { 273 builder.MoveToCell(0, 0, i, 0); //移动单元格274if (builder.CurrentNode.NodeType == NodeType.BookmarkStart) 275 { 276 listcolumn.Add((builder.CurrentNode as BookmarkStart).Name); 277 } 278 } 279double width = builder.CellFormat.Width;//获取单元格宽度280if (doc.Range.Bookmarks[bookmark] != null) 281 { 282 builder.MoveToBookmark(bookmark); //开始添加值283for (var m = 0; m < dt.Rows.Count; m++) 284 { 285for (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#endregion302303#region 创建DataTable,存放处理后的值进新的DataTable里 304///<summary>305/// 创建datatable 306///</summary>307///<param name="dt">数据源</param>308///<param name="bookmark">模板列表书签</param>309///<returns></returns>310private DataTable CreateNewTable(Type t, DataTable dt, string bookmark = null) 311 { 312 DataTable TableList = new DataTable(); 313if (!string.IsNullOrEmpty(bookmark)) 314 { 315 TableList.TableName = bookmark; 316 } 317string strMark = ""; 318 List<string> lsMark = new List<string>(); 319for (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 } 331332if (dt.Rows.Count > 0) 333 { 334for (int i = 0; i < dt.Rows.Count; i++) 335 { 336 DataRow dr = TableList.NewRow(); 337for (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 } 344else//没有值时,直接赋值为"",去掉文档里的域值345 { 346 DataRow dr = TableList.NewRow(); 347for (int j = 0; j < dt.Columns.Count; j++) 348 { 349if (t.Name == "PrejobTraining") //岗前培训为空时350 { 351 dr[j] = "□是 □否"; 352 } 353else354 { 355 dr[j] = ""; 356 } 357 } 358 TableList.Rows.Add(dr); 359 } 360return TableList; 361 } 362#endregion363 } 364#endregion
其它相关辅助类:
HandleMergeFieldInsertDocument 类
1 #region 导出Word处理图片 2///<summary> 3/// 导出Word处理图片 4///</summary> 5publicclass HandleMergeFieldInsertDocument : IFieldMergingCallback 6 { 7//文本处理在这里,如果写在这一块,则不起作用 8void IFieldMergingCallback.FieldMerging(FieldMergingArgs e) 9 { 10 } 11//图片处理在这里12void IFieldMergingCallback.ImageFieldMerging(ImageFieldMergingArgs args) 13 { 14if (args.DocumentFieldName.Equals("Photo")) 15 { 16// 使用DocumentBuilder处理图片的大小17 DocumentBuilder builder = new DocumentBuilder(args.Document); 18 builder.MoveToMergeField(args.FieldName); 19if (!string.IsNullOrEmpty((string)args.FieldValue)) 20 { 21string argsPath = HttpContext.Current.Server.MapPath(args.FieldValue.ToString()); 22if (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
原文:http://www.cnblogs.com/jingshuisihan/p/4604278.html
内容总结
以上是互联网集市为您收集整理的C# 导出word文档及批量导出word文档(2)全部内容,希望文章能够帮你解决C# 导出word文档及批量导出word文档(2)所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。