.net使用Aspose.Words进行Word替换操作的实现代码
DLL文件下载
示例:
Aspose.Words.Document doc = new Aspose.Words.Document(TempFile); Aspose.Words.DocumentBuilder builder = new Aspose.Words.DocumentBuilder(doc); //首先替换标签和图片内容 for (int i = 0; i < doc.Range.Bookmarks.Count; i++) { string name = doc.Range.Bookmarks[i].Name; if (pDic.ContainsKey(name)) { if (name != "vPic2" && name != "vPic1") { doc.Range.Bookmarks[i].Text = pDic[name]; } } else { doc.Range.Bookmarks[i].Text = ""; } } NodeCollection allTables = doc.GetChildNodes(NodeType.Table, true); //按照模板目前只有2个表格,第一个表格为第一页右上脚,其它为一个大表格 //填写表格数据必须先空白一行,拷贝数据然后再删除当前行 Aspose.Words.Tables.Table table = allTables[1] as Aspose.Words.Tables.Table; #region 生产线基本信息 for (var i = 0; i < dtA2.Rows.Count; i++) { Row roww = table.Rows[pSCXJBXX]; Row row1 = (Row)roww.Clone(true); //拷贝行 table.Rows.Insert(pSCXJBXX, row1); //将复制的行插入当前行的上方 for (var j = 0; j < dtA2.Columns.Count; j++) { Cell c = row1.Cells[j]; Paragraph p = new Paragraph(doc); p.AppendChild(new Run(doc, dtA2.Rows[i][j].ToString())); p.ParagraphFormat.Style.Font.Size = 12; p.ParagraphFormat.Style.Font.Name = "仿宋"; row1.Cells[j].FirstParagraph.Remove(); row1.Cells[j].AppendChild(p); row1.Cells[j].Remove(); row1.Cells.Insert(j, c); } pSCXJBXX += 1; pCWZYSCGY += 1; pWRZLGY += 1; pZXBZ += 1; pWRFFCC += 1; pWRWPWQX += 1; //pJCXXGK += 1; } table.Rows.RemoveAt(pSCXJBXX); //合并单元格 int pIndexCount = pZXBZ - dtA3.Rows.Count; int pPreIndex = pIndexCount + 1; string str1 = ""; string str2 = ""; for (int i = pPreIndex; i < pZXBZ; i++) { Row row1 = table.Rows[pIndexCount]; Row row2 = table.Rows[i]; str1 = row1.Cells[1].GetText(); str2 = row2.Cells[1].GetText(); if (str1 == str2) { table.Rows[pIndexCount].Cells[0].CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.First; table.Rows[i].Cells[0].CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.Previous; table.Rows[pIndexCount].Cells[1].CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.First; table.Rows[i].Cells[1].CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.Previous; table.Rows[pIndexCount].Cells[2].CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.First; table.Rows[i].Cells[2].CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.Previous; } else { pIndexCount = i; } }
//文字居中 row1.Cells[0].CellFormat.VerticalAlignment = CellVerticalAlignment.Center;
操作类:
using Aspose.Words; using Aspose.Words.Drawing; using Aspose.Words.Tables; using DAL.BaseData; using Model; using System; using System.Collections.Generic; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Web; namespace Publish.Supervised.Admin.Ajax { /// <summary> /// ExportHandDataInfo 的摘要说明 /// 导出监督性监测手工数据 /// 2017-08-01 @ /// </summary> public class ExportHandDataInfo : IHttpHandler { public void ProcessRequest(HttpContext context) { //context.Response.ContentType = "text/plain"; //context.Response.Write("Hello World"); string strUnitID = context.Request["id"]; List<Pub_MNHandExtInfo> listhand = new T_P_MNHandInfoDAL().GetPub_MNHandDataList(strUnitID, null, 2);//.GetByFilter(string.Format(" MNStandItemID in ({0})", strStandItemID.TrimEnd(','))); if (listhand == null || listhand.Count < 1) { context.Response.Write("0"); return; } string strFilePath = @"\Publish\Upload\doc\"; string strFileName = "监督性监测手工数据模版"; string strDocSuffix = ".doc"; string strPDFSuffix = ".pdf"; string strSavePath = @"\Publish\Upload\PDFExport\"; string strDownPath = strSavePath + strFileName + strPDFSuffix;//下载路径 #region 1、加载模版 string strPath = context.Server.MapPath(strFilePath + strFileName + strDocSuffix); Aspose.Words.Document doc = new Aspose.Words.Document(strPath); #endregion List<AsposePDFModel> listModel = new List<AsposePDFModel>(); AsposePDFModel item = new AsposePDFModel(); item.MarkName = "导出日期"; item.MarkMemo =DateTime.Now.ToString("yyyy年MM月dd日"); listModel.Add(item); DataTable dtYHP = AsposePDFHelper.CreateTableColumns("企业名称,行政区,监测点名称,监测日期,监测项目名称,监测指标浓度,排放标准限制,排放单位,是否达标,超标倍数,备注"); //DataRow rowhead = dtYHP.NewRow(); //rowhead = dtYHP.NewRow(); //rowhead["企业名称"] = "企业名称"; //rowhead["行政区"] = "行政区"; //rowhead["监测点名称"] = "监测点名称"; //rowhead["监测日期"] = "监测日期"; //rowhead["监测项目名称"] = "监测项目名称"; //rowhead["监测指标浓度"] = "监测指标浓度"; //rowhead["排放标准限制"] = "排放标准限制"; //rowhead["排放单位"] = "排放单位"; //rowhead["是否达标"] = "是否达标"; //rowhead["超标倍数"] = "超标倍数"; //rowhead["备注"] = "备注"; //dtYHP.Rows.Add(rowhead); #region 中间多行记录 for (int i = 0; i < listhand.Count; i++) { Pub_MNHandExtInfo ext = listhand[i]; DataRow row = dtYHP.NewRow(); row = dtYHP.NewRow(); row["企业名称"] = ext.UnitsName; row["行政区"] = ext.AreaName; row["监测点名称"] = ext.MPointName; row["监测日期"] = ext.MonitorTime == null ? "" : ext.MonitorTime.ToString("yyyy-MM-dd"); row["监测项目名称"] = ext.ParamName; row["监测指标浓度"] = ext.ActualValue == null ? "" : ext.ActualValue.ToString(); row["排放标准限制"] = ext.ItemMinValue + "" + ext.ItemMaxValue; row["排放单位"] = ext.ItemValueUnit; row["是否达标"] =""; row["超标倍数"] =""; row["备注"] = ext.Remarks; dtYHP.Rows.Add(row); } doc = AsposePDFHelper.AddDocumentTableInfo(doc, dtYHP, "测试", 0, 0, 11); #endregion doc = AsposePDFHelper.AddDocumentMarkInfo(doc, listModel); strSavePath = context.Server.MapPath(strSavePath + strFileName + strPDFSuffix); doc.Save(strSavePath, SaveFormat.Pdf); context.Response.Write(strDownPath); } public bool IsReusable { get { return false; } } } /// <summary> /// http://www.cnblogs.com/wuhuacong/archive/2012/08/30/2662961.html /// AsposePDF基础操作类 /// 2015-12-15 @ /// /// http://www.jb51.net/article/23065.htm /// 文档添加页脚 /// </summary> public class AsposePDFHelper { public AsposePDFHelper() { } /// <summary> /// 根据书签设置替换值,返回doc内容 /// </summary> /// <param name="doc">新建doc</param> /// <param name="listPDF">书签内容列表</param> /// <returns></returns> public static Aspose.Words.Document AddDocumentMarkInfo(Aspose.Words.Document doc, List<AsposePDFModel> listPDF) { if (listPDF == null || listPDF.Count < 1) return null; for (int i = 0; i < listPDF.Count; i++) { AsposePDFModel temp = listPDF[i]; if (doc.Range.Bookmarks[temp.MarkName] != null)//查找书签 { Bookmark mark = doc.Range.Bookmarks[temp.MarkName]; mark.Text = temp.MarkMemo == null ? "" : temp.MarkMemo;//设置书签值 } } return doc; } /// <summary> /// 添加datatable内容到doc中 /// </summary> /// <param name="doc">Aspose.Words.Document</param> /// <param name="TableInfo">DataTable内容</param> /// <param name="TableMarkName">放置表格内容的书签名称</param> /// <param name="TableIndex">表序号,起始值 = 0</param> /// <param name="RowIndex">行序号,起始值 = 0</param> /// <param name="ColumnIndex">列总数,最小值 = 1</param> /// <returns></returns> public static Aspose.Words.Document AddDocumentTableInfo(Aspose.Words.Document doc, DataTable TableInfo, string TableMarkName, int TableIndex, int RowIndex, int ColumnIndex, ParagraphAlignment CellAlignment = ParagraphAlignment.Center) { Aspose.Words.DocumentBuilder builder = new Aspose.Words.DocumentBuilder(doc); List<double> widthList = new List<double>(); if (ColumnIndex == 1) { double width = builder.CellFormat.PreferredWidth.Value;//获取单元格宽度 widthList.Add(width); } else { for (int i = 0; i < ColumnIndex; i++) { builder.MoveToCell(TableIndex, RowIndex, i, 0); //移动单元格 double width = builder.CellFormat.Width;//获取单元格宽度 widthList.Add(width); } } builder.MoveToBookmark(TableMarkName); //开始添加值 Aspose.Words.Tables.Table table = builder.StartTable(); builder.RowFormat.HeadingFormat = true; builder.ParagraphFormat.Alignment = ParagraphAlignment.Center; if (doc.Range.Bookmarks[TableMarkName] != null) { for (int r = 0; r < TableInfo.Rows.Count; r++) { for (int c = 0; c < TableInfo.Columns.Count; c++) { builder.InsertCell();// 添加一个单元格 builder.CellFormat.Borders.Bottom.LineStyle = LineStyle.Single; builder.CellFormat.Borders.Bottom.Color = System.Drawing.Color.Black; builder.CellFormat.Width = widthList[c]; builder.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;//垂直居中对齐 builder.ParagraphFormat.Alignment = CellAlignment;//水平居中对齐 builder.CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.None; builder.Write(TableInfo.Rows[r][c].ToString()); } builder.EndRow(); } builder.EndTable(); } return doc; } /// <summary> /// 添加datatable内容到doc中 /// </summary> /// <param name="doc">Aspose.Words.Document</param> /// <param name="TableInfo">DataTable内容</param> /// <param name="TableMarkName">放置表格内容的书签名称</param> /// <param name="TableIndex">表序号,起始值 = 0</param> /// <param name="RowIndex">行序号,起始值 = 0</param> /// <param name="ColumnIndex">列总数,最小值 = 1</param> /// <param name="listColumnWidth">列总数,最小值 = 1</param> /// <returns></returns> public static Aspose.Words.Document AddDocumentTableInfo(Aspose.Words.Document doc, DataTable TableInfo, string TableMarkName, int TableIndex, int RowIndex, int ColumnIndex, List<double> listColumnWidth, ParagraphAlignment CellAlignment = ParagraphAlignment.Center) { Aspose.Words.DocumentBuilder builder = new Aspose.Words.DocumentBuilder(doc); List<double> widthList = new List<double>(); for (int i = 0; i < ColumnIndex; i++) { //builder.MoveToCell(TableIndex, RowIndex, i, 0); //移动单元格 //double width = builder.CellFormat.Width;//获取单元格宽度 widthList.Add(listColumnWidth[i]); } builder.MoveToBookmark(TableMarkName); //开始添加值 Aspose.Words.Tables.Table table = builder.StartTable(); builder.RowFormat.HeadingFormat = true; builder.ParagraphFormat.Alignment = ParagraphAlignment.Center; if (doc.Range.Bookmarks[TableMarkName] != null) { for (int r = 0; r < TableInfo.Rows.Count; r++) { for (int c = 0; c < TableInfo.Columns.Count; c++) { builder.InsertCell();// 添加一个单元格 builder.CellFormat.Borders.Bottom.LineStyle = LineStyle.Single; builder.CellFormat.Borders.Bottom.Color = System.Drawing.Color.Black; //builder.CellFormat.Borders.Right.Color = System.Drawing.Color.White; builder.CellFormat.Width = widthList[c]; builder.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;//垂直居中对齐 builder.ParagraphFormat.Alignment = CellAlignment;//水平居中对齐 builder.CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.None; builder.Write(TableInfo.Rows[r][c].ToString()); } builder.EndRow(); } builder.EndTable(); } return doc; } /// <summary> /// 创建表,并根据传值添加列名 /// 2015-12-15 @ /// </summary> /// <param name="ColumnInfo">添加表列,格式:列1,列2,列3</param> /// <returns></returns> public static DataTable CreateTableColumns(string ColumnInfo) { if (string.IsNullOrEmpty(ColumnInfo)) return null; string[] strLine = ColumnInfo.Split(','); DataTable dt = new DataTable(); DataColumn col = null; for (int i = 0; i < strLine.Length; i++) { string line = strLine[i]; if (!dt.Columns.Contains(line)) { col = dt.Columns.Add(line); } } return dt; } /// <summary> /// 灵活创建表格 /// </summary> /// <param name="doc">Document对象</param> /// <param name="MarkName">书签名称</param> /// <param name="listCell">单元格行列List</param> /// <param name="iTableIndex">表格序号,从0开始</param> /// <param name="iRowIndex">行序号</param> /// <param name="iCellIndex">列序号</param> /// <param name="iCharacterIndex">字符序号</param> public static void CreateDocBuilder(Document doc, string MarkName, List<AsposeBuilderCellModel> listCell, int iTableIndex, int iRowIndex, int iCellIndex, int iCharacterIndex) { DocumentBuilder builder = new DocumentBuilder(doc); //builder.MoveToCell(1,2, 0, 0);//第一个表格,第三行,第0列,第0字符 builder.MoveToCell(iTableIndex, iRowIndex, iCellIndex, iCharacterIndex); double cellWidth = builder.CellFormat.Width; builder.MoveToBookmark(MarkName); for (int i = 0; i < listCell.Count; i++) { AsposeBuilderCellModel model = listCell[i]; builder.InsertCell();//开始插入行 builder.CellFormat.Width = cellWidth;//宽度 builder.CellFormat.Borders.Bottom.LineStyle = LineStyle.Single; builder.CellFormat.Borders.Bottom.Color = System.Drawing.Color.Black; //设置整个背景色 //Shading shading = builder.ParagraphFormat.Shading; //shading.BackgroundPatternColor = System.Drawing.Color.Silver; //设置单行背景颜色 Shading shadingCell = builder.CellFormat.Shading; shadingCell.BackgroundPatternColor = model.CellBackgroundColor; builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;//水平居中对齐 builder.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;//垂直居中对齐 if (model.MergeType)//行合并还是列合并 builder.CellFormat.HorizontalMerge = model.MergeMethod; else builder.CellFormat.VerticalMerge = model.MergeMethod; builder.Write(model.TextValue);//写入单元格内容 if (model.IsEndCell)//是否最后列,并结束 builder.EndRow(); } } /// <summary> /// 添加页脚打印时间 /// 2016-10-25 @ /// </summary> /// <param name="doc"></param> /// <param name="TypeInfo"></param> public static void AddDocHeaderOrFooter(Document doc, HeaderFooterType TypeInfo = HeaderFooterType.FooterPrimary) { DocumentBuilder builder = new DocumentBuilder(doc); builder.MoveToHeaderFooter(TypeInfo); //上边框 Border topBorder = builder.CellFormat.Borders[BorderType.Top]; topBorder.LineStyle = LineStyle.Single; topBorder.LineWidth = 1; //下边框 Border bottomBorder = builder.CellFormat.Borders[BorderType.Bottom]; bottomBorder.LineStyle = LineStyle.None; //左边框 Border leftBorder = builder.CellFormat.Borders[BorderType.Left]; leftBorder.LineStyle = LineStyle.None; //右边框 Border rightBorder = builder.CellFormat.Borders[BorderType.Right]; rightBorder.LineStyle = LineStyle.None; //第一列 builder.InsertCell(); //builder.CellFormat.Width = 3 * 72;//单列的宽度 builder.Write(string.Format("打印时间: {0}", DateTime.Today.ToLongDateString())); builder.ParagraphFormat.Alignment = ParagraphAlignment.Right;//显示位置 //第二列 //builder.InsertCell(); //builder.ParagraphFormat.Alignment = ParagraphAlignment.Right; //builder.Write("版本 V3.00"); builder.EndRow(); builder.EndTable(); } /// <summary> /// 插入图片 /// 根据指定的书签位置进行插入 /// 2016-10-25 @ /// </summary> /// <param name="doc"></param> /// <param name="strMarkName">书签名称</param> /// <param name="strImagePath">图片的路径</param> public static void AddImage(Document doc, string strMarkName, string strImagePath, double imgcellwidth = 150, double imgcellheight = 150) { DocumentBuilder builder = new DocumentBuilder(doc); //向此单元格中插入图片 Shape shape = new Shape(doc, ShapeType.Image); shape.ImageData.SetImage(strImagePath); shape.Width = imgcellwidth - 2; shape.Height = imgcellheight; shape.HorizontalAlignment = HorizontalAlignment.Left; CompositeNode node = shape.ParentNode; //把此图片移动到那个单元格中 //builder.MoveToCell(8, 1, 1, 0);//通过指定的表、行、列进行定位 builder.MoveToBookmark(strMarkName);//通过书签直接定位 builder.InsertNode(shape); } /// <summary> /// 插入图片 /// 根据指定的表序号、行序号、列序号进行图片插入 /// 2016-10-25 @ /// </summary> /// <param name="doc"></param> /// <param name="TableIndex">表序号</param> /// <param name="RowIndex">行序号</param> /// <param name="ColumnIndex">列序号</param> /// <param name="imgcellwidth">宽度</param> /// <param name="imgcellheight">高度</param> public static void AddImage(Document doc, string strImagePath, int TableIndex, int RowIndex, int ColumnIndex, double imgcellwidth = 150, double imgcellheight = 150) { DocumentBuilder builder = new DocumentBuilder(doc); //向此单元格中插入图片 Shape shape = new Shape(doc, ShapeType.Image); shape.ImageData.SetImage(strImagePath); shape.Width = imgcellwidth - 2; shape.Height = imgcellheight; shape.HorizontalAlignment = HorizontalAlignment.Left; CompositeNode node = shape.ParentNode; //把此图片移动到那个单元格中 builder.MoveToCell(TableIndex, RowIndex, ColumnIndex, 0);//通过指定的表、行、列进行定位 builder.InsertNode(shape); } } public class AsposePDFModel { /// <summary> /// word书签名称 /// </summary> public string MarkName { get; set; } /// <summary> /// 书签内容 /// </summary> public string MarkMemo { get; set; } protected string _type = "1"; /// <summary> /// 类型 1 = 文本(默认值) 2 = 图片 /// </summary> public string MartType { get { return _type; } set { value = _type; } } } public class AsposeBuilderCellModel { /// <summary> /// 合并类型 /// true 行合并 用HorizontalMerge; /// false 列合并 用VerticalMerge /// </summary> public bool MergeType { get; set; } /// <summary> /// 合并方法 None,First,Previous /// </summary> public CellMerge MergeMethod { get; set; } /// <summary> /// 单元格内容 /// </summary> public string TextValue { get; set; } /// <summary> /// 是否结束列(最后一列) /// </summary> public bool IsEndCell { get; set; } private Color _CellBackgroundColor = Color.White; /// <summary> /// 设置行背景色 /// </summary> public Color CellBackgroundColor { get { return _CellBackgroundColor; } set { _CellBackgroundColor = value; } } //public Color CellBackgroundColor //{ // get; // set; //} } }
经典示例:
namespace WordOut { public class Program { public static void Main(string strServerMapPath)//string[] args { var dic = new Dictionary<string, string>(); dic.Add("姓名", "张三"); dic.Add("学历", "本科"); dic.Add("联系方式", "02759597666"); dic.Add("邮箱", "123456789@qq.com"); dic.Add("头像", strServerMapPath + "/1.jpg"); //使用书签操作 Document doc = new Document(strServerMapPath + "/1.doc"); DocumentBuilder builder = new DocumentBuilder(doc); foreach (var key in dic.Keys) { builder.MoveToBookmark(key); if (key != "头像") { builder.Write(dic[key]); } else { builder.InsertImage(dic[key]); } } doc.Save(strServerMapPath + "/书签操作.doc");//也可以保存为1.doc 兼容03-07 //直接替换书签文字 doc.Range.Bookmarks[key].Text = dic[key]; doc = new Aspose.Words.Document(strServerMapPath + "/1.doc"); bool IsLower = true;//匹配大小写 foreach (Aspose.Words.Bookmark bm in doc.Range.Bookmarks) { if (dic.ContainsKey(IsLower ? bm.Name.ToLower() : bm.Name)) { bm.Text = string.IsNullOrEmpty(dic[IsLower ? bm.Name.ToLower() : bm.Name]) ? "" : dic[IsLower ? bm.Name.ToLower() : bm.Name].ToString(); } else { bm.Text = ""; } } string NewFile = strServerMapPath + "/书签操作New.doc"; doc.Save(NewFile);//也可以保存为1.doc 兼容03-07 //ShowReq(NewFile, "书签操作New.doc", "word");//输出 Console.WriteLine("已经完成书签操作"); //使用特殊字符串替换 doc = new Document(strServerMapPath + "/2.doc"); foreach (var key in dic.Keys) { if (key != "头像") { var repStr = string.Format("&{0}&", key); doc.Range.Replace(repStr, dic[key], false, false); } else { Regex reg = new Regex("&头像&"); doc.Range.Replace(reg, new ReplaceAndInsertImage(strServerMapPath + "/1.jpg"), false); } } doc.Save(strServerMapPath + "/字符串替换操作.doc");//也可以保存为1.doc 兼容03-07 Console.WriteLine("已经完成特殊字符串替换操作"); Console.ReadKey(); } //输出到客户端 public static void ShowReq(string pFile, string ShowName, string Type) { //GC.Collect(); //FileStream fs = new FileStream(pFile, FileMode.Open); //byte[] buffer = new byte[fs.Length]; //fs.Read(buffer, 0, buffer.Length); //fs.Close(); //File.Delete(pFile); //Response.ContentType = "application/ms-" + Type; //Response.Charset = "GB2312"; //Response.ContentEncoding = System.Text.Encoding.UTF8; //Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(ShowName)); //Response.OutputStream.Write(buffer, 0, buffer.Length); //Response.Flush(); } } public class ReplaceAndInsertImage : IReplacingCallback { /// <summary> /// 需要插入的图片路径 /// </summary> public string url { get; set; } public ReplaceAndInsertImage(string url) { this.url = url; } public ReplaceAction Replacing(ReplacingArgs e) { //获取当前节点 var node = e.MatchNode; //获取当前文档 Document doc = node.Document as Document; DocumentBuilder builder = new DocumentBuilder(doc); //将光标移动到指定节点 builder.MoveTo(node); //插入图片 builder.InsertImage(url); return ReplaceAction.Replace; } } }
其它实例:
//模板完整路径 string strTemplate = Server.MapPath("~/Files/WordTemplate/") + "登记表.doc"; //打开模板 Document doc = new Document(strTemplate); DocumentBuilder builder = new DocumentBuilder(doc); //普通信息 doc.Range.Replace("&Text_NormalReagentName&", strNormalReagentName, false, false); doc.Range.Replace("&Text_Concentration&", strConcentration, false, false); doc.Range.Replace("&Text_Manufacturer&", strManufacturer, false, false); doc.Range.Replace("&Text_AcceptPersonName&", strAcceptPersonName, false, false); doc.Range.Replace("&Text_PurchaseTime&", strPurchaseTime, false, false); doc.Range.Replace("&Text_PurchaseQuantity&", strPurchaseQuantity, false, false); if (queryResultNormalReagentReceive.ResultCollection != null && queryResultNormalReagentReceive.ResultCollection.Count > 0) { //获取所有表格 NodeCollection allTables = doc.GetChildNodes(NodeType.Table, true); //第一个表格 Table table = allTables[0] as Table; for (int i = 0; i < queryResultNormalReagentReceive.ResultCollection.Count; i++) { //数据开始行 var dataRow = table.Rows[DATA_START_ROW + i]; //复制空行 var row = dataRow.Clone(true); //插入行 table.Rows.Insert(DATA_START_ROW + i, row); //领用日期 builder.MoveToCell(0, DATA_START_ROW + i, 0, 0); builder.Write(queryResultNormalReagentReceive.ResultCollection[i].ReceiveTime.ToString("yyyy-MM-dd")); //领用量 builder.MoveToCell(0, DATA_START_ROW + i, 1, 0); builder.Write(queryResultNormalReagentReceive.ResultCollection[i].ReceiveQuantity.ToString() + queryResultNormalReagentReceive.ResultCollection[i].UnitName); //剩余量 builder.MoveToCell(0, DATA_START_ROW + i, 2, 0); builder.Write(queryResultNormalReagentReceive.ResultCollection[i].RemainQuantity.ToString() + queryResultNormalReagentReceive.ResultCollection[i].UnitName); //领用登记人 builder.MoveToCell(0, DATA_START_ROW + i, 3, 0); builder.Write(queryResultNormalReagentReceive.ResultCollection[i].OperatorName); //备注 builder.MoveToCell(0, DATA_START_ROW + i, 4, 0); builder.Write(queryResultNormalReagentReceive.ResultCollection[i].Remarks); } //删除最后空行 table.Rows.RemoveAt(DATA_START_ROW + queryResultNormalReagentReceive.ResultCollection.Count); } string strOutFileName = Guid.NewGuid().ToString("D"); string strOutFilepath = Server.MapPath("~/Files/WordOutput/") + strOutFileName + ".doc"; //保存 doc.Save(strOutFilepath);
//表格单元格(Table Cell)文字添加背景 p0.ParagraphFormat.Shading.BackgroundPatternColor = Color.LightGoldenrodYellow; //表格单元格(Table Cell)添加背景 row1.Cells[1].CellFormat.Shading.BackgroundPatternColor = Color.LightGoldenrodYellow;
/// <summary> /// Doc Table Cells 动态添加单元格 /// AddCell(row1, doc, ++iCols, iRows.ToString()); /// </summary> /// <param name="row1"></param> /// <param name="doc"></param> /// <param name="iClos"></param> /// <param name="strValue"></param> private static void AddCell(Row row1, Document doc, int iClos, string strValue) { Cell c = row1.Cells[iClos]; Paragraph p0 = new Paragraph(doc); p0.AppendChild(new Run(doc, strValue)); p0.ParagraphFormat.Alignment = ParagraphAlignment.Center; //p0.ParagraphFormat.Style.Font.Size = 9; //p0.ParagraphFormat.Style.Font.Name = "宋体"; //row1.Cells[0].CellFormat.Width = 33; row1.Cells[iClos].CellFormat.VerticalAlignment = CellVerticalAlignment.Center; row1.Cells[iClos].FirstParagraph.Remove(); row1.Cells[iClos].AppendChild(p0); row1.Cells[iClos].Remove(); row1.Cells.Insert(iClos, c); }


浙公网安备 33010602011771号