您的位置:首页 > 编程语言 > ASP

用Aspose来打印Word方法类

2016-07-18 16:29 344 查看
使用Aspose来打印word是常用的一种方法,循环打印,多个列表打印,图片打印,数据库SQL查询语句select xx1,xx2,xx3 from 表名称,Word里面对应的就写$XX1$,$XX2$,$XX3$,当然也可以根据自己需要自定义,用到的Aspose去主页下载,当然也可以点击http://download.csdn.net/detail/u012949335/9579250下载。
</pre><pre name="code" class="csharp">
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using Aspose.Words;
using System.Configuration;
using System.Data.SqlClient;
using System.Reflection;
using Aspose.Words.Drawing;
using System.Text.RegularExpressions;
using System.IO;
using Aspose.Words.Saving;
using Aspose.Words.Tables;
using System.Text;
using System.Drawing.Printing;
using System.Collections;

namespace Gmis.WebControl
{
public class PrintClass
{
public string path = string.Empty;
public string filename = "打印";
public string WordTabChar = "$";
public string title = string.Empty;
public static string Dotype = "word";

/// <summary>
/// 保存文档
/// </summary>
/// <param name="doc"></param>
private void SaveDocument(Document doc)
{

if (Dotype.Equals("word"))
{
SaveOptions saveop = SaveOptions.CreateSaveOptions(filename + ".doc");
doc.Save(HttpContext.Current.Response, filename + ".doc", ContentDisposition.Attachment, saveop);
}

}

/// <summary>
/// 打印信息和列表
/// </summary>
/// <param name="dtinfo"></param>
/// <param name="dtlist"></param>
public void Print_InfoList(DataTable dtinfo, DataTable dtlist)
{
Document maindoc = new Document();
DocumentBuilder builder = null;
Document newdoc = new Document(path);
builder = new DocumentBuilder(newdoc);

newdoc.Range.Replace(WordTabChar + "title" + WordTabChar, title, false, false);// 清掉标示
for (int n = 0; n < dtinfo.Columns.Count; n++)
{
string fieldname = dtinfo.Columns
.ColumnName.ToLower();
try
{
newdoc.Range.Replace(WordTabChar + fieldname.ToLower() + WordTabChar, dtinfo.Rows[0][fieldname].ToString(), false, false);
}
catch { }
}

Aspose.Words.Tables.Table dtdoc = (Aspose.Words.Tables.Table)newdoc.GetChild(NodeType.Table, 0, true);//定位第一个table
int listrow = 0, listcell = 0;
for (int r = 0; r < dtdoc.Rows.Count; r++)
{
for (int c = 0; c < dtdoc.Rows[r].Cells.Count; c++)
{
if (dtdoc.Rows[r].Cells[c].Range.Text.ToLower().Contains(WordTabChar + "list" + WordTabChar))
{
listrow = r;
listcell = c;
}

}
if (listrow > 0)
{ break; }
}

newdoc.Range.Replace(WordTabChar + "list" + WordTabChar, "", false, false);
List<string> celltabs = new List<string>();

for (int t = listcell; t < dtdoc.Rows[listrow].Cells.Count; t++)
{
string colname = dtdoc.Rows[listrow].Cells[t].Range.Text.Replace(WordTabChar, "").Replace("\a", "");
celltabs.Add(colname);
newdoc.Range.Replace(WordTabChar + colname + WordTabChar, "", false, false);
}

//插入需要补充的行
int ynum = dtdoc.Rows.Count;
for (int k = 0; k < dtlist.Rows.Count - (ynum - listrow); k++)
{
Aspose.Words.Node newrow1 = dtdoc.Rows[listrow + k + 1].Clone(true);
dtdoc.Rows.Insert(listrow + k, newrow1);
}

for (int m = 0; m < dtlist.Rows.Count; m++)
{

for (int n = 0; n < celltabs.Count; n++)
{
try
{
builder.MoveToCell(0, listrow + m, listcell + n, 0);
builder.Write(dtlist.Rows[m][celltabs
.ToString()].ToString());
}
catch
{
//builder.MoveToCell(0, listrow + m, listcell + n, 0);
//builder.Write(dtlist.Rows[m][celltabs
.ToString()].ToString());
}
}
}

maindoc = newdoc;
maindoc.Protect(ProtectionType.AllowOnlyFormFields);//只读无法编辑,因为没有密码确认
this.SaveDocument(maindoc);
}

