辅助类1  json和datatable互转:  

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization; //System.Web.Extensions.dll
using System.Collections;
using System.Data; namespace Utils
{
public static class JsonDataTableConvert
{
#region DataTable 转换为Json 字符串
/// <summary>
/// DataTable 对象 转换为Json 字符串
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
public static string ToJson(DataTable dt)
{
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
javaScriptSerializer.MaxJsonLength = Int32.MaxValue; //取得最大数值
ArrayList arrayList = new ArrayList();
foreach (DataRow dataRow in dt.Rows)
{
Dictionary<string, object> dictionary = new Dictionary<string, object>(); //实例化一个参数集合
foreach (DataColumn dataColumn in dt.Columns)
{
dictionary.Add(dataColumn.ColumnName, dataRow[dataColumn.ColumnName].ToStr());
}
arrayList.Add(dictionary); //ArrayList集合中添加键值
} return javaScriptSerializer.Serialize(arrayList); //返回一个json字符串
}
#endregion #region Json 字符串 转换为 DataTable数据集合
/// <summary>
/// Json 字符串 转换为 DataTable数据集合
/// </summary>
/// <param name="json"></param>
/// <returns></returns>
public static DataTable ToDataTable(string json)
{
DataTable dataTable = new DataTable(); //实例化
DataTable result;
try
{
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
javaScriptSerializer.MaxJsonLength = Int32.MaxValue; //取得最大数值
ArrayList arrayList = javaScriptSerializer.Deserialize<ArrayList>(json);
if (arrayList.Count > 0)
{
foreach (Dictionary<string, object> dictionary in arrayList)
{
if (dictionary.Keys.Count<string>() == 0)
{
result = dataTable;
return result;
}
if (dataTable.Columns.Count == 0)
{
foreach (string current in dictionary.Keys)
{
var obj = dictionary[current];
dataTable.Columns.Add(current,typeof(string) /*obj == null ? typeof(string) : obj.GetType()*/);//全当做字符串处理
}
}
DataRow dataRow = dataTable.NewRow();
foreach (string current in dictionary.Keys)
{
dataRow[current] = dictionary[current];
} dataTable.Rows.Add(dataRow); //循环添加行到DataTable中
}
}
}
catch
{
}
result = dataTable;
return result;
}
#endregion #region 转换为string字符串类型
/// <summary>
/// 转换为string字符串类型
/// </summary>
/// <param name="s">获取需要转换的值</param>
/// <param name="format">需要格式化的位数</param>
/// <returns>返回一个新的字符串</returns>
public static string ToStr(this object s, string format = "")
{
string result = "";
try
{
if (format == "")
{
result = s.ToString();
}
else
{
result = string.Format("{0:" + format + "}", s);
}
}
catch
{
}
return result;
}
#endregion
}
}

