.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 = ; 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[] as Aspose.Words.Tables.Table; #region 生产线基本信息
for (var i = ; i < dtA2.Rows.Count; i++)
{
Row roww = table.Rows[pSCXJBXX];
Row row1 = (Row)roww.Clone(true); //拷贝行
table.Rows.Insert(pSCXJBXX, row1); //将复制的行插入当前行的上方 for (var j = ; 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 = ;
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 += ;
pCWZYSCGY += ;
pWRZLGY += ;
pZXBZ += ;
pWRFFCC += ;
pWRWPWQX += ;
//pJCXXGK += 1;
} table.Rows.RemoveAt(pSCXJBXX); //合并单元格
int pIndexCount = pZXBZ - dtA3.Rows.Count;
int pPreIndex = pIndexCount + ;
string str1 = "";
string str2 = ""; for (int i = pPreIndex; i < pZXBZ; i++)
{
Row row1 = table.Rows[pIndexCount];
Row row2 = table.Rows[i];
str1 = row1.Cells[].GetText();
str2 = row2.Cells[].GetText();
if (str1 == str2)
{
table.Rows[pIndexCount].Cells[].CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.First;
table.Rows[i].Cells[].CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.Previous; table.Rows[pIndexCount].Cells[].CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.First;
table.Rows[i].Cells[].CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.Previous; table.Rows[pIndexCount].Cells[].CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.First;
table.Rows[i].Cells[].CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.Previous;
}
else
{
pIndexCount = i;
}
}
//文字居中
row1.Cells[].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, );//.GetByFilter(string.Format(" MNStandItemID in ({0})", strStandItemID.TrimEnd(',')));
if (listhand == null || listhand.Count < )
{
context.Response.Write("");
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 = ; 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, "测试", , , );
#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 < )
return null;
for (int i = ; 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 == )
{
double width = builder.CellFormat.PreferredWidth.Value;//获取单元格宽度
widthList.Add(width);
}
else
{
for (int i = ; i < ColumnIndex; i++)
{
builder.MoveToCell(TableIndex, RowIndex, i, ); //移动单元格
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 = ; r < TableInfo.Rows.Count; r++)
{
for (int c = ; 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 = ; 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 = ; r < TableInfo.Rows.Count; r++)
{
for (int c = ; 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 = ; 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 = ; 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 = ; //下边框
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 = , double imgcellheight = )
{
DocumentBuilder builder = new DocumentBuilder(doc);
//向此单元格中插入图片
Shape shape = new Shape(doc, ShapeType.Image);
shape.ImageData.SetImage(strImagePath);
shape.Width = imgcellwidth - ;
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 = , double imgcellheight = )
{
DocumentBuilder builder = new DocumentBuilder(doc);
//向此单元格中插入图片
Shape shape = new Shape(doc, ShapeType.Image);
shape.ImageData.SetImage(strImagePath);
shape.Width = imgcellwidth - ;
shape.Height = imgcellheight;
shape.HorizontalAlignment = HorizontalAlignment.Left;
CompositeNode node = shape.ParentNode;
//把此图片移动到那个单元格中
builder.MoveToCell(TableIndex, RowIndex, ColumnIndex, );//通过指定的表、行、列进行定位
builder.InsertNode(shape);
}
}
public class AsposePDFModel
{
/// <summary>
/// word书签名称
/// </summary>
public string MarkName { get; set; } /// <summary>
/// 书签内容
/// </summary>
public string MarkMemo { get; set; } protected string _type = "";
/// <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("联系方式", "");
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 > )
{
//获取所有表格
NodeCollection allTables = doc.GetChildNodes(NodeType.Table, true);
//第一个表格
Table table = allTables[] as Table;
for (int i = ; 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(, DATA_START_ROW + i, , );
builder.Write(queryResultNormalReagentReceive.ResultCollection[i].ReceiveTime.ToString("yyyy-MM-dd"));
//领用量
builder.MoveToCell(, DATA_START_ROW + i, , );
builder.Write(queryResultNormalReagentReceive.ResultCollection[i].ReceiveQuantity.ToString() + queryResultNormalReagentReceive.ResultCollection[i].UnitName);
//剩余量
builder.MoveToCell(, DATA_START_ROW + i, , );
builder.Write(queryResultNormalReagentReceive.ResultCollection[i].RemainQuantity.ToString() + queryResultNormalReagentReceive.ResultCollection[i].UnitName);
//领用登记人
builder.MoveToCell(, DATA_START_ROW + i, , );
builder.Write(queryResultNormalReagentReceive.ResultCollection[i].OperatorName);
//备注
builder.MoveToCell(, DATA_START_ROW + i, , );
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[].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);
}
.net使用Aspose.Words进行Word替换操作的实现代码的更多相关文章
- Aspose.Words对于Word的操作
对于word操作一般是对已有word模板的操作,直接新建的不考虑,网上教程很多,自己看吧一般有以下几种办法(忘了具体几种了,一般情况下以下就够了)1.通过书签替换顾名思义,就是先定义一个书签,然后在书 ...
- Aspose.Words进行Word替换(插入图片和水印)
由于最近一直在忙着做着Word打印模板的一些工作,就整理一些Asponse.Words对Word文档进行操作的资料. using System; using System.Collections.Ge ...
- 使用Aspose.Words将Word文档转换为Tiff格式图片文件
用Aspose组件的优点是操作Word文档不需要安装Office就可以实现. 首先需要引用Aspose.Words.dll,链接地址:链接:https://pan.baidu.com/s/1rJvjp ...
- C# 调用word进程操作文档关闭进程
C# 调用word进程操作文档关闭进程 作者:Jesai 时间:2018-02-12 20:36:23 前言: office办公软件作为现在主流的一款办公软件,在我们的日常生活和日常工作里面几乎每天都 ...
- 在C#中使用Spire.doc对word的操作总结
在C#中使用Spire.doc对word的操作总结 在最近的工程中我们要处理一些word文档.通过在网上的大量搜索,我发现大多数软件功能不是不完整就是有重复.极少数可以完全实现的word组件又要收费. ...
- Java进阶(三十九)Java集合类的排序,查找,替换操作
Java进阶(三十九)Java集合类的排序,查找,替换操作 前言 在Java方向校招过程中,经常会遇到将输入转换为数组的情况,而我们通常使用ArrayList来表示动态数组.获取到ArrayList对 ...
- Aspose.Words给word文档加水印
需求:在一些重要的Word文档需要打印时,添加水印以明出处. 方案:使用Aspose组件给word文档 代码:干货如下 /// <summary> /// Inserts a waterm ...
- WPF使用Aspose.Words导出Word文档
一.创建Word文档模板 分析需要导出的word文档,将固定的内容和由程序生成的内容分开; 创建一个word(例如:Template.doc)文档,将固定的内容按照一定的格式写入当前文档中; 打开Te ...
- jQuery_替换操作
代码: <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title ...
随机推荐
- RabbitMQ基本示例,轮询机制,no_ack作用
一.RabbitMQ简介: ''' RabbitMQ就是消息队列 之前不是学了Queue了吗,都是队列还学RabbitMQ干嘛? 干的事情是一样的 Python的Queue有两个, 一个线程Queue ...
- Python总结(一)
从大学开始,就对python有了兴趣,毕业设计就是用python做的一个新闻爬取和关键字提取的程序.然而,毕业之后由于一直没有从事python相关的开发,所以就一直没有再使用,一直停留在偶尔看一些资料 ...
- linux 系统信息展示 htop glances conky psensor
htop glances conky psensor htop glances 只能在终端内展示. htop 使用系统自带程序包管理程序就可以安装 glances github地址:https://g ...
- xcrun: error: unable to find utility "PackageApplication", not a developer tool or in PATH
xcrun: error: unable to find utility "PackageApplication", not a developer tool or in PATH ...
- PHP依赖注入原理与用法分析
https://www.jb51.net/article/146025.htm 本文实例讲述了PHP依赖注入原理与用法.分享给大家供大家参考,具体如下: 引言 依然是来自到喜啦的一道面试题,你知道什么 ...
- CF1012B Chemical table
$CF1012B Chemical table 给你一个 \(n\times m\) 的矩形,一开始有 \(q\) 个格子上被标记.对于任意两行两列,如果交汇的四个格子中有三个被标记,那么第 \(4\ ...
- Spring Boot2.0使用Spring Security
一.Spring Secutity简介 Spring 是一个非常流行和成功的 Java 应用开发框架.Spring Security 基于 Spring 框架,提供了一套 Web 应用安全性 ...
- Day3 Numerical simulation of optical wave propagation之标量衍射理论基本原理(三)
3.标量衍射理论 光源通常不是简单地平面.球面或高斯光束波.对于更一般的情况,必须使用更老练的方法来求解标量赫姆霍兹方程,需要利用格林定理并灵活使用边界条件. 基本问题:给定源平面光场U(x1,y1) ...
- Java的selenium代码随笔(5)
//以下七种方法主要用于生成年.月.日.小时.分钟和秒的信息,用于生成保存截图的文件目录名和文件名/** 格式化输出日期* * @return 返回字符型日期*/public static Strin ...
- MySQL系列:数据类型、运算符及函数(5)
1. 数据类型 MySQL支持多种数据类型,主要有数值类型.日期/时间类型和字符串类型. (1)数值类型:包括整数类型:TINYINT.SMALLINT.MEDIUMINT.INT.BIGINT, ...