/// <summary>
/// 打印信息和列表
/// </summary>
/// <param name="dtinfo"></param>
/// <param name="dtlist"></param>
public void Print_InfoList(DataTable dtinfo, Dictionary<string, string> dict, DataTable dtlist, int tableindex)
{
//Print_InfoList(dtinfo, dict, dtlist, false);
Document maindoc = new Document();
Document newdoc = new Document(path);
DocumentBuilder builder = new DocumentBuilder(newdoc);
newdoc.Range.Replace(WordTabChar + "title" + WordTabChar, title, false, false);
if (dtinfo != null)
{
for (int n = 0; n < dtinfo.Columns.Count; n++)
{
string fieldname = dtinfo.Columns
.ColumnName.ToLower();
try
{
newdoc.Range.Replace(WordTabChar + fieldname.ToLower() + WordTabChar, dtinfo.Rows[0][fieldname].ToString(), false, false);
}
catch { }
}
}
if (dict != null)
{
foreach (string k in dict.Keys)
{
newdoc.Range.Replace(WordTabChar + k.ToLower() + WordTabChar, dict[k].ToString(), false, false);
}
}
Aspose.Words.Tables.Table dtdoc = (Aspose.Words.Tables.Table)newdoc.GetChild(NodeType.Table, tableindex, true);//定位第一个table
PositionPro pos = new PositionPro();
for (int r = 0; r < dtdoc.Rows.Count; r++)
{
for (int c = 0; c < dtdoc.Rows[r].Cells.Count; c++)
{
if (dtdoc.Rows[r].Cells[c].Range.Text.ToLower().Contains("#start#"))
{

pos.row_start = r;
pos.cell_start = c;
pos.row_end = r;
pos.cell_end = c;
}
if (dtdoc.Rows[r].Cells[c].Range.Text.ToLower().Contains("#end#"))
{
pos.row_end = r;
pos.cell_end = c;
}
}

}
newdoc.Range.Replace("#START#", "", false, false);
newdoc.Range.Replace("#END#", "", false, false);

DataTable dt = dtlist;
List<string> celltabs = new List<string>();
for (int t = pos.cell_start; t < dtdoc.Rows[pos.row_start].Cell
4000
s.Count; t++)
{
string colname = dtdoc.Rows[pos.row_start].Cells[t].Range.Text.Replace(WordTabChar, "").Replace("\a", "");
celltabs.Add(colname);
dtdoc.Rows[pos.row_start].Cells[t].Range.Replace(WordTabChar + colname + WordTabChar, "", false, false);
}
if (dt.Rows.Count > pos.rownum)
{
int addrow = dt.Rows.Count - pos.rownum;
for (int a = 0; a < addrow; a++)
{
Aspose.Words.Node newrow = dtdoc.Rows[pos.row_start].Clone(true);
dtdoc.Rows.Insert(pos.row_start + 1, newrow);
}
}
for (int m = 0; m < dt.Rows.Count; m++)
{
for (int n = 0; n < celltabs.Count; n++)
{
try
{
builder.MoveToCell(tableindex, pos.row_start + m, pos.cell_start + n, 0);
builder.Write(dt.Rows[m][celltabs
.ToString()].ToString());
}
catch { }
}
}
maindoc = newdoc;
maindoc.Protect(ProtectionType.AllowOnlyFormFields);//只读无法编辑,因为没有密码确认
this.SaveDocument(maindoc);
}