辅助类2  Excel表格数据和datatable互转:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using NPOI.HSSF.UserModel;
using System.IO;
using System.Data; namespace Utils
{
//http://www.cnblogs.com/luxiaoxun/p/3374992.html
public class ExcelDataTableConverter : IDisposable
{
private string fileName = null; //文件名
private IWorkbook workbook = null;
private FileStream fs = null;
private bool disposed; public ExcelDataTableConverter(string fileName)
{
this.fileName = fileName;
disposed = false;
} /// <summary>
/// 将DataTable数据导入到excel中
/// </summary>
/// <param name="data">要导入的数据</param>
/// <param name="isColumnWritten">DataTable的列名是否要导入</param>
/// <param name="sheetName">要导入的excel的sheet的名称</param>
/// <returns>导入数据行数(包含列名那一行)</returns>
public int DataTableToExcel(DataTable data, string sheetName, bool isColumnWritten)
{
int i = 0;
int j = 0;
int count = 0;
ISheet sheet = null; fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite);
if (fileName.IndexOf(".xlsx") > 0) // 2007版本
workbook = new XSSFWorkbook();
else if (fileName.IndexOf(".xls") > 0) // 2003版本
workbook = new HSSFWorkbook(); try
{
if (workbook != null)
{
sheet = workbook.CreateSheet(sheetName);
}
else
{
return -1;
} if (isColumnWritten == true) //写入DataTable的列名
{
IRow row = sheet.CreateRow(0);
for (j = 0; j < data.Columns.Count; ++j)
{
row.CreateCell(j).SetCellValue(data.Columns[j].ColumnName);
}
count = 1;
}
else
{
count = 0;
} for (i = 0; i < data.Rows.Count; ++i)
{
IRow row = sheet.CreateRow(count);
for (j = 0; j < data.Columns.Count; ++j)
{
row.CreateCell(j).SetCellValue(data.Rows[i][j].ToString());
}
++count;
}
workbook.Write(fs); //写入到excel
return count;
}
catch (Exception ex)
{
Console.WriteLine("Exception: " + ex.Message);
return -1;
}
} /// <summary>
/// 将excel中的数据导入到DataTable中
/// </summary>
/// <param name="sheetName">excel工作薄sheet的名称</param>
/// <param name="isFirstRowColumn">第一行是否是DataTable的列名</param>
/// <returns>返回的DataTable</returns>
public DataTable ExcelToDataTable(string sheetName, bool isFirstRowColumn)
{
ISheet sheet = null;
DataTable data = new DataTable();
int startRow = 0;
try
{
fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
if (fileName.IndexOf(".xlsx") > 0) // 2007版本
workbook = new XSSFWorkbook(fs);
else if (fileName.IndexOf(".xls") > 0) // 2003版本
workbook = new HSSFWorkbook(fs); if (sheetName != null)
{
sheet = workbook.GetSheet(sheetName);
if (sheet == null) //如果没有找到指定的sheetName对应的sheet,则尝试获取第一个sheet
{
sheet = workbook.GetSheetAt(0);
}
}
else
{
sheet = workbook.GetSheetAt(0);
}
if (sheet != null)
{
IRow firstRow = sheet.GetRow(0);
int cellCount = firstRow.LastCellNum; //一行最后一个cell的编号 即总的列数 if (isFirstRowColumn)
{
for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
{
ICell cell = firstRow.GetCell(i);
if (cell != null)
{
string cellValue = cell.StringCellValue;
if (cellValue != null)
{
DataColumn column = new DataColumn(cellValue);
data.Columns.Add(column);
}
}
}
startRow = sheet.FirstRowNum + 1;
}
else
{
startRow = sheet.FirstRowNum;
} //最后一列的标号
int rowCount = sheet.LastRowNum;
for (int i = startRow; i <= rowCount; ++i)
{
IRow row = sheet.GetRow(i);
if (row == null) continue; //没有数据的行默认是null        DataRow dataRow = data.NewRow();
for (int j = row.FirstCellNum; j < cellCount; ++j)
{
if (row.GetCell(j) != null) //同理,没有数据的单元格都默认是null
{
//dataRow[j] = row.GetCell(j).ToString(); //19890603会显示成MIDB(C2,7,6)
dataRow[j] = row.GetCell(j).StringCellValue;
}
}
data.Rows.Add(dataRow);
}
} return data;
}
catch (Exception ex)
{
Console.WriteLine("Exception: " + ex.Message);
return null;
}
} public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
} protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
if (fs != null)
fs.Close();
} fs = null;
disposed = true;
}
}
}
}

