C# 导出word文档及批量导出word文档(2)

时间:2023-03-09 08:29:13
C# 导出word文档及批量导出word文档(2)

aspose.word主要是通过把读取出来的数据放到datatable里,在datable里做相应的格式的调整,再导出到word文档里。mvc和webform最后导出的语句略有不同,在mvc的controller,用的是base.File,对应的是FileContentResult,在webform里用的是Response。写法分别为:

         //在WebForm中,保存文档到流中,使用Response. BinaryWrite输出该文件
         var docStream = new MemoryStream();
         doc.Save(docStream, SaveOptions.CreateSaveOptions(SaveFormat.Doc));
         Response.ContentType = "application/msword";
         Response.AddHeader("content-disposition", "attachment;  filename=Template.doc");
         Response.BinaryWrite(docStream.ToArray());
         Response.End();
        //在MVC中采用,保存文档到流中,使用base.File输出该文件
        var docStream = new MemoryStream();
        doc.Save(docStream, SaveOptions.CreateSaveOptions(SaveFormat.Doc));
        return base.File(docStream.ToArray(), "application/msword","Template.doc");
       本人的项目是基于mvc的,所以采用后者。
      首先项目需要对 aspose.word.dll进行添加引用, aspose.word.dll下载破解版的,版本过低会无法使用某些,如Aspose.Words.Saving等的相关属性,就没有SaveOptions.CreateSaveOptions方法,这个可以直接删掉,对基本的导出功能没有影响。之后将贴核心代码,代码都已经封装好,只需调用,传相关参数即可,后面解析代码的功能。
      本人创建了一个WordHelper类,定义了公共属性,因为只是当前类调用,所以设为了私有,调用首先需实例化模板,模板就是之前已经写好的word模板,同时还写了相应的方法转化为可以接受中文值,比如性别是数据表里是bool类型,用false or true来代表男女,导出时则需转化为对应的中文值:
 /// <summary>