/// <summary>
/// 打印多个列表
/// </summary>
/// <param name="xh"></param>
public void Print_InfoLists(List<PrintData> pageData, int tableindex)
{
List<PositionPro> listpos = new List<PositionPro>();
Document maindoc = new Document();
for (int p = 0; p < pageData.Count; p++)
{
Document newdoc = new Document(path);
DocumentBuilder builder = new DocumentBuilder(newdoc);
List<DataTable> dtinfos = pageData[p].dtinfos;
Dictionary<string, string> dict = pageData[p].dict;
List<DataTable> dtlist = pageData[p].dtlist;
//newdoc.Range.Replace(WordTabChar + "title" + WordTabChar, title, false, false);
if (dtinfos != null)
{
for (int i = 0; i < dtinfos.Count; i++)
{
DataTable dtinfo = dtinfos[i];
for (int n = 0; n < dtinfo.Columns.Count; n++)
{
string fieldname = dtinfo.Columns
.ColumnName.ToLower();
try
{
newdoc.Range.Replace(WordTabChar + fieldname.ToLower() + WordTabChar, dtinfo.Rows[0][fieldname].ToString(), false, false);
}
catch { }
}
}
}
if (dict != null)
{
foreach (string k in dict.Keys)
{
newdoc.Range.Replace(WordTabChar + k.ToLower() + WordTabChar, dict[k].ToString(), false, false);
}
}
Aspose.Words.Tables.Table dtdoc = (Aspose.Words.Tables.Table)newdoc.GetChild(NodeType.Table, tableindex, true);//定位table
if (p == 0)
{
for (int r = 0; r < dtdoc.Rows.Count; r++)
{
for (int c = 0; c < dtdoc.Rows[r].Cells.Count; c++)
{
if (dtdoc.Rows[r].Cells[c].Range.Text.ToLower().Contains("#start#"))
{
PositionPro pos = new PositionPro();
pos.row_start = r;
pos.cell_start = c;
pos.row_end = r;
pos.cell_end = c;
listpos.Add(pos);
}
if (dtdoc.Rows[r].Cells[c].Range.Text.ToLower().Contains("#end#"))
{
PositionPro pos = listpos.Last<PositionPro>();
pos.row_end = r;
pos.cell_end = c;
}
}
}
}
newdoc.Range.Replace("#START#", "", false, false);
newdoc.Range.Replace("#END#", "", false, false);
for (int i = 0; i < dtlist.Count; i++)
{
PositionPro pos = new PositionPro();
if (listpos.Count > i)
{
pos = listpos[i];
}
DataTable dt = dtlist[i];
List<string> celltabs = new List<string>();
for (int t = pos.cell_start; t < dtdoc.Rows[pos.row_start].Cells.Count; t++)
{
string colname = dtdoc.Rows[pos.row_start].Cells[t].Range.Text.Replace(WordTabChar, "").Replace("\a", "");
celltabs.Add(colname);
dtdoc.Rows[pos.row_start].Range.Replace(WordTabChar + colname + WordTabChar, "", false, false);
}
if (dt.Rows.Count > pos.rownum)
{
int addrow = dt.Rows.Count - pos.rownum;
for (int a = 0; a < addrow; a++)
{
Aspose.Words.Node newrow = dtdoc.Rows[pos.row_start + 1].Clone(true);
dtdoc.Rows.Insert(pos.row_start + 1, newrow);
if (i < listpos.Count - 1)
{
for (int l = i + 1; l < listpos.Count; l++)
{
PositionPro posnext = listpos[l];
posnext.row_start += 1;
posnext.row_end += 1;
}
}
}
}
for (int m = 0; m < dt.Rows.Count; m++)
{
for (int n = 0; n < celltabs.Count; n++)
{
try
{
builder.MoveToCell(tableindex, pos.row_start + m, pos.cell_start + n, 0);
builder.Write(dt.Rows[m][celltabs
.ToString()].ToString());
}
catch { }
}
}
}
if (p == 0)
{
maindoc = newdoc;
}
else
{
newdoc.FirstSection.PageSetup.SectionStart = SectionStart.NewPage;
maindoc.AppendDocument(newdoc, ImportFormatMode.KeepSourceFormatting);
}
}
//maindoc = newdoc;
maindoc.Protect(ProtectionType.AllowOnlyFormFields);//只读无法编辑,因为没有密码确认
this.SaveDocument(maindoc);
}