书签内容替换封装:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Aspose.Words;
using System.Data; namespace Utils
{
public static class AsposeWordReplaceBookMarkContentApi
{
public static void BookMarkReplace(Document wordDoc,DocumentBuilder builder, string bookMark, string type, string value)
{
var bm = wordDoc.Range.Bookmarks[bookMark];
if (bm == null)
{
return;
} if (type == "IMG")
{
bm.Text = "";
builder.MoveToBookmark(bookMark);
var img = builder.InsertImage(@value);
//img.Width = 300;
//img.Height = 300;
               <span style="color:#ff0000;">img.Width =ConvertUtil.PixelToPoint(124d); //单位转换</span>
          img.Height = ConvertUtil.PixelToPoint(134d);
img.HorizontalAlignment = Aspose.Words.Drawing.HorizontalAlignment.Center;
}
else if (type == "TABLE")
{
bm.Text = "";
builder.MoveToBookmark(bookMark); DataTable dt = Utils.JsonDataTableConvert.ToDataTable(value);//json转datatable int rowCount = dt.Rows.Count;
int columnCount = dt.Columns.Count; builder.MoveToBookmark(bookMark);
builder.StartTable();//开始画Table            
builder.ParagraphFormat.Alignment = ParagraphAlignment.Center; // RowAlignment.Center;                 string str = string.Empty; builder.RowFormat.Height = 20; //添加列头
for (int i = 0; i < columnCount; i++)
{
builder.InsertCell();
//Table单元格边框线样式
builder.CellFormat.Borders.LineStyle = LineStyle.Single;
//Table此单元格宽度
builder.CellFormat.Width = 600;
//此单元格中内容垂直对齐方式
builder.CellFormat.VerticalAlignment = Aspose.Words.Tables.CellVerticalAlignment.Center;
builder.CellFormat.HorizontalMerge = Aspose.Words.Tables.CellMerge.None;
builder.CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.None;
//字体大小
builder.Font.Size = 10;
//是否加粗
builder.Bold = true;
//向此单元格中添加内容
builder.Write(dt.Columns[i].ColumnName);
}
builder.EndRow(); //添加每行数据
for (int i = 0; i < rowCount; i++)
{ for (int j = 0; j < columnCount; j++)
{
str = dt.Rows[i][j].ToString(); //http://www.cnblogs.com/geovindu/p/4106418.html
//http://www.cnblogs.com/wuhuacong/archive/2012/08/30/2662961.html //插入Table单元格
builder.InsertCell(); //Table单元格边框线样式
builder.CellFormat.Borders.LineStyle = LineStyle.Single; //Table此单元格宽度 跟随列头宽度
//builder.CellFormat.Width = 500; //此单元格中内容垂直对齐方式
builder.CellFormat.VerticalAlignment = Aspose.Words.Tables.CellVerticalAlignment.Center; builder.CellFormat.HorizontalMerge = Aspose.Words.Tables.CellMerge.None;
builder.CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.None; //字体大小
builder.Font.Size = 10; //是否加粗
builder.Bold = false; //向此单元格中添加内容
builder.Write(str); } //Table行结束
builder.EndRow(); }
builder.EndTable();
}
else
{//其他文字,日期等文字
bm.Text = "";
builder.MoveToBookmark(bookMark);
bm.Text =@value;
} } }
}