/// 模板
/// </summary>
private string templateFile { get; set; }
private Document doc { get; set; }
private DocumentBuilder builder { get; set; }
#region 实例化模板
public WordHelper(string templateFile)
{
string templatePath = "Content/templates";
if (Path.GetExtension(templateFile) != ".doc") //如果传的模板参数没有扩展名,则加上扩展名
templateFile = templateFile + ".doc";
templateFile = WordFilePath.GetFilePath(templatePath, templateFile); //获取模板路径
doc = new Document(templateFile); //载入模板
builder = new DocumentBuilder(doc);
}
#endregion
#region 输出文件流
public MemoryStream DocStream
{
get
{
var docStream = new MemoryStream();
doc.Save(docStream, SaveOptions.CreateSaveOptions(SaveFormat.Doc));
return docStream;
}
}
#endregion
#region 转化为对应的中文值
/// <summary>
/// 转化为对应的中文值
/// </summary>
/// <param name="objName">值名称</param>
/// <param name="objValue">对应的值类型</param>
/// <returns></returns>
public static string SetChinaValue(object objName, object objValue)
{
object value = "";
if (!string.IsNullOrEmpty(objValue.ToString()))
{
if (Common.lstDictionaryCodes.Contains(objName)) //字典值
{
value = Common.GetDicName(Convert.ToInt32(objValue));
}
else if (Common.lstUserIDs.Contains(objName)) //人员档案
{
string[] strValue = objValue.ToString().Split(',');
for (int i = ; i < strValue.Length; i++)
{
value += Common.GetPersonName(strValue[i]) + ",";
}
value = !string.IsNullOrEmpty(value.ToString()) ? value.ToString().Substring(, value.ToString().Length - ) : "";
}
else if (objValue.GetType() == typeof(string))
{
value = objValue;
}
else if (objValue.GetType() == typeof(int) || objValue.GetType() == typeof(int?))
{
value = objValue;
}
else if (objValue.GetType() == typeof(DateTime) || objValue.GetType() == typeof(DateTime?))
{
value = Convert.ToDateTime(objValue).ToString("yyyy-MM-dd");
}
else if (objValue.GetType() == typeof(decimal) || objValue.GetType() == typeof(decimal?))
{
value = objValue;
}
else if (objValue.GetType() == typeof(bool) || objValue.GetType() == typeof(bool?))
{
if (objName.Equals("Sex"))
{
if (objValue.Equals(false))
value = "男";
else
value = "女";
}
else
{
if (objValue.Equals(true))
value = "☑是 □否";
else
value = "□是 ☑否";
}
}
}
return value.ToString();
}
#endregion
#region 保存文件名
/// <summary>
/// 保存文件名
/// </summary>
/// <param name="name">姓名</param>
/// <param name="value">编号</param>
/// <returns></returns>
public static string SaveDocName(string name, string value)
{
string oDoc = "";
if (!string.IsNullOrEmpty(name))
{
oDoc = name + "_" + value + ".doc";
}
else
{
oDoc = DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".doc";
}
return oDoc;
}
#endregion
#region 保存合并后的文档
public MemoryStream ExportDoc()
{
//保存合并后的文档
var docStream = new MemoryStream();
doc.Save(docStream, SaveOptions.CreateSaveOptions(SaveFormat.Doc));
return docStream;
}
#endregion #region 通过DataTable导出基本信息
/// <summary>
/// 获取导出文件的基本信息
/// </summary>
/// <param name="bllType">bll类</param>
/// <param name="dicWhere">查询条件</param>
/// <returns></returns>
public void GetBasicInfo(Type bllType, Dictionary<string, string> dicWhere)
{
try
{
NameValueCollection nvc = new NameValueCollection();
foreach (var item in dicWhere)
{
if (!string.IsNullOrEmpty(item.Key))
{
nvc.Add(item.Key, item.Value);
}
}
Assembly asmBLL = Assembly.Load(typeof(BLL.BLLBase).Namespace);
BLL.IBLLBase ibllBase = (BLL.IBLLBase)asmBLL.CreateInstance(bllType.FullName);
DataSet ds = ibllBase.GetData(nvc); //数据源
DataTable dt = CreateNewTable(bllType, ds.Tables[]); doc.MailMerge.FieldMergingCallback = new HandleMergeFieldInsertDocument(); //图片处理
doc.MailMerge.Execute(dt); //合并模版,相当于页面的渲染
}
catch (Exception)
{
throw;
}
}
#endregion #region 通过二维数组获取基本信息
/// <summary>
/// 通过二维数组获取基本信息
/// </summary>
/// <param name="bllType">bll类</param>
/// <param name="templateFile">导出模板</param>
/// <param name="dicWhere">查询条件</param>
/// <param name="lsField">导出的字段</param>
/// <returns></returns>
public void GetBasicInfo(Type bllType, Dictionary<string, string> dicWhere, List<string> lsField)
{
try
{
decimal count = ;
NameValueCollection nvc = new NameValueCollection();
foreach (var item in dicWhere)
{
if (!string.IsNullOrEmpty(item.Key))
{
nvc.Add(item.Key, item.Value);
}
}
Assembly asmBLL = Assembly.Load(typeof(BLL.BLLBase).Namespace);
BLL.IBLLBase ibllBase = (BLL.IBLLBase)asmBLL.CreateInstance(bllType.FullName);
DataSet ds = ibllBase.GetData(nvc); //数据源 String[] arrNames = lsField.ToArray();
Object[] objValues = new Object[arrNames.Length]; for (int j = ; j < arrNames.Length; j++)
{
if (ds.Tables[].Rows.Count > )
objValues[j] = SetChinaValue(arrNames[j], ds.Tables[].Rows[][arrNames[j]]);
else
objValues[j] = "";
}
doc.MailMerge.Execute(arrNames, objValues); //合并模版,相当于页面的渲染
}
catch (Exception)
{
throw;
}
}
#endregion #region 通过域循环导出table列表
/// <summary>
/// 通过域循环导出table列表
/// </summary>
/// <param name="bllType">bll类</param>
/// <param name="dicWhere">查询条件</param>
/// <param name="bookmark">模板书签</param>
public void GetTableList(Type bllType, Dictionary<string, string> dicWhere, string bookmark)
{
NameValueCollection nvc = new NameValueCollection();
foreach (var item in dicWhere)
{
if (!string.IsNullOrEmpty(item.Key))
{
nvc.Add(item.Key, item.Value);
}
}
Assembly asmBLL = Assembly.Load(typeof(BLL.BLLBase).Namespace);
BLL.IBLLBase ibllBase = (BLL.IBLLBase)asmBLL.CreateInstance(bllType.FullName);
DataSet ds = ibllBase.GetData(nvc); //数据源
DataTable dt = CreateNewTable(bllType, ds.Tables[], bookmark); //合并模版,相当于页面的渲染
doc.MailMerge.ExecuteWithRegions(dt);
}
#endregion
#region 通过书签来循环导出数据列表
/// <summary>
/// 通过书签来循环导出数据列表
/// </summary>
/// <param name="bllType">bll类</param>
/// <param name="dicWhere">查询条件</param>
/// <param name="dicOrderby">排序条件</param>
/// <param name="bookmark">模板循环列表书签</param>
public void GetListByMark(Type bllType, Dictionary<string, string> dicWhere, Dictionary<string, string> dicOrderby, string bookmark)
{
NameValueCollection nvc = new NameValueCollection();
foreach (var item in dicWhere)
{
if (!string.IsNullOrEmpty(item.Key))
{
nvc.Add(item.Key, item.Value);
}
}
NameValueCollection orderby = new NameValueCollection();
foreach (var item in dicOrderby) //查询条件
{
if (!string.IsNullOrEmpty(item.Key))
{
orderby.Add(item.Key, item.Value);
}
} Assembly asmBLL = Assembly.Load(typeof(BLL.BLLBase).Namespace);
BLL.IBLLBase ibllBase = (BLL.IBLLBase)asmBLL.CreateInstance(bllType.FullName);
DataTable dt = ibllBase.GetData(nvc, orderby).Tables[]; //数据源 int count = ;
//记录要显示多少列
for (var i = ; i < dt.Columns.Count; i++)
{
string strMark = dt.Columns[i].ColumnName.Trim();
if (doc.Range.Bookmarks[strMark] != null)
{
Bookmark mark = doc.Range.Bookmarks[strMark];
mark.Text = "";
count++;
}
}
List<string> listcolumn = new List<string>(count);
for (var i = ; i < count; i++)
{
builder.MoveToCell(, , i, ); //移动单元格
if (builder.CurrentNode.NodeType == NodeType.BookmarkStart)
{
listcolumn.Add((builder.CurrentNode as BookmarkStart).Name);
}
}
double width = builder.CellFormat.Width;//获取单元格宽度
if (doc.Range.Bookmarks[bookmark] != null)
{
builder.MoveToBookmark(bookmark); //开始添加值
for (var m = ; m < dt.Rows.Count; m++)
{
for (var i = ; i < listcolumn.Count; i++)
{
builder.InsertCell(); // 添加一个单元格
builder.CellFormat.Borders.LineStyle = LineStyle.Single;
builder.CellFormat.Borders.Color = System.Drawing.Color.Black;
builder.CellFormat.Width = width;
builder.CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.None;
builder.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;//垂直居中对齐
builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;//水平居中对齐
builder.Write(dt.Rows[m][listcolumn[i]].ToString());
}
builder.EndRow();
}
doc.Range.Bookmarks[bookmark].Text = "";
}
}
#endregion #region 创建DataTable,存放处理后的值进新的DataTable里
/// <summary>
/// 创建datatable
/// </summary>
/// <param name="dt">数据源</param>
/// <param name="bookmark">模板列表书签</param>
/// <returns></returns>
private DataTable CreateNewTable(Type t, DataTable dt, string bookmark = null)
{
DataTable TableList = new DataTable();
if (!string.IsNullOrEmpty(bookmark))
{
TableList.TableName = bookmark;
}
string strMark = "";
List<string> lsMark = new List<string>();
for (var i = ; i < dt.Columns.Count; i++)
{
strMark = dt.Columns[i].ColumnName.Trim();
TableList.Columns.Add(strMark);
//if (doc.Range.Bookmarks[strMark] != null) //按书签添加到新表
//{
// Bookmark mark = doc.Range.Bookmarks[strMark];
// mark.Remove();
// TableList.Columns.Add(strMark);
// lsMark.Add(strMark);
//}
} if (dt.Rows.Count > )
{
for (int i = ; i < dt.Rows.Count; i++)
{
DataRow dr = TableList.NewRow();
for (int j = ; j < dt.Columns.Count; j++)
{
dr[j] = SetChinaValue(dt.Columns[j].ColumnName, dt.Rows[i][j]);
}
TableList.Rows.Add(dr);
}
}
else //没有值时,直接赋值为"",去掉文档里的域值
{
DataRow dr = TableList.NewRow();
for (int j = ; j < dt.Columns.Count; j++)
{
if (t.Name == "PrejobTraining") //岗前培训为空时
{
dr[j] = "□是 □否";
}
else
{
dr[j] = "";
}
}
TableList.Rows.Add(dr);
}
return TableList;
}
#endregion
}
#endregion

WordHelper

其它相关辅助类:
   HandleMergeFieldInsertDocument 类

 #region 导出Word处理图片
/// <summary>
/// 导出Word处理图片
/// </summary>
public class HandleMergeFieldInsertDocument : IFieldMergingCallback
{
//文本处理在这里,如果写在这一块,则不起作用
void IFieldMergingCallback.FieldMerging(FieldMergingArgs e)
{
}
//图片处理在这里
void IFieldMergingCallback.ImageFieldMerging(ImageFieldMergingArgs args)
{
if (args.DocumentFieldName.Equals("Photo"))
{
// 使用DocumentBuilder处理图片的大小
DocumentBuilder builder = new DocumentBuilder(args.Document);
builder.MoveToMergeField(args.FieldName);
if (!string.IsNullOrEmpty((string)args.FieldValue))
{
string argsPath = HttpContext.Current.Server.MapPath(args.FieldValue.ToString());
if (System.IO.File.Exists(argsPath)) //找到文件才添加
{
Shape shape = builder.InsertImage(argsPath);
// 设置x,y坐标和高宽.
shape.Left = ;
shape.Top = ;
shape.Width = ;
shape.Height = ;
}
}
}
}
}
#endregion

HandleMergeFieldInsertDocument