/// <summary>
/// 打印多个列表(图片)
/// </summary>
/// <param name="xh"></param>
public void Print_InfoLists(List<PrintData> pageData, int tableindex, bool img)
{
List<PositionPro> listpos = new List<PositionPro>();
Document maindoc = new Document();
for (int p = 0; p < pageData.Count; p++)
{
Document newdoc = new Document(path);
DocumentBuilder builder = new DocumentBuilder(newdoc);
List<DataTable> dtinfos = pageData[p].dtinfos;
Dictionary<string, string> dict = pageData[p].dict;
List<DataTable> dtlist = pageData[p].dtlist;
if (dtinfos != null)
{
for (int i = 0; i < dtinfos.Count; i++)
{

DataTable dtinfo = dtinfos[i];
#region 照片
if (i == 0 && img == true)
{

string url = "../.../../zj.jpg";//照片的路径

if (url != "")
{
newdoc.Range.Replace(WordTabChar + "photoxj" + WordTabChar, "#photoxj#", false, false);
Regex reg = new Regex("#photoxj#");
newdoc.Range.Replace(reg, new ReplaceImage(url), true);
}
else
{
newdoc.Range.Replace(WordTabChar + "photoxj" + WordTabChar, "", false, false);
}
}
#endregion

for (int n = 0; n < dtinfo.Columns.Count; n++)
{
string fieldname = dtinfo.Columns
.ColumnName.ToLower();
try
{
newdoc.Range.Replace(WordTabChar + fieldname.ToLower() + WordTabChar, dtinfo.Rows[0][fieldname].ToString(), false, false);
}
catch { }
}
}
}
if (dict != null)
{
foreach (string k in dict.Keys)
{
newdoc.Range.Replace(WordTabChar + k.ToLower() + WordTabChar, dict[k].ToString(), false, false);
}
}
Aspose.Words.Tables.Table dtdoc = (Aspose.Words.Tables.Table)newdoc.GetChild(NodeType.Table, tableindex, true);//定位table
if (p == 0)
{
for (int r = 0; r < dtdoc.Rows.Count; r++)
{
for (int c = 0; c < dtdoc.Rows[r].Cells.Count; c++)
{
if (dtdoc.Rows[r].Cells[c].Range.Text.ToLower().Contains("#start#"))
{
PositionPro pos = new PositionPro();
pos.row_start = r;
pos.cell_start = c;
pos.row_end = r;
pos.cell_end = c;
listpos.Add(pos);
}
if (dtdoc.Rows[r].Cells[c].Range.Text.ToLower().Contains("#end#"))
{
PositionPro pos = listpos.Last<PositionPro>();
pos.row_end = r;
pos.cell_end = c;
}
}
}
}
newdoc.Range.Replace("#START#", "", false, false);
newdoc.Range.Replace("#END#", "", false, false);
for (int i = 0; i < dtlist.Count; i++)
{
PositionPro pos = new PositionPro();
if (listpos.Count > i)
{
pos = listpos[i];
}
DataTable dt = dtlist[i];
List<string> celltabs = new List<string>();
for (int t = pos.cell_start; t < dtdoc.Rows[pos.row_start].Cells.Count; t++)
{
string colname = dtdoc.Rows[pos.row_start].Cells[t].Range.Text.Replace(WordTabChar, "").Replace("\a", "");
celltabs.Add(colname);
dtdoc.Rows[pos.row_start].Range.Replace(WordTabChar + colname + WordTabChar, "", false, false);
}
if (dt.Rows.Count > pos.rownum)
{
int addrow = dt.Rows.Count - pos.rownum;
for (int a = 0; a < addrow; a++)
{
Aspose.Words.Node newrow = dtdoc.Rows[pos.row_start + 1].Clone(true);
dtdoc.Rows.Insert(pos.row_start + 1, newrow);
if (i < listpos.Count - 1)
{
for (int l = i + 1; l < listpos.Count; l++)
{
PositionPro posnext = listpos[l];
posnext.row_start += 1;
posnext.row_end += 1;
}
}
}
}
for (int m = 0; m < dt.Rows.Count; m++)
{
for (int n = 0; n < celltabs.Count; n++)
{
try
{
builder.MoveToCell(tableindex, pos.row_start + m, pos.cell_start + n, 0);
builder.Write(dt.Rows[m][celltabs
.ToString()].ToString());
}
catch { }
}
}
}
if (p == 0)
{
maindoc = newdoc;
}
else
{
newdoc.FirstSection.PageSetup.SectionStart = SectionStart.NewPage;
maindoc.AppendDocument(newdoc, ImportFormatMode.KeepSourceFormatting);
}
}
maindoc.Protect(ProtectionType.AllowOnlyFormFields);//只读无法编辑,因为没有密码确认
this.SaveDocument(maindoc);
}