调用:

        private void button2_Click(object sender, EventArgs e)
{
Aspose.Words.Document doc = new Aspose.Words.Document("TEMPLATE.DOCX");
Aspose.Words.DocumentBuilder builder = new Aspose.Words.DocumentBuilder(doc); //在书签处插入表格
Utils.AsposeWordReplaceBookMarkContentApi.BookMarkReplace(doc, builder, "BK002", "TABLE", "[{'Name':'zhangsan','Sex':'Male'},{'Name':'wangwu','Sex':'Female'}]");
//在书签处插入图片
Utils.AsposeWordReplaceBookMarkContentApi.BookMarkReplace(doc, builder, "BK001", "IMG", "1.PNG");
//在书签处插入文字
Utils.AsposeWordReplaceBookMarkContentApi.BookMarkReplace(doc, builder, "BK003", "TEXT", " 测试文字啊啊涉及到法律框架阿斯兰开发按时交电费卡拉斯几发,阿斯顿减肥拉斯加付款阿卡丽交电费卡拉斯发的,看到谁放假啦设计费看,开始搭建费绿卡是否看见快乐健康了阿斯顿发顺丰空间看拉丁方."); string saveDocFile = "1.DOCX";
doc.Save(saveDocFile); if (MessageBox.Show("保存成功,是否打开文件?", "", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
{
System.Diagnostics.Process.Start(saveDocFile);
}
}

效果:

打印

doc.Print();

文本替换

doc.Range.Replace("{{name}}", "张三", false, true);

版权声明:本文为博主原创文章,未经博主允许不得转载。

c#对Aspose.Word替换书签内容的简单封装的更多相关文章

  1. C# Aspose word 替换指定键值数据

    今天研究一天的导出word,一开始准备选用为软件自带的office,但是有局限性,机子上必须安装office才能使用,最后在网上搜了一下资料aspose开源的 小公司没得钱,你懂得.最后选择了这款 开 ...

  2. aspose.word 在书签处插入符号

    doc.Range.Bookmarks["CBJYQQDFS110"].Text = ""; Aspose.Words.DocumentBuilder buil ...

  3. c#调用Aspose.Word组件操作word 插入文字/图片/表格 书签替换套打

    由于NPOI暂时没找到书签内容替换功能,所以换用Apose.Word组件. using System; using System.Collections.Generic; using System.C ...

  4. C# 操作Word书签(二)——插入图片、表格到书签;读取、替换书签

    概要 书签的设置可以帮助我们快速的定位某段文字,使用起来很方便,也很节省时间.在前一篇文章“C# 如何添加/删除Word书签”中介绍了插入.删除书签的方法,本篇文章将对C# 操作Word书签的功能做进 ...

  5. .net使用Aspose.Words进行Word替换操作的实现代码

    DLL文件下载 示例: Aspose.Words.Document doc = new Aspose.Words.Document(TempFile); Aspose.Words.DocumentBu ...

  6. Java 操作Word书签(三):用文本、图片、表格替换书签

    本篇文章将继续介绍通过Java来操作Word书签的方法,即替换Word中已有书签,包括用新的文本.图片.表格等替换原有书签处的内容. 使用工具:Free Spire.Doc for Java (免费版 ...

  7. Java 操作Word书签(二):添加文本、图片、表格到书签内容

    在Java操作Word书签(一)中介绍了给Word中的特定段落或文字添加书签.读取及删除已有书签的方法,本文将继续介绍Java 操作Word书签的方法,即如何给已有的书签添加内容,包括添加文本.图片. ...

  8. aspose.word 读取word段落内容

    注:转载请标明文章原始出处及作者信息 aspose.word 插件下载 链接: http://pan.baidu.com/s/1qXIgOXY 密码: wsj2 使用原因:无需安装office,无兼容 ...

  9. 利用Aspose.Word控件和Aspose.Cell控件,实现Word文档和Excel文档的模板化导出

    我们知道,一般都导出的Word文档或者Excel文档,基本上分为两类,一类是动态生成全部文档的内容方式,一种是基于固定模板化的内容输出,后者在很多场合用的比较多,这也是企业报表规范化的一个体现. 我的 ...

随机推荐

  1. 【转】Objective-C Class Dump

    (转自:http://blog.sina.com.cn/s/blog_4431c7610100x15t.html) class dump是一个命令行工具,用来监测存储在Mach-O二进制文件理的Obj ...

  2. 桌面oracle 11g导入多年库的dump备忘

    接到客户6G的dump文件.先导入桌面orcale ,imp提示出错,执行impdp后如下 连接到: Oracle Database 11g Express Edition Release 11.2. ...

  3. Unity3D]引擎崩溃、异常、警告、BUG与提示总结及解决方法

    此贴会持续更新,都是项目中常会遇到的问题,总结成贴,提醒自己和方便日后检查,也能帮到有需要的同学. 若各位有啥好BUG好异常好警告好崩溃可以分享的话,请多多指教.xuzhiping7#qq.com. ...

  4. Arduino 学习

    Arduino 背景可以参考官方网站www.arduino.cc 先看一个最简单的示例程序: 打开 Arduino IDE , 选择菜单:文件 -> 示例 -> 01.Basics -&g ...

  5. 7个惊艳的HTML5 Canvas动画效果及源码

    HTML5非常强大,尤其是现在大部分浏览器都支持HTML5和CSS3,用HTML5制作的动画也多了起来.另外,Canvas上绘制图形非常简单,本文就分享了一些强大的HTML5 Cnavas动画,一起来 ...

  6. java计算当前周开始日期&结束日期

    public static Date getFirstDayOfWeek(Date date) { Calendar c = new GregorianCalendar(); c.setFirstDa ...

  7. AjaxControlToolKit--TabContainer控件的介绍

    1.       Introduction: Tab本身就应该是个以页签形式显示组织网页内容的一个控件.在AJAX Control Tool Kit的控件中有TabContainer控件,它是一些Ta ...

  8. zepto - scrollLeft

    <div style="border:1px solid black;width:100px;height:130px;overflow:auto"> The long ...

  9. MySQL server has gone away 问题的解决方法

    mysql出现ERROR : (2006, 'MySQL server has gone away') 的问题意思就是指client和MySQL server之间的链接断开了. 造成这样的原因一般是s ...

  10. mockito

    import org.junit.Assert;import org.junit.Before;import org.junit.Test;import org.junit.runner.RunWit ...