public void Print_InfoZdzm(DataTable dtinfo)
{
Document maindoc = new Document();
for (int c = 0; c < dtinfo.Rows.Count; c++)
{
Document newdoc = new Document(path);
DocumentBuilder builder = new DocumentBuilder(newdoc);
newdoc.Range.Replace(WordTabChar + "title" + WordTabChar, title, false, false);
for (int n = 0; n < dtinfo.Columns.Count; n++)
{
string fieldname = dtinfo.Columns
.ColumnName.ToLower();
string fieldtext = dtinfo.Rows[c][fieldname].ToString();
try
{
newdoc.Range.Replace(WordTabChar + fieldname.ToLower() + WordTabChar, fieldtext, false, false);
}
catch { }
}
//Dictionary<string, string> dict = list[c];
//if (dict != null)
//{
//    foreach (string k in dict.Keys)
//    {
//        newdoc.Range.Replace(WordTabChar + k.ToLower() + WordTabChar, dict[k].ToString(), false, false);
//    }
//}
if (c == 0)
{
maindoc = newdoc;
}
else
{
newdoc.FirstSection.PageSetup.SectionStart = SectionStart.NewPage;
maindoc.AppendDocument(newdoc, ImportFormatMode.KeepSourceFormatting);
}
}
Dotype = "word";
this.SaveDocument(maindoc);
//maindoc.Save(filename + ".doc", SaveFormat.Doc, SaveType.OpenInWord, HttpContext.Current.Response);

}

}
//转文本
public class ReplaceText : IReplacingCallback    {        /// <summary>  be8f              /// 需要插入的图片路径                /// </summary>        public string Text { get; set; }        public ReplaceText(string Text)        {            this.Text = Text;        }        public ReplaceAction Replacing(ReplacingArgs e)        {            //获取当前节点                    var node = e.MatchNode;            Document doc = node.Document as Document;            DocumentBuilder builder = new DocumentBuilder(doc);            builder.MoveTo(node);            builder.Write(Text);            return ReplaceAction.Replace;        }    }
//html格式转文本
public class ReplaceHtml : IReplacingCallback{/// <summary>/// 需要插入的图片路径/// </summary>public string Text { get; set; }public ReplaceHtml(string Text){this.Text = Text;}public ReplaceAction Replacing(ReplacingArgs e){//获取当前节点var node = e.MatchNode;Document doc = node.Document as Document;DocumentBuilder builder = new DocumentBuilder(doc);builder.MoveTo(node);builder.InsertHtml(Text);return ReplaceAction.Replace;}}//插入图片public class ReplaceImage : IReplacingCallback{/// <summary>/// 需要插入的图片路径/// </summary>public string ImageUrl { get; set; }//public ReplaceImage(string url){this.ImageUrl = url;}public ReplaceAction Replacing(ReplacingArgs e){//获取当前节点if (!string.IsNullOrEmpty(ImageUrl)){var node = e.MatchNode;Document doc = node.Document as Document;DocumentBuilder builder = new DocumentBuilder(doc);builder.MoveTo(node);//builder.Write(Text);Shape shape = new Shape(doc, ShapeType.Image);shape.ImageData.SetImage(ImageUrl);shape.Top = 0;shape.Width = 80;shape.Height = 104;shape.HorizontalAlignment = HorizontalAlignment.Center;CompositeNode node1 = shape.ParentNode;builder.InsertNode(shape);}return ReplaceAction.Replace;}}public class PositionPro{public string key { get; set; }public int row_start { get; set; }public int row_end { get; set; }public int cell_start { get; set; }public int cell_end { get; set; }public int rownum{get{return row_end - row_start + 1;}}}public class PrintData{public List<DataTable> dtinfos;public Dictionary<string, string> dict;public List<DataTable> dtlist;}}
调用方法:
protected void btnzdzm_Click(object sender, EventArgs e){string path = Server.MapPath("../xxx/xxx.doc");PrintClass printc = new PrintClass();printc.path = path;printc.filename = "xxxxx";string sql = string.Format(@"select xx1,xx2,xx3 from infoxinx");DataTable dtinfo = SqlData.ExecuteDataset(GetSetting(), CommandType.Text, sql).Tables[0];//链接数据库信息返回DataTableprintc.Print_InfoZdzm(dtinfo);